The Error is here
lastrow = wsPOR.Range("A" & Rows.Count).End(xlUp).Row + 1
wsPOR is a workbook and not a worksheet. If you are working with "Sheet1" of that workbook then try this
lastrow = wsPOR.Sheets("Sheet1").Range("A" & _
wsPOR.Sheets("Sheet1").Rows.Count).End(xlUp).Row + 1
Similarly
wsPOR.Range("A2:G" & lastrow).Select
should be
wsPOR.Sheets("Sheet1").Range("A2:G" & lastrow).Select
this should be the most obvious and straight forward way
using (var dialog = new System.Windows.Forms.FolderBrowserDialog())
{
System.Windows.Forms.DialogResult result = dialog.ShowDialog();
if(result == System.Windows.Forms.DialogResult.OK)
{
selectedFolder = dialog.SelectedPath;
}
}
I think my answer to my own question here is the simplest solution to what you are trying to do:
Select the cell where the first line of text from the file should be.
Use the Data
/Get External Data
/From File
dialog to select the text file to import.
Format the imported text as required.
In the Import Data
dialog that opens, click on Properties...
Uncheck the Prompt for file name on refresh
box.
Whenever the external file changes, click the Data
/Get External Data
/Refresh All
button.
Note: in your case, you should probably want to skip step #5.
In the VBA Editor's Tools menu, click References... scroll down to "Microsoft Shell Controls And Automation" and choose it.
Sub FolderSelection()
Dim MyPath As String
MyPath = SelectFolder("Select Folder", "")
If Len(MyPath) Then
MsgBox MyPath
Else
MsgBox "Cancel was pressed"
End If
End Sub
'Both arguements are optional. The first is the dialog caption and
'the second is is to specify the top-most visible folder in the
'hierarchy. The default is "My Computer."
Function SelectFolder(Optional Title As String, Optional TopFolder _
As String) As String
Dim objShell As New Shell32.Shell
Dim objFolder As Shell32.Folder
'If you use 16384 instead of 1 on the next line,
'files are also displayed
Set objFolder = objShell.BrowseForFolder _
(0, Title, 1, TopFolder)
If Not objFolder Is Nothing Then
SelectFolder = objFolder.Items.Item.Path
End If
End Function
I agree John M has best answer to OP's question. Thought not explictly stated, the apparent purpose is to get a selected file name, whereas other answers return either counts or lists. I would add, however, that the msofiledialogfilepicker might be a better option in this case. ie:
Dim f As object
Set f = Application.FileDialog(msoFileDialogFilePicker)
dim varfile as variant
f.show
with f
.allowmultiselect = false
for each varfile in .selecteditems
msgbox varfile
next varfile
end with
Note: the value of varfile will remain the same since multiselect is false (only one item is ever selected). I used its value outside the loop with equal success. It's probably better practice to do it as John M did, however. Also, the folder picker can be used to get a selected folder. I always prefer late binding, but I think the object is native to the default access library, so it may not be necessary here
I know it has been a while since this was asked, but I learned an alternative yesterday
We all know you can do:
if(o instanceof String) { // etc
but what if you dont know exactly what type of class it needs to be? you cannot generically do:
if(o instanceof <Class variable>.getClass()) {
as it gives a compile error.
Instead, here is an alternative - isAssignableFrom()
For example:
public static boolean isASubClass(Class classTypeWeWant, Object objectWeHave) {
return classTypeWeWant.isAssignableFrom(objectWeHave.getClass())
}
You can run the query as:
select * from person where dob between '2011-01-01' and '2011-01-31 23:59:59'
like others pointed out, if your dates are hardcoded.
On the other hand, if the date is in another table, you can add a day and subtract a second (if the dates are saved without the second/time), like:
select * from person JOIN some_table ... where dob between some_table.initial_date and (some_table.final_date + INTERVAL 1 DAY - INTERVAL 1 SECOND)
Avoid doing casts on the dob
fiels (like in the accepted answer), because that can cause huge performance problems (like not being able to use an index in the dob
field, assuming there is one). The execution plan may change from using index condition
to using where
if you make something like DATE(dob)
or CAST(dob AS DATE)
, so be careful!
If using Vagrant try reloading your box. This solved my issue.
www.bitvise.com - sftpc is a good command line client also.
Try something like:
$post_data="dispnumber=567567567&extension=6";
$url="http://xxxxxxxx.xxx/xx/xx";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
echo $result;
If that is the case, I think you need to use a better way of creating a class name or a class name convention. For example, like you said you want the .container
class to have different color according to a specific usage or appearance. You can do this:
SCSS
.container {
background: red;
&--desc {
background: blue;
}
// or you can do a more specific name
&--blue {
background: blue;
}
&--red {
background: red;
}
}
CSS
.container {
background: red;
}
.container--desc {
background: blue;
}
.container--blue {
background: blue;
}
.container--red {
background: red;
}
The code above is based on BEM Methodology in class naming conventions. You can check this link: BEM — Block Element Modifier Methodology
I don't know if you can change the size at runtime but you can allocate the size at runtime. Try using this code:
class MyClass {
void myFunction () {
Scanner s = new Scanner (System.in);
int myArray [];
int x;
System.out.print ("Enter the size of the array: ");
x = s.nextInt();
myArray = new int[x];
}
}
this assigns your array size to be the one entered at run time into x.
It may be a problem with "From:" $email address in this part of the $headers:
From: \"$name\" <$email>
To try it out, send an email without the headers part, like:
mail('[email protected]', $subject, $message);
If that is a case, try using an email account that is already created at the system you are trying to send mail from.
Lodash _.isEqual
allows you to do that:
var_x000D_
remoteJSON = {"allowExternalMembers": "false", "whoCanJoin": "CAN_REQUEST_TO_JOIN"},_x000D_
localJSON = {"whoCanJoin": "CAN_REQUEST_TO_JOIN", "allowExternalMembers": "false"};_x000D_
_x000D_
console.log( _.isEqual(remoteJSON, localJSON) );
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
_x000D_
to your surprise, you do need to declare variable for workbook and worksheet in excel 2007 or later version. Just add single line expression.
Sub kl()
Set ws = ThisWorkbook.Sheets("name")
ws.select
End Sub
Remove everything else and enjoy. But why to select a sheet? selection of sheets is now old fashioned for calculation and manipulation. Just add formula like this
Sub kl()
Set ws = ThisWorkbook.Sheets("name")
ws.range("cell reference").formula = "your formula"
'OR in case you are using copy paste formula, just use 'insert or formula method instead of ActiveSheet.paste e.g.:
ws.range("your cell").formula
'or
ws.colums("your col: one col e.g. "A:A").insert
'if you need to clear the previous value, just add the following above insert line
ws.columns("your column").delete
End Sub
select * from tbl
where exists (select 1 from all_likes where all_likes.value = substr(tbl.my_col,0, length(tbl.my_col)))
1.downlad nvm
2.install chocolaty
3.change C:\Program Files\node to C:\Program Files\nodejsx
emphasized textThe first thing that we need to do is install NVM. website : https://docs.microsoft.com/en-us/windows/nodejs/setup-on-windows
I ended up writing a convenience method for our test-utils library
/**
* Utility method to test for a specific error class and message in Jest
* @param {fn, expectedErrorClass, expectedErrorMessage }
* @example failTest({
fn: () => {
return new MyObject({
param: 'stuff'
})
},
expectedErrorClass: MyError,
expectedErrorMessage: 'stuff not yet implemented'
})
*/
failTest: ({ fn, expectedErrorClass, expectedErrorMessage }) => {
try {
fn()
expect(true).toBeFalsy()
} catch (err) {
let isExpectedErr = err instanceof expectedErrorClass
expect(isExpectedErr).toBeTruthy()
expect(err.message).toBe(expectedErrorMessage)
}
}
TabLayout tab_layout = (TabLayout)findViewById(R.id.tab_Layout_);
private void changeTabsFont() {
Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/"+ Constants.FontStyle);
ViewGroup vg = (ViewGroup) tab_layout.getChildAt(0);
int tabsCount = vg.getChildCount();
for (int j = 0; j < tabsCount; j++) {
ViewGroup vgTab = (ViewGroup) vg.getChildAt(j);
int tabChildsCount = vgTab.getChildCount();
for (int i = 0; i < tabChildsCount; i++) {
View tabViewChild = vgTab.getChildAt(i);
if (tabViewChild instanceof TextView) {
((TextView) tabViewChild).setTypeface(font);
((TextView) tabViewChild).setTextSize(15);
}
}
}
}
This code is works for me using tablayout. It will change size of fonts and also change font style.
This will also help you guys please check this link
https://stackoverflow.com/a/43156384/5973946
This code works for Tablayout change text color,type face (font style) and also text size.
For its base array class, 2d arrays are no more special than 1d or 3d ones. There are some operations the preserve the dimensions, some that reduce them, other combine or even expand them.
M=np.arange(9).reshape(3,3)
M[:,0].shape # (3,) selects one column, returns a 1d array
M[0,:].shape # same, one row, 1d array
M[:,[0]].shape # (3,1), index with a list (or array), returns 2d
M[:,[0,1]].shape # (3,2)
In [20]: np.dot(M[:,0].reshape(3,1),np.ones((1,3)))
Out[20]:
array([[ 0., 0., 0.],
[ 3., 3., 3.],
[ 6., 6., 6.]])
In [21]: np.dot(M[:,[0]],np.ones((1,3)))
Out[21]:
array([[ 0., 0., 0.],
[ 3., 3., 3.],
[ 6., 6., 6.]])
Other expressions that give the same array
np.dot(M[:,0][:,np.newaxis],np.ones((1,3)))
np.dot(np.atleast_2d(M[:,0]).T,np.ones((1,3)))
np.einsum('i,j',M[:,0],np.ones((3)))
M1=M[:,0]; R=np.ones((3)); np.dot(M1[:,None], R[None,:])
MATLAB started out with just 2D arrays. Newer versions allow more dimensions, but retain the lower bound of 2. But you still have to pay attention to the difference between a row matrix and column one, one with shape (1,3)
v (3,1)
. How often have you written [1,2,3].'
? I was going to write row vector
and column vector
, but with that 2d constraint, there aren't any vectors in MATLAB - at least not in the mathematical sense of vector as being 1d.
Have you looked at np.atleast_2d
(also _1d and _3d versions)?
If you make both dates NSDate
s you can use NSDate
's compare:
method:
NSComparisonResult result = [Date2 compare:Date1];
if(result==NSOrderedAscending)
NSLog(@"Date1 is in the future");
else if(result==NSOrderedDescending)
NSLog(@"Date1 is in the past");
else
NSLog(@"Both dates are the same");
You can take a look at the docs here.
Came here to see how to append an item to a 2D array, but the title of the thread is a bit misleading because it is exploring an issue with the appending.
The easiest way I found to append to a 2D list is like this:
list=[[]]
list.append((var_1,var_2))
This will result in an entry with the 2 variables var_1, var_2. Hope this helps!
Simply put:
SELECT *
FROM TABLE_NAME
WHERE
dob > '1/21/2012'
Where 1/21/2012 is the date and you want all data, including that date.
SELECT *
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'
Use a between if you're selecting time between two dates
Since Webpack v4, simply setting mode
in your Webpack config will set the NODE_ENV
for you (via DefinePlugin
). Docs here.
If you need to interact directly with the DOM element, why not just use document.getElementById
since, if you are trying to interact with a specific element you will probably know the id, as assuming that the classname is on only one element or some other option tends to be risky.
But, I tend to agree with the others, that in most cases you should learn to do what you need using what jQuery gives you, as it is very flexible.
UPDATE: Based on a comment: Here is a post with a nice explanation: http://www.mail-archive.com/[email protected]/msg04461.html
$(this).attr("checked") ? $(this).val() : 0
This will return the value if it's checked, or 0 if it's not.
$(this).val()
is just reaching into the dom and getting the attribute "value" of the element, whether or not it's checked.
int get_int_len (int value){
int l=1;
while(value>9){ l++; value/=10; }
return l;
}
and second one will work for negative numbers too:
int get_int_len_with_negative_too (int value){
int l=!value;
while(value){ l++; value/=10; }
return l;
}
If one of you guys are using virtual terminal in proteus and want to clear it just add Serial.write(0x0C); and it gonna work fine
Use jQuery multiple-selector if the only difference between the two functions is the value of the button being triggered.
$("#button_1, #button_2").on("click", function(e) {
e.preventDefault();
$.ajax({type: "POST",
url: "/pages/test/",
data: { id: $(this).val(), access_token: $("#access_token").val() },
success:function(result) {
alert('ok');
},
error:function(result) {
alert('error');
}
});
});
After your comments this actually makes perfect sense why you don't get a histogram of each different value. There are 1.4 million rows, and ten discrete buckets. So apparently each bucket is exactly 10% (to within what you can see in the plot).
A quick rerun of your data:
In [25]: df.hist(column='Trip_distance')
Prints out absolutely fine.
The df.hist
function comes with an optional keyword argument bins=10
which buckets the data into discrete bins. With only 10 discrete bins and a more or less homogeneous distribution of hundreds of thousands of rows, you might not be able to see the difference in the ten different bins in your low resolution plot:
In [34]: df.hist(column='Trip_distance', bins=50)
I think this will do what you need:
var uri = new Uri(hreflink);
var filename = uri.Segments.Last();
Try jQuery:
$("#banner-contenedor").width();
Yes, jQuery
can be used with Node.js
.
Steps to include jQuery in node project:-
npm i jquery --save
Include jquery in codes
import jQuery from 'jquery';
const $ = jQuery;
I do use jquery in node.js projects all the time specifically in the chrome extension's project.
e.g. https://github.com/fxnoob/gesture-control-chrome-extension/blob/master/src/default_plugins/tab.js
In the end, you only have two options:
You generate your content using Doxygen, or you generate your content using Sphinx*.
Doxygen: It is not the tool of choice for most Python projects. But if you have to deal with other related projects written in C or C++ it could make sense. For this you can improve the integration between Doxygen and Python using doxypypy.
Sphinx: The defacto tool for documenting a Python project. You have three options here: manual, semi-automatic (stub generation) and fully automatic (Doxygen like).
autosummary_generate
config. You will require to setup a page with the autosummaries, and then manually edit the pages. You have options, but my experience with this approach is that it requires way too much configuration, and at the end even after creating new templates, I found bugs and the impossibility to determine exactly what was exposed as public API and what not. My opinion is this tool is good for stub generation that will require manual editing, and nothing more. Is like a shortcut to end up in manual.There are other options to note:
https://docs.mongodb.com/manual/reference/sql-comparison/
http://php.net/manual/en/mongo.sqltomongo.php
MySQL
SELECT * FROM users WHERE username LIKE "%Son%"
MongoDB
db.users.find({username:/Son/})
You need the python-dev
package which contains Python.h
The answers as they are require you to add code to the spawned window. That is unnecessary coupling.
// In parent window
var pop = open(url);
pop.onunload = function() {
// Run your code, the popup window is unloading
// Beware though, this will also fire if the user navigates to a different
// page within thepopup. If you need to support that, you will have to play around
// with pop.closed and setTimeouts
}
Boolean(val) === false. This worked for me to check if value was falsely.
In this public Github repo https://github.com/boskjoett/BasicAuthWebApi you can see a simple example of a ASP.NET Core 2.2 web API with endpoints protected by Basic Authentication.
Your syntax error is caused by a missing "table" in the query
ALTER TABLE mytable MODIFY mycolumn varchar(255) null;
Had the same issue and got curious about the performance of each solution.
Here's is the %timeit
:
import numpy as np
lst = [['a','b','c'], [1,2,3], ['x','y','z']]
The first numpy-way, transforming the array:
%timeit list(np.array(lst).T[0])
4.9 µs ± 163 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Fully native using list comprehension (as explained by @alecxe):
%timeit [item[0] for item in lst]
379 ns ± 23.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Another native way using zip
(as explained by @dawg):
%timeit list(zip(*lst))[0]
585 ns ± 7.26 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Second numpy-way. Also explained by @dawg:
%timeit list(np.array(lst)[:,0])
4.95 µs ± 179 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Surprisingly (well, at least for me) the native way using list comprehension is the fastest and about 10x faster than the numpy-way. Running the two numpy-ways without the final list
saves about one µs which is still in the 10x difference.
Note that, when I surrounded each code snippet with a call to len
, to ensure that Generators run till the end, the timing stayed the same.
How about something like this, by passing ID of the element and it will return the left or top, we can also combine them:
1) find left
function findLeft(element) {
var rec = document.getElementById(element).getBoundingClientRect();
return rec.left + window.scrollX;
} //call it like findLeft('#header');
2) find top
function findTop(element) {
var rec = document.getElementById(element).getBoundingClientRect();
return rec.top + window.scrollY;
} //call it like findTop('#header');
or 3) find left and top together
function findTopLeft(element) {
var rec = document.getElementById(element).getBoundingClientRect();
return {top: rec.top + window.scrollY, left: rec.left + window.scrollX};
} //call it like findTopLeft('#header');
Choose either:
a) Create not null with some valid default value
b) Create null, fill it, alter to not null
use the builtin: (no need for tkinter)
s = input('->>')
print(s) # what you just typed); now use if's
Use six
:
from six.moves.urllib.parse import quote
six
will simplify compatibility problems between Python 2 and Python 3, such as different import paths.
To justify the bootstrap 3 navbar-nav justify menu to 100% width you can use this code:
@media (min-width: 768px){
.navbar-nav {
margin: 0 auto;
display: table;
table-layout: auto;
float: none;
width: 100%;
}
.navbar-nav>li {
display: table-cell;
float: none;
text-align: center;
}
}
Good references to the docs. Here's how you can guarantee the order regardless of the documentation / implementation:
k, v = zip(*d.iteritems())
if ($.inArray('yourElement', yourArray) > -1)
{
//yourElement in yourArray
//code here
}
Reference: Jquery Array
The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0.
I know this is very late, but maybe this will help someone else.
I use a Cancel button to return to the referring url. In the View, try adding this:
@{
ViewBag.Title = "Page title";
Layout = "~/Views/Shared/_Layout.cshtml";
if (Request.UrlReferrer != null)
{
string returnURL = Request.UrlReferrer.ToString();
ViewBag.ReturnURL = returnURL;
}
}
Then you can set your buttons href like this:
<a href="@ViewBag.ReturnURL" class="btn btn-danger">Cancel</a>
Other than that, the update by Jason Enochs works great!
I think you need to do is to transform your data from object not to JSON string, but to url params.
By default, the $http service will transform the outgoing request by serializing the data as JSON and then posting it with the content- type, "application/json". When we want to post the value as a FORM post, we need to change the serialization algorithm and post the data with the content-type, "application/x-www-form-urlencoded".
Example from here.
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {username: $scope.userName, password: $scope.password}
}).then(function () {});
To use new services added with AngularJS V1.4, see
text()
and node()
are node tests, in XPath terminology (compare).
Node tests operate on a set (on an axis, to be exact) of nodes and return the ones that are of a certain type. When no axis is mentioned, the child
axis is assumed by default.
There are all kinds of node tests:
node()
matches any node (the least specific node test of them all)text()
matches text nodes onlycomment()
matches comment nodes*
matches any element nodefoo
matches any element node named "foo"
processing-instruction()
matches PI nodes (they look like <?name value?>
).*
also matches attribute nodes, but only along the attribute
axis. @*
is a shorthand for attribute::*
. Attributes are not part of the child
axis, that's why a normal *
does not select them.This XML document:
<produce>
<item>apple</item>
<item>banana</item>
<item>pepper</item>
</produce>
represents the following DOM (simplified):
root node element node (name="produce") text node (value="\n ") element node (name="item") text node (value="apple") text node (value="\n ") element node (name="item") text node (value="banana") text node (value="\n ") element node (name="item") text node (value="pepper") text node (value="\n")
So with XPath:
/
selects the root node/produce
selects a child element of the root node if it has the name "produce"
(This is called the document element; it represents the document itself. Document element and root node are often confused, but they are not the same thing.) /produce/node()
selects any type of child node beneath /produce/
(i.e. all 7 children)/produce/text()
selects the 4 (!) whitespace-only text nodes/produce/item[1]
selects the first child element named "item"
/produce/item[1]/text()
selects all child text nodes (there's only one - "apple" - in this case)And so on.
So, your questions
/produce/item/text()
(3 nodes selected)//department/manager
(1 node selected)Notes
child
axis. You can change the axis by prefixing a different axis name. For example: //item/ancestor::produce
/produce/item[1]/text()
and string(/produce/item[1])
will be the same.About "can it be that 0 errors and IsValid == false": here's MVC source code from https://github.com/Microsoft/referencesource/blob/master/System.Web/ModelBinding/ModelStateDictionary.cs#L37-L41
public bool IsValid {
get {
return Values.All(modelState => modelState.Errors.Count == 0);
}
}
Now, it looks like it can't be. Well, that's for ASP.NET MVC v1.
Ozi, when you create a new datetime object as in datetime foo = new datetime(); foo is constructed with the time datetime.minvalue() in building a parameterized query, you could check to see if the values entered are equal to datetime.minvalue()
-Just a side thought. seems you have things working.
I was struggling with this problem, and I learned (thanks to this post) that:
div:first-child {_x000D_
opacity: .99; _x000D_
}_x000D_
_x000D_
.red, .green, .blue {_x000D_
position: absolute;_x000D_
width: 100px;_x000D_
color: white;_x000D_
line-height: 100px;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
.red {_x000D_
z-index: 1;_x000D_
top: 20px;_x000D_
left: 20px;_x000D_
background: red;_x000D_
}_x000D_
_x000D_
.green {_x000D_
top: 60px;_x000D_
left: 60px;_x000D_
background: green;_x000D_
}_x000D_
_x000D_
.blue {_x000D_
top: 100px;_x000D_
left: 100px;_x000D_
background: blue;_x000D_
}
_x000D_
<div>_x000D_
<span class="red">Red</span>_x000D_
</div>_x000D_
<div>_x000D_
<span class="green">Green</span>_x000D_
</div>_x000D_
<div>_x000D_
<span class="blue">Blue</span>_x000D_
</div>
_x000D_
Open your system command prompt/terminal -> Go to your Project folder path (root project folder ) -> Execute following command : command :- gradlew clean
or ./gradlew clean
Make sure that all your gradle dependencies are of same version. -> Example :- your appcompat and recyclerview dependencies should have same version.
-> Change your gradle dependencies to same version like :-
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.android.support:design:23.4.0'
compile 'com.android.support:recyclerview-v7:23.4.0'
compile 'com.android.support:cardview-v7:23.4.0'
-> Rebuild your project and it will work fine.
Write static a method into some utility class, which accept string as parameter and return the decoded html string.
Include the using System.Web.HttpUtility
into your class
public static string HtmlEncode(string text)
{
if(text.length > 0){
return HttpUtility.HtmlDecode(text);
}else{
return text;
}
}
Not sure if you're talking about Coverflow (scroll through images) or Quicklook (preview files in lightbox), try editing your question.
Here's some JS Coverflow implementations:
1. Without plugin
class IndiSampleState extends State<ProgHudPage> {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Demo'),
),
body: Center(
child: RaisedButton(
color: Colors.blueAccent,
child: Text('Login'),
onPressed: () async {
showDialog(
context: context,
builder: (BuildContext context) {
return Center(child: CircularProgressIndicator(),);
});
await loginAction();
Navigator.pop(context);
},
),
));
}
Future<bool> loginAction() async {
//replace the below line of code with your login request
await new Future.delayed(const Duration(seconds: 2));
return true;
}
}
2. With plugin
check this plugin progress_hud
add the dependency in the pubspec.yaml file
dev_dependencies:
progress_hud:
import the package
import 'package:progress_hud/progress_hud.dart';
Sample code is given below to show and hide the indicator
class ProgHudPage extends StatefulWidget {
@override
_ProgHudPageState createState() => _ProgHudPageState();
}
class _ProgHudPageState extends State<ProgHudPage> {
ProgressHUD _progressHUD;
@override
void initState() {
_progressHUD = new ProgressHUD(
backgroundColor: Colors.black12,
color: Colors.white,
containerColor: Colors.blue,
borderRadius: 5.0,
loading: false,
text: 'Loading...',
);
super.initState();
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('ProgressHUD Demo'),
),
body: new Stack(
children: <Widget>[
_progressHUD,
new Positioned(
child: RaisedButton(
color: Colors.blueAccent,
child: Text('Login'),
onPressed: () async{
_progressHUD.state.show();
await loginAction();
_progressHUD.state.dismiss();
},
),
bottom: 30.0,
right: 10.0)
],
));
}
Future<bool> loginAction()async{
//replace the below line of code with your login request
await new Future.delayed(const Duration(seconds: 2));
return true;
}
}
Can't you just use <span contenteditable="true" spellcheck="false">
element in place of <input type="text">
?
<span>
(with contenteditable="true" spellcheck="false"
as attributes) distincts by <input>
mainly because:
<input>
.value
property, but the text is rendered as innerText
and makes part of its inner body. <input>
isn't although you set the attribute multiline="true"
.To accomplish the appearance you can, of course, style it in CSS, whereas writing the value as innerText
you can get for it an event:
Here's a fiddle.
Unfortunately there's something that doesn't actually work in IE and Edge, which I'm unable to find.
[INFO] BUILD SUCCESS
Anyway, it works for me:)
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF8
You can also do this with pandas by broadcasting your columns as categories first, e.g. dtype="category"
e.g.
cats = ['client', 'hotel', 'currency', 'ota', 'user_country']
df[cats] = df[cats].astype('category')
and then calling describe
:
df[cats].describe()
This will give you a nice table of value counts and a bit more :):
client hotel currency ota user_country
count 852845 852845 852845 852845 852845
unique 2554 17477 132 14 219
top 2198 13202 USD Hades US
freq 102562 8847 516500 242734 340992
The first problem is that when you call append on a jQuery set with more than one element, a clone of the element to append is created for each and thus the attached event observer is lost.
An alternative way to do it would be to create the link for each element:
function handler() { alert('hello'); }
$('.add_to_this').append(function() {
return $('<a>Click here</a>').click(handler);
})
Another potential problem might be that the event observer is attached before the element has been added to the DOM. I'm not sure if this has anything to say, but I think the behavior might be considered undetermined. A more solid approach would probably be:
function handler() { alert('hello'); }
$('.add_to_this').each(function() {
var link = $('<a>Click here</a>');
$(this).append(link);
link.click(handler);
});
You could actually just set the image of the UIButton
to what you would normally put in a UIImageView
. For example, where you would do:
myImageView.image = myUIImage
You could instead use:
myButton.setImage(myUIImage, forState: UIControlState.Normal)
So, here's what your code could look like:
override func viewDidLoad(){
super.viewDidLoad()
var myUIImage: UIImage //set the UIImage here
myButton.setImage(myUIImage, forState: UIControlState.Normal)
}
@IBOutlet var myButton: UIButton!
@IBAction func buttonTap(sender: UIButton!){
//handle the image tap
}
The great thing about using this method is that if you have to load the image from a database, you could set the title of the button before you set the image:
myButton.setTitle("Loading Image...", forState: UIControlState.Normal)
To tell your users that you are loading the image
You may simply use both as per the specification kindly provided by Oli.
I always use border:0 none;
.
Though there is no harm in specifying them seperately and some browsers will parse the CSS faster if you do use the legacy CSS1 property calls.
Though border:0;
will normally default the border style to none
, I have however noticed some browsers enforcing their default border style which can strangely overwrite border:0;
.
As long as you're increasing the size of your varchar you're OK. As per the Alter Table reference:
Reducing the precision or scale of a column may cause data truncation.
Live example of Curl command to send OPTIONS requests: https://reqbin.com/req/c-d8nxa0fl
Use a .gitignore file. This allows you to ignore certain files. http://git-scm.com/docs/gitignore
Here's an example Eclipse one, which handles your classpath and project files: https://github.com/github/gitignore/blob/master/Global/Eclipse.gitignore
At the time when this question was asked there wasn't another function in Pandas to test equality, but it has been added a while ago: pandas.equals
You use it like this:
df1.equals(df2)
Some differenes to ==
are:
dtype
to be considered equal, see this stackoverflow questionIn R2013b or later you can use a table:
>> table = readtable('myfile.txt','Delimiter',';','ReadVariableNames',false)
>> table =
Var1 Var2 Var3 Var4 Var5 Var6 Var7 Var8 Var9 Var10
____ _____ _____ _____ _____ __________ __________ ________ ____ _____
4 'abc' 'def' 'ghj' 'klm' '' '' '' NaN NaN
NaN '' '' '' '' 'Test' 'text' '0xFF' NaN NaN
NaN '' '' '' '' 'asdfhsdf' 'dsafdsag' '0x0F0F' NaN NaN
Here is more info.
Use VerticalScrollBar
with the TextBlock
control in WPF. In your code behind, add the following code:
In the constructor, define an event handler for the scrollbar:
scrollBar1.ValueChanged += new RoutedPropertyChangedEventHandler<double>(scrollBar1_ValueChanged);
scrollBar1.Minimum = 0;
scrollBar1.Maximum = 1;
scrollBar1.SmallChange = 0.1;
Then in the event handler, add:
void scrollBar1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
FteHolderText.Text = scrollBar1.Value.ToString();
}
Here is the original snippet from my code... make necessary changes.. :)
public NewProjectPlan()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(NewProjectPlan_Loaded);
scrollBar1.ValueChanged += new RoutedPropertyChangedEventHandler<double>(scrollBar1_ValueChanged);
scrollBar1.Minimum = 0;
scrollBar1.Maximum = 1;
scrollBar1.SmallChange = 0.1;
// etc...
}
void scrollBar1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
FteHolderText.Text = scrollBar1.Value.ToString();
}
macOS 10.15.7
Prefrences...
Window
tabScrollback
to Limit number of rows to:
what your wanted.That would be the destructor(freeing up any dynamic memory)
There's an easier way, have a link table, i.e.:
Table 1: clients, client info, blah blah blah
Table 2: courses, course info, blah blah
Table 3: clientid, courseid
Then do a JOIN and you're off to the races.
The point for diamond operator is simply to reduce typing of code when declaring generic types. It doesn't have any effect on runtime whatsoever.
The only difference if you specify in Java 5 and 6,
List<String> list = new ArrayList();
is that you have to specify @SuppressWarnings("unchecked")
to the list
(otherwise you will get an unchecked cast warning). My understanding is that diamond operator is trying to make development easier. It's got nothing to do on runtime execution of generics at all.
As BalusC indicated, the actionListener
by default swallows exceptions, but in JSF 2.0 there is a little more to this. Namely, it doesn't just swallows and logs, but actually publishes the exception.
This happens through a call like this:
context.getApplication().publishEvent(context, ExceptionQueuedEvent.class,
new ExceptionQueuedEventContext(context, exception, source, phaseId)
);
The default listener for this event is the ExceptionHandler
which for Mojarra is set to com.sun.faces.context.ExceptionHandlerImpl
. This implementation will basically rethrow any exception, except when it concerns an AbortProcessingException, which is logged. ActionListeners wrap the exception that is thrown by the client code in such an AbortProcessingException which explains why these are always logged.
This ExceptionHandler
can be replaced however in faces-config.xml with a custom implementation:
<exception-handlerfactory>
com.foo.myExceptionHandler
</exception-handlerfactory>
Instead of listening globally, a single bean can also listen to these events. The following is a proof of concept of this:
@ManagedBean
@RequestScoped
public class MyBean {
public void actionMethod(ActionEvent event) {
FacesContext.getCurrentInstance().getApplication().subscribeToEvent(ExceptionQueuedEvent.class, new SystemEventListener() {
@Override
public void processEvent(SystemEvent event) throws AbortProcessingException {
ExceptionQueuedEventContext content = (ExceptionQueuedEventContext)event.getSource();
throw new RuntimeException(content.getException());
}
@Override
public boolean isListenerForSource(Object source) {
return true;
}
});
throw new RuntimeException("test");
}
}
(note, this is not how one should normally code listeners, this is only for demonstration purposes!)
Calling this from a Facelet like this:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:body>
<h:form>
<h:commandButton value="test" actionListener="#{myBean.actionMethod}"/>
</h:form>
</h:body>
</html>
Will result in an error page being displayed.
This is late but this may help someone :) :) For adding the view programmatically try like
LinearLayout rlmain = new LinearLayout(this);
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.FILL_PARENT);
LinearLayout ll1 = new LinearLayout (this);
ImageView iv = new ImageView(this);
iv.setImageResource(R.drawable.logo);
LinearLayout .LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
iv.setLayoutParams(lp);
ll1.addView(iv);
rlmain.addView(ll1);
setContentView(rlmain, llp);
This will create your entire view programmatcally. You can add any number of view as same. Hope this may help. :)
I also had this problem running unit tests by using ReSharper on Visual Studio 2017 and fixed it with following config:
Also you can change the ReSharper's run test setting: https://resharper-support.jetbrains.com/hc/en-us/articles/207242715-How-to-run-MSTest-tests-using-x64-configuration
I tried to fix the 'no public DNS' once the EC2 was up and running, I couldnt add a public DNS
this is even after following the above steps making mods to the VPC or the Subnet
so, I had to make modifications to the subnet and the vpc, before starting another instance, and THEN start up a new instance.
the new instance had a public DNS. That is how it worked for me.
In my case, I use Symfony2.3.x and the minimum-stability parameter is by default "stable" (which is good). I wanted to import a repo not in packagist but had the same issue "Your requirements could not be resolved to an installable set of packages.". It appeared that the composer.json in the repo I tried to import use a minimum-stability "dev".
So to resolve this issue, don't forget to verify the minimum-stability
. I solved it by requiring a dev-master
version instead of master
as stated in this post.
I'll give 4 solutions:
cryptography
libraryHere is a solution using the package cryptography
, that you can install as usual with pip install cryptography
:
import base64
from cryptography.fernet import Fernet, InvalidToken
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
def cipherFernet(password):
key = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=b'abcd', iterations=1000, backend=default_backend()).derive(password)
return Fernet(base64.urlsafe_b64encode(key))
def encrypt1(plaintext, password):
return cipherFernet(password).encrypt(plaintext)
def decrypt1(ciphertext, password):
return cipherFernet(password).decrypt(ciphertext)
# Example:
print(encrypt1(b'John Doe', b'mypass'))
# b'gAAAAABd53tHaISVxFO3MyUexUFBmE50DUV5AnIvc3LIgk5Qem1b3g_Y_hlI43DxH6CiK4YjYHCMNZ0V0ExdF10JvoDw8ejGjg=='
print(decrypt1(b'gAAAAABd53tHaISVxFO3MyUexUFBmE50DUV5AnIvc3LIgk5Qem1b3g_Y_hlI43DxH6CiK4YjYHCMNZ0V0ExdF10JvoDw8ejGjg==', b'mypass'))
# b'John Doe'
try: # test with a wrong password
print(decrypt1(b'gAAAAABd53tHaISVxFO3MyUexUFBmE50DUV5AnIvc3LIgk5Qem1b3g_Y_hlI43DxH6CiK4YjYHCMNZ0V0ExdF10JvoDw8ejGjg==', b'wrongpass'))
except InvalidToken:
print('Wrong password')
You can adapt with your own salt, iteration count, etc. This code is not very far from @HCLivess's answer but the goal is here to have ready-to-use encrypt
and decrypt
functions. Source: https://cryptography.io/en/latest/fernet/#using-passwords-with-fernet.
Note: use .encode()
and .decode()
everywhere if you want strings 'John Doe'
instead of bytes like b'John Doe'
.
Crypto
libraryThis works with Python 3:
import base64
from Crypto import Random
from Crypto.Hash import SHA256
from Crypto.Cipher import AES
def cipherAES(password, iv):
key = SHA256.new(password).digest()
return AES.new(key, AES.MODE_CFB, iv)
def encrypt2(plaintext, password):
iv = Random.new().read(AES.block_size)
return base64.b64encode(iv + cipherAES(password, iv).encrypt(plaintext))
def decrypt2(ciphertext, password):
d = base64.b64decode(ciphertext)
iv, ciphertext = d[:AES.block_size], d[AES.block_size:]
return cipherAES(password, iv).decrypt(ciphertext)
# Example:
print(encrypt2(b'John Doe', b'mypass'))
print(decrypt2(b'B/2dGPZTD8V22cIVKfp2gD2tTJG/UfP/', b'mypass'))
print(decrypt2(b'B/2dGPZTD8V22cIVKfp2gD2tTJG/UfP/', b'wrongpass')) # wrong password: no error, but garbled output
Note: you can remove base64.b64encode
and .b64decode
if you don't want text-readable output and/or if you want to save the ciphertext to disk as a binary file anyway.
Crypto
libraryThe solution 2) with AES "CFB mode" is ok, but has two drawbacks: the fact that SHA256(password)
can be easily bruteforced with a lookup table, and that there is no way to test if a wrong password has been entered. This is solved here by the use of AES in "GCM mode", as discussed in AES: how to detect that a bad password has been entered? and Is this method to say “The password you entered is wrong” secure?:
import Crypto.Random, Crypto.Protocol.KDF, Crypto.Cipher.AES
def cipherAES_GCM(pwd, nonce):
key = Crypto.Protocol.KDF.PBKDF2(pwd, nonce, count=100000)
return Crypto.Cipher.AES.new(key, Crypto.Cipher.AES.MODE_GCM, nonce=nonce, mac_len=16)
def encrypt3(plaintext, password):
nonce = Crypto.Random.new().read(16)
return nonce + b''.join(cipherAES_GCM(password, nonce).encrypt_and_digest(plaintext)) # you case base64.b64encode it if needed
def decrypt3(ciphertext, password):
nonce, ciphertext, tag = ciphertext[:16], ciphertext[16:len(ciphertext)-16], ciphertext[-16:]
return cipherAES_GCM(password, nonce).decrypt_and_verify(ciphertext, tag)
# Example:
print(encrypt3(b'John Doe', b'mypass'))
print(decrypt3(b'\xbaN_\x90R\xdf\xa9\xc7\xd6\x16/\xbb!\xf5Q\xa9]\xe5\xa5\xaf\x81\xc3\n2e/("I\xb4\xab5\xa6ezu\x8c%\xa50', b'mypass'))
try:
print(decrypt3(b'\xbaN_\x90R\xdf\xa9\xc7\xd6\x16/\xbb!\xf5Q\xa9]\xe5\xa5\xaf\x81\xc3\n2e/("I\xb4\xab5\xa6ezu\x8c%\xa50', b'wrongpass'))
except ValueError:
print("Wrong password")
Adapted from https://github.com/bozhu/RC4-Python/blob/master/rc4.py.
def PRGA(S):
i = 0
j = 0
while True:
i = (i + 1) % 256
j = (j + S[i]) % 256
S[i], S[j] = S[j], S[i]
yield S[(S[i] + S[j]) % 256]
def encryptRC4(plaintext, key, hexformat=False):
key, plaintext = bytearray(key), bytearray(plaintext) # necessary for py2, not for py3
S = list(range(256))
j = 0
for i in range(256):
j = (j + S[i] + key[i % len(key)]) % 256
S[i], S[j] = S[j], S[i]
keystream = PRGA(S)
return b''.join(b"%02X" % (c ^ next(keystream)) for c in plaintext) if hexformat else bytearray(c ^ next(keystream) for c in plaintext)
print(encryptRC4(b'John Doe', b'mypass')) # b'\x88\xaf\xc1\x04\x8b\x98\x18\x9a'
print(encryptRC4(b'\x88\xaf\xc1\x04\x8b\x98\x18\x9a', b'mypass')) # b'John Doe'
(Outdated since the latest edits, but kept for future reference): I had problems using Windows + Python 3.6 + all the answers involving pycrypto
(not able to pip install pycrypto
on Windows) or pycryptodome
(the answers here with from Crypto.Cipher import XOR
failed because XOR
is not supported by this pycrypto
fork ; and the solutions using ... AES
failed too with TypeError: Object type <class 'str'> cannot be passed to C code
). Also, the library simple-crypt
has pycrypto
as dependency, so it's not an option.
If you are using C99 just include stdint.h
. BTW, the 64bit types are there iff the processor supports them.
Since version 1.3.0
AngularJS introduced extra filter parameter timezone
, like following:
{{ date_expression | date : format : timezone}}
But in versions 1.3.x
only supported timezone is UTC
, which can be used as following:
{{ someDate | date: 'MMM d, y H:mm:ss' : 'UTC' }}
Since version 1.4.0-rc.0
AngularJS supports other timezones too. I was not testing all possible timezones, but here's for example how you can get date in Japan Standard Time (JSP, GMT +9):
{{ clock | date: 'MMM d, y H:mm:ss' : '+0900' }}
Here you can find documentation of AngularJS date filters.
NOTE: this is working only with Angular 1.x
Here's working example
Swift 4:
let attributes = [NSAttributedStringKey.font: UIFont(name: "HelveticaNeue-Bold", size: 17)!,
NSAttributedStringKey.foregroundColor: UIColor.white]
private String getApplicationName(Context context, String data, int flag) {
final PackageManager pckManager = context.getPackageManager();
ApplicationInfo applicationInformation;
try {
applicationInformation = pckManager.getApplicationInfo(data, flag);
} catch (PackageManager.NameNotFoundException e) {
applicationInformation = null;
}
final String applicationName = (String) (applicationInformation != null ? pckManager.getApplicationLabel(applicationInformation) : "(unknown)");
return applicationName;
}
A compact, flexible method for timestamps without fractional seconds would be:
SELECT * FROM table_name
WHERE field_name
BETWEEN UNIX_TIMESTAMP('2010-10-01') AND UNIX_TIMESTAMP('2010-10-31 23:59:59')
If you are using fractional seconds and a recent version of MySQL then you would be better to take the approach of using the >=
and <
operators as per Wouter's answer.
Here is an example of temporal fields defined with fractional second precision (maximum precision in use):
mysql> create table time_info (t_time time(6), t_datetime datetime(6), t_timestamp timestamp(6), t_short timestamp null);
Query OK, 0 rows affected (0.02 sec)
mysql> insert into time_info set t_time = curtime(6), t_datetime = now(6), t_short = t_datetime;
Query OK, 1 row affected (0.01 sec)
mysql> select * from time_info;
+-----------------+----------------------------+----------------------------+---------------------+
| 22:05:34.378453 | 2016-01-11 22:05:34.378453 | 2016-01-11 22:05:34.378453 | 2016-01-11 22:05:34 |
+-----------------+----------------------------+----------------------------+---------------------+
1 row in set (0.00 sec)
If you have "something" and need 'something', use replace(col, "\"", "\'")
and viceversa.
int value = 35634646;
DecimalFormat myFormatter = new DecimalFormat("#,###");
String output = myFormatter.format(value);
System.out.println(output);
Output: 35,634,646
I've discovered the {{ request.get_host }}
method.
Java 8+ version:
Files.createDirectories(Paths.get("/Your/Path/Here"));
The Files.createDirectories()
creates a new directory and parent directories that do not exist. This method does not throw an exception if the directory already exists.
I had the same problem and found two different solutions (see this thread for more details). Both reduced the size of my uncompressed PDF dramatically.
Pixelated (lossy):
convert input.pdf -compress Zip output.pdf
Unpixelated (lossless, but may display slightly differently):
gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/screen -dNOPAUSE -dBATCH -dQUIET -sOutputFile=output.pdf input.pdf
Edit: I just discovered another option (for lossless compression), which avoids the nasty gs command. qpdf is a neat tool that converts PDFs (compression/decompression, encryption/decryption), and is much faster than the gs command:
qpdf --linearize input.pdf output.pdf
For centos7 I required:
sudo yum install mysql-devel gcc python-pip python-devel
sudo pip install mysql-python
So, gcc
and mysql-devel
(rather than mysql
) were important
I really like Darren Cook's and stacker's answers to this problem. I was in the midst of throwing my thoughts into a comment on those, but I believe my approach is too answer-shaped to not leave here.
In short summary, you've identified an algorithm to determine that a Coca-Cola logo is present at a particular location in space. You're now trying to determine, for arbitrary orientations and arbitrary scaling factors, a heuristic suitable for distinguishing Coca-Cola cans from other objects, inclusive of: bottles, billboards, advertisements, and Coca-Cola paraphernalia all associated with this iconic logo. You didn't call out many of these additional cases in your problem statement, but I feel they're vital to the success of your algorithm.
The secret here is determining what visual features a can contains or, through the negative space, what features are present for other Coke products that are not present for cans. To that end, the current top answer sketches out a basic approach for selecting "can" if and only if "bottle" is not identified, either by the presence of a bottle cap, liquid, or other similar visual heuristics.
The problem is this breaks down. A bottle could, for example, be empty and lack the presence of a cap, leading to a false positive. Or, it could be a partial bottle with additional features mangled, leading again to false detection. Needless to say, this isn't elegant, nor is it effective for our purposes.
To this end, the most correct selection criteria for cans appear to be the following:
Your classification might then look like the following:
This visually highlights to the user what was detected, emphasizing weak positives that may, correctly, be detected as mangled cans.
The detection of each property carries a very different time and space complexity, and for each approach, a quick pass through http://dsp.stackexchange.com is more than reasonable for determining the most correct and most efficient algorithm for your purposes. My intent here is, purely and simply, to emphasize that detecting if something is a can by invalidating a small portion of the candidate detection space isn't the most robust or effective solution to this problem, and ideally, you should take the appropriate actions accordingly.
And hey, congrats on the Hacker News posting! On the whole, this is a pretty terrific question worthy of the publicity it received. :)
Add validation groups for your validator elements. This allows you distinguish between different groups which to include in validation. Add validation group also to your submit button
Public Class Form1
Private animatedimage As New Bitmap("C:\MyData\Search.gif")
Private currentlyanimating As Boolean = False
Private Sub OnFrameChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
Me.Invalidate()
End Sub
Private Sub AnimateImage()
If currentlyanimating = True Then
ImageAnimator.Animate(animatedimage, AddressOf Me.OnFrameChanged)
currentlyanimating = False
End If
End Sub
Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
AnimateImage()
ImageAnimator.UpdateFrames(animatedimage)
e.Graphics.DrawImage(animatedimage, New Point((Me.Width / 4) + 40, (Me.Height / 4) + 40))
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
BtnStop.Enabled = False
End Sub
Private Sub BtnStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnStop.Click
currentlyanimating = False
ImageAnimator.StopAnimate(animatedimage, AddressOf Me.OnFrameChanged)
BtnStart.Enabled = True
BtnStop.Enabled = False
End Sub
Private Sub BtnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnStart.Click
currentlyanimating = True
AnimateImage()
BtnStart.Enabled = False
BtnStop.Enabled = True
End Sub
End Class
Eamon Nerbonne, I changed some css in your code and it's better now(the scroll bar starts from the first row)
I just add two line :
.div : padding-left:5em;
.headcol : background-color : #fff;
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.
I am of the firm belief that in an Entity Relation Diagram, the entity should be reflected with a singular name, similar to a class name being singular. Once instantiated, the name reflects its instance. So with databases, the entity when made into a table (a collection of entities or records) is plural. Entity, User is made into table Users. I would agree with others who suggested maybe the name User could be improved to Employee or something more applicable to your scenario.
This then makes more sense in a SQL statement because you are selecting from a group of records and if the table name is singular, it doesn't read well.
So Volley has been updated to Android studio build style which makes it harder create a jar. But the recommended way for eclipse was using it as a library project and this goes for android studio as well, but when working in android studio we call this a module. So here is a guide to how do it the way Google wants us to do it. Guide is based on this nice tutorial.
First get latest volley with git (git clone https://android.googlesource.com/platform/frameworks/volley).
In your current project (android studio) click [File]
--> [New]
-->[Import Module]
.
Now select the directory where you downloaded Volley to.
Now Android studio might guide you to do the rest but continue guide to verify that everything works correct
Open settings.gradle (find in root) and add (or verify this is included):
include ':app', ':volley'
Now go to your build.gradle in your project and add the dependency:
compile project(":volley")
Thats all there is to it, much simpler and easier than compiling a jar and safer than relying on third parties jars or maven uploads.
2018 10 25. Update.
Notepad++ 7.5.8 does not have plugin manager by default. You have to download plugins manually.
Keep in mind, if you use 64 bit version of Notepad++, you should also use 64 bit version of plugin. I had a similar issue here.
It might help you! demo
AngularJs Code-sample
var app = angular.module('urlApp', []);
app.controller('urlCtrl', function ($scope, $log, $window) {
$scope.ClickMeToRedirect = function () {
var url = "http://" + $window.location.host + "/Account/Login";
$log.log(url);
$window.location.href = url;
};
});
HTML Code-sample
<div ng-app="urlApp">
<div ng-controller="urlCtrl">
Redirect to <a href="#" ng-click="ClickMeToRedirect()">Click Me!</a>
</div>
</div>
If executed within "sqlplus", you can execute a host operating system command "sleep" :
!sleep 1
or
host sleep 1
var url = ConfigurationManager.AppSettings["ServiceProviderUrl"];
Warning: do not use the following command unless you want to lose uncommitted work!
Using git reset
has been explained, but you asked for an explanation of the piped commands as well, so here goes:
git ls-files -z | xargs -0 rm -f
git diff --name-only --diff-filter=D -z | xargs -0 git rm --cached
The command git ls-files
lists all files git knows about. The option -z
imposes a specific format on them, the format expected by xargs -0
, which then invokes rm -f
on them, which means to remove them without checking for your approval.
In other words, "list all files git knows about and remove your local copy".
Then we get to git diff
, which shows changes between different versions of items git knows about. Those can be changes between different trees, differences between local copies and remote copies, and so on.
As used here, it shows the unstaged changes; the files you have changed but haven't committed yet. The option --name-only
means you want the (full) file names only and --diff-filter=D
means you're interested in deleted files only. (Hey, didn't we just delete a bunch of stuff?)
This then gets piped into the xargs -0
we saw before, which invokes git rm --cached
on them, meaning that they get removed from the cache, while the working tree should be left alone — except that you've just removed all files from your working tree. Now they're removed from your index as well.
In other words, all changes, staged or unstaged, are gone, and your working tree is empty. Have a cry, checkout your files fresh from origin or remote, and redo your work. Curse the sadist who wrote these infernal lines; I have no clue whatsoever why anybody would want to do this.
TL;DR: you just hosed everything; start over and use git reset
from now on.
Here is a solution am using with anular 6.
[readonly]="DateRelatedObject.bool_DatesEdit ? true : false"
plus above given answer
[attr.disabled]="valid == true ? true : null"
did't work for me plus be aware of using null cause it's expecting bool.
I faced a similar problem. I was trying to add the reference of a .net 2.0 dll to a .Net 1.1 project. When I tried adding a previous version of the .dll which was complied in .Net 1.1. it worked for me.
If you want something beyond the ID column that's there in all lists, you're probably going to have to resort to an Event Receiver on the list that "calculates" what the value of your unique identified should be or using a custom field type that has the required logic embedded in this. Unfortunately, both of these options will require writing and deploying custom code to the server and deploying assemblies to the GAC, which can be frowned upon in environments where you don't have complete control over the servers.
If you don't need the unique identifier to show up immediately, you could probably generate it via a workflow (either with SharePoint Designer or a custom WF workflow built in Visual Studio).
Unfortunately, calculated columns, which seem like an obvious solution, won't work for this purpose because the ID is not yet assigned when the calculation is attempted. If you go in after the fact and edit the item, the calculation may achieve what you want, but on initial creation of a new item it will not be calculated correctly.
This problem comes when you are writing data in many files simultaneously and your Operating System has a fixed limit of Open files. In Linux, you can increase the limit of open files.
https://www.tecmint.com/increase-set-open-file-limits-in-linux/
One thing to keep in mind is :
The name 'ReentrantLock' gives out a wrong message about other locking mechanism that they are not re-entrant. This is not true. Lock acquired via 'synchronized' is also re-entrant in Java.
Key difference is that 'synchronized' uses intrinsic lock ( one that every Object has ) while Lock API doesn't.
You don't need to use display:inline
to achieve this:
.inline {
border: 1px solid red;
margin:10px;
float:left;/*Add float left*/
margin :10px;
}
You can use float-left
.
Using float:left is best way to place multiple div elements in one line. Why? Because inline-block does have some problem when is viewed in IE older versions.
Try something like
find . \( -type f -name \*_peaks.bed -print \) -or \( -type d -and \( -name tmp -or -name scripts \) -and -prune \)
and don't be too surprised if I got it a bit wrong. If the goal is an exec (instead of print), just substitute it in place.
I'm surprised no-one's mentioned Vim's windowing support. Ctrl + W, S is something I use nearly every time I open Vim.
You're not running a module -- you're running subroutines/functions that happen to be stored in modules.
If you put the code in a standalone module and don't specify scope in the definitions of your subroutines/functions, they will be public by default, and callable from anywhere within your application. This means that you can call them with RunCode in a macro, from the class modules of forms/reports, from standalone class modules, or for the functions, from SQL (with some caveats).
Given that you were trying to implement in VBA something that you felt was too complicated for SQL, SQL is the likely context in which you want to execute the code. So, you should just be able to call your function within the SQL statement:
SELECT MyTable.PersonID, MyTable.FirstName, MyTable.LastName, FormatAddress([Address], [City], [State], [Zip], [Country]) As Address
FROM MyTable;
That SQL calls a public function called FormatAddress() that takes as arguments the components of an address and formats them appropriately. It's a trivial example as you likely would not need a VBA function for that purpose, but the point is that this is how you call functions from within a SQL statement.
Subroutines (i.e., code that returns no value) are not callable from within SQL statements.
This can be done via EnvInject plugin in the following way:
Create an "Execute shell" build step that runs:
echo AOEU=$(echo aoeu) > propsfile
Create an Inject environment variables build step and set "Properties File Path" to propsfile
.
Note: This plugin is (mostly) not compatible with the Pipeline plugin.
I would try the itemStateChanged()
method of the ItemListener
interface if jodonnell's solution fails.
support for document.location
is also good though its a deprecated method.
I've been using this method for a while with no problems.
you can refer here for more details:
https://developer.mozilla.org/en-US/docs/Web/API/document.location
Seems a bit too late, but there is a PPA repository with SmartGit, enjoy! =)
First, close all instances of Google Chrome. There should be no instances of chrome.exe
running in the Windows Task Manager. Then
%LOCALAPPDATA%\Google\Chrome\User Data\Default\
..txt
). This will serve as a backup, should something go wrong.window_placement
. Under window_placement
you will see things like "bottom", "left", "right", etc. with numbers after them.You will need to play around with these numbers to get your desired window size and placement. When finished, save this file with the name "Preferences" again with no extension. This will overwrite the existing Preferences file. Open Chrome and see how you did. If you're not satisfied with the size and placement, close Chrome and change the numbers in the Preferences file until you get what you want.
What you can do is:
Update your local git repo:
git fetch
Build a local branch and checkout on it:
git branch pouet && git checkout pouet
Apply the commit you want on this branch:
git cherry-pick abcdefabcdef
(abcdefabcdef is the sha1 of the commit you want to apply)
$this->validate($request,[
'input_field_name'=>'digits_between:2,5',
]);
Try this it will be work
The proper way to sort strings is:
import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # vary depending on your lang/locale
assert sorted((u'Ab', u'ad', u'aa'), cmp=locale.strcoll) == [u'aa', u'Ab', u'ad']
# Without using locale.strcoll you get:
assert sorted((u'Ab', u'ad', u'aa')) == [u'Ab', u'aa', u'ad']
The previous example of mylist.sort(key=lambda x: x.lower())
will work fine for ASCII-only contexts.
I think this command killall is exactly what you need. The command is described as "kill processes by name".It's easy to use.For example
killall chrome
This command will kill all process of Chrome.Here is a link about killall command
http://linux.about.com/library/cmd/blcmdl1_killall.htm
Hope this command could help you.
try to use: cmake --clean-first path-of-CMakeLists.txt-file -B output-dir
--clean-first: Build target clean first, then build.
(To clean only, use --target clean.)
If you want to match a word A in a string and not to match a word B. For example: If you have a text:
1. I have a two pets - dog and a cat
2. I have a pet - dog
If you want to search for lines of text that HAVE a dog for a pet and DOESN'T have cat you can use this regular expression:
^(?=.*?\bdog\b)((?!cat).)*$
It will find only second line:
2. I have a pet - dog
wouldn't
margin-left:auto;
margin-right:auto;
added to the .image_block
a img do the trick?
Note that that won't work in IE6 (maybe 7 not sure)
there you will have to do on .image_block
the container Div
text-align:center;
position:relative;
could be a problem too.
this error is also caused by null pointer reference. if you are using a pointer who is not initialized then it causes this error.
to check either a pointer is initialized or not you can try something like
Class *pointer = new Class();
if(pointer!=nullptr){
pointer->myFunction();
}
My simple solution. IMHO it's the cleanest.
First create a application.yml
spring.main.allow-bean-definition-overriding: true
security:
oauth2:
client:
clientId: XXX
clientSecret: XXX
accessTokenUri: XXX
tokenName: access_token
grant-type: client_credentials
Create the main class: Main
@SpringBootApplication
@EnableOAuth2Client
public class Main extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/").permitAll();
}
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
@Bean
public OAuth2RestTemplate oauth2RestTemplate(ClientCredentialsResourceDetails details) {
return new OAuth2RestTemplate(details);
}
}
Then Create the controller class: Controller
@RestController
class OfferController {
@Autowired
private OAuth2RestOperations restOperations;
@RequestMapping(value = "/<your url>"
, method = RequestMethod.GET
, produces = "application/json")
public String foo() {
ResponseEntity<String> responseEntity = restOperations.getForEntity(<the url you want to call on the server>, String.class);
return responseEntity.getBody();
}
}
Maven dependencies
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.1.5.RELEASE</version>
</dependency>
</dependencies>
the mime type might not be text/csv
some systems can read/save them different. (for example sometimes IE sends .csv files as application/vnd.ms-excel
) so you best bet would be to build an array of allowed values and test against that, then find all possible values to test against.
$mimes = array('application/vnd.ms-excel','text/plain','text/csv','text/tsv');
if(in_array($_FILES['file']['type'],$mimes)){
// do something
} else {
die("Sorry, mime type not allowed");
}
if you wished you could add a further check if mime is returned as text/plain you could run a preg_match
to make sure it has enough commas in it to be a csv.
Is there some handy way of defining direction per column?
No. You cannot specify the sort order other than by a callback function that inverses the value. Not even this is possible for a multicolumn sort.
You might be able to do
_.each(array_of_objects, function(o) {
o.typeDesc = -o.type; // assuming a number
});
_.sortBy(array_of_objects, ['typeDesc', 'name'])
For everything else, you will need to resort to the native .sort()
with a custom comparison function:
array_of_objects.sort(function(a, b) {
return a.type - b.type // asc
|| +(b.name>a.name)||-(a.name>b.name) // desc
|| …;
});
The above example using sort is close, but in the case of strings simply use SearchString:
files := []string{"Test.conf", "util.go", "Makefile", "misc.go", "main.go"}
target := "Makefile"
sort.Strings(files)
i := sort.SearchStrings(files, target)
if i < len(files) && files[i] == target {
fmt.Printf("found \"%s\" at files[%d]\n", files[i], i)
}
insertRow2 <- function(existingDF, newrow, r) {
existingDF <- rbind(existingDF,newrow)
existingDF <- existingDF[order(c(1:(nrow(existingDF)-1),r-0.5)),]
row.names(existingDF) <- 1:nrow(existingDF)
return(existingDF)
}
insertRow2(existingDF,newrow,r)
V1 V2 V3 V4
1 1 6 11 16
2 2 7 12 17
3 1 2 3 4
4 3 8 13 18
5 4 9 14 19
6 5 10 15 20
microbenchmark(
+ rbind(existingDF[1:r,],newrow,existingDF[-(1:r),]),
+ insertRow(existingDF,newrow,r),
+ insertRow2(existingDF,newrow,r)
+ )
Unit: microseconds
expr min lq median uq max
1 insertRow(existingDF, newrow, r) 513.157 525.6730 531.8715 544.4575 1409.553
2 insertRow2(existingDF, newrow, r) 430.664 443.9010 450.0570 461.3415 499.988
3 rbind(existingDF[1:r, ], newrow, existingDF[-(1:r), ]) 606.822 625.2485 633.3710 653.1500 1489.216
I tried two ways, and it worked fine to center the div. Both the ways will align the divs on all screens.
Way 1: Using Push:
<div class = "col-lg-4 col-md-4 col-sm-4 col-xs-4 col-lg-push-4 col-md-push-4 col-sm-push-4 col-xs-push-4" style="border-style:solid;border-width:1px">
<h2>Grievance form</h2> <!-- To center this text, use style="text-align: center" -->
</div>
Way 2: Using Offset:
<div class = "col-lg-4 col-md-4 col-sm-4 col-xs-4 col-lg-offset-4 col-md-offest-4 col-sm-offest-4 col-xs-offest-4" style="border-style:solid;border-width:1px">
<h2>Grievance form</h2> <!--to center this text, use style="text-align: center"-->
</div>
Result:
Explanation
Bootstrap will designate to the left, the first column of the specified screen-occupancy. If we use offset or push it will shift the 'this' column by 'those' many columns. Though I faced some issues in responsiveness of offset, push was awesome.
Both of my dev machines have JDK 8 installed, the debugging function is restored once JDK 7.0.71 was installed and JAVA_HOME environmental variable was set to point to the new JDK.
Guess there's some compatibility issue between Android Studio + ADB + JDK8 (Eclipse + ADB + JDK8 works fine).
Here is simple way to access parent id
document.getElementById("child1").parentNode;
will do the magic for you to access the parent div.
<html>
<head>
</head>
<body id="body">
<script>
function alertAncestorsUntilID() {
var a = document.getElementById("child").parentNode;
alert(a.id);
}
</script>
<div id="master">
Master
<div id="child">Child</div>
</div>
<script>
alertAncestorsUntilID();
</script>
</body>
</html>
I posted something similar here
From Joachim's answer, from Dianne Hackborn:
http://groups.google.com/group/android-developers/browse_thread/thread/d2a5c203dad6ec42
I ended up just using:
FragmentManager fm = getActivity().getSupportFragmentManager();
for(int i = 0; i < fm.getBackStackEntryCount(); ++i) {
fm.popBackStack();
}
But could equally have used something like:
((AppCompatActivity)getContext()).getSupportFragmentManager().popBackStack(String name, FragmentManager.POP_BACK_STACK_INCLUSIVE)
Which will pop all states up to the named one. You can then just replace the fragment with what you want
If you have notepad++ installed in your pc, then you can copy text as RTF (Rich Text Format) and paste it in your outlook mail.
1) Paste you code snippet into notepad++
2) From Menu bar navigate to "Plugins -> NppExport -> Copy RTF to clipboard"
3) Paste into your email
4) Done
With some web hosts including NameCheap, it's not possible to disable ModSecurity using .htaccess
. The only option is to contact tech support and ask them to alter the configuration for you.
Here is a more complete example of an XML filter (the example above by itself will not work since it just shows a snippet and is missing the <FindBugsFilter>
begin and end tags):
<FindBugsFilter>
<Match>
<Class name="com.mycompany.foo" />
<Method name="bar" />
<Bug pattern="NP_BOOLEAN_RETURN_NULL" />
</Match>
</FindBugsFilter>
If you are using the Android Studio FindBugs plugin, browse to your XML filter file using File->Other Settings->Default Settings->Other Settings->FindBugs-IDEA->Filter->Exclude filter files->Add.
Find complete example of Spring Mvc Validation
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.technicalkeeda.bean.Login;
public class LoginValidator implements Validator {
public boolean supports(Class aClass) {
return Login.class.equals(aClass);
}
public void validate(Object obj, Errors errors) {
Login login = (Login) obj;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userName",
"username.required", "Required field");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userPassword",
"userpassword.required", "Required field");
}
}
public class LoginController extends SimpleFormController {
private LoginService loginService;
public LoginController() {
setCommandClass(Login.class);
setCommandName("login");
}
public void setLoginService(LoginService loginService) {
this.loginService = loginService;
}
@Override
protected ModelAndView onSubmit(Object command) throws Exception {
Login login = (Login) command;
loginService.add(login);
return new ModelAndView("loginsucess", "login", login);
}
}
This answer is very late but what I do is set a class that holds Booleans, arrays, and integer-initial values as global scope static variables. Any constant strings are defined as such.
define("myconstant", "value");
class globalVars {
static $a = false;
static $b = 0;
static $c = array('first' => 2, 'second' => 5);
}
function test($num) {
if (!globalVars::$a) {
$returnVal = 'The ' . myconstant . ' of ' . $num . ' plus ' . globalVars::$b . ' plus ' . globalVars::$c['second'] . ' is ' . ($num + globalVars::$b + globalVars::$c['second']) . '.';
globalVars::$a = true;
} else {
$returnVal = 'I forgot';
}
return $returnVal;
}
echo test(9); ---> The value of 9 + 0 + 5 is 14.
echo "<br>";
echo globalVars::$a; ----> 1
The static
keywords must be present in the class else the vars $a, $b, and $c will not be globally scoped.
This works for me,
$('#datepicker').datepicker("setValue", '01/10/2014' );
$('#datepicker').datepicker("setValue", new Date(2008,9,03));
Quick example using company1
from your question, with python3.
import pickle
# Save the file
pickle.dump(company1, file = open("company1.pickle", "wb"))
# Reload the file
company1_reloaded = pickle.load(open("company1.pickle", "rb"))
However, as this answer noted, pickle often fails. So you should really use dill
.
import dill
# Save the file
dill.dump(company1, file = open("company1.pickle", "wb"))
# Reload the file
company1_reloaded = dill.load(open("company1.pickle", "rb"))
if (iv_new_pwd.isSelected()) {
iv_new_pwd.setSelected(false);
Log.d("mytag", "in case 1");
edt_new_pwd.setInputType(InputType.TYPE_CLASS_TEXT);
} else {
Log.d("mytag", "in case 1");
iv_new_pwd.setSelected(true);
edt_new_pwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
}
Since none of the suggestions above helped me with charts.js 2.1.4, I solved it by adding the value 0 to my data set array (but no extra label):
statsData.push(0);
[...]
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
datasets: [{
data: statsData,
[...]
The error indicates another process is trying to access the file. Maybe you or someone else has it open while you are attempting to write to it. "Read" or "Copy" usually doesn't cause this, but writing to it or calling delete on it would.
There are some basic things to avoid this, as other answers have mentioned:
In FileStream
operations, place it in a using
block with a FileShare.ReadWrite
mode of access.
For example:
using (FileStream stream = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
{
}
Note that FileAccess.ReadWrite
is not possible if you use FileMode.Append
.
I ran across this issue when I was using an input stream to do a File.SaveAs
when the file was in use. In my case I found, I didn't actually need to save it back to the file system at all, so I ended up just removing that, but I probably could've tried creating a FileStream in a using
statement with FileAccess.ReadWrite
, much like the code above.
Saving your data as a different file and going back to delete the old one when it is found to be no longer in use, then renaming the one that saved successfully to the name of the original one is an option. How you test for the file being in use is accomplished through the
List<Process> lstProcs = ProcessHandler.WhoIsLocking(file);
line in my code below, and could be done in a Windows service, on a loop, if you have a particular file you want to watch and delete regularly when you want to replace it. If you don't always have the same file, a text file or database table could be updated that the service always checks for file names, and then performs that check for processes & subsequently performs the process kills and deletion on it, as I describe in the next option. Note that you'll need an account user name and password that has Admin privileges on the given computer, of course, to perform the deletion and ending of processes.
When you don't know if a file will be in use when you are trying to save it, you can close all processes that could be using it, like Word, if it's a Word document, ahead of the save.
If it is local, you can do this:
ProcessHandler.localProcessKill("winword.exe");
If it is remote, you can do this:
ProcessHandler.remoteProcessKill(computerName, txtUserName, txtPassword, "winword.exe");
where txtUserName
is in the form of DOMAIN\user
.
Let's say you don't know the process name that is locking the file. Then, you can do this:
List<Process> lstProcs = new List<Process>();
lstProcs = ProcessHandler.WhoIsLocking(file);
foreach (Process p in lstProcs)
{
if (p.MachineName == ".")
ProcessHandler.localProcessKill(p.ProcessName);
else
ProcessHandler.remoteProcessKill(p.MachineName, txtUserName, txtPassword, p.ProcessName);
}
Note that file
must be the UNC path: \\computer\share\yourdoc.docx
in order for the Process
to figure out what computer it's on and p.MachineName
to be valid.
Below is the class these functions use, which requires adding a reference to System.Management
. The code was originally written by Eric J.:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Management;
namespace MyProject
{
public static class ProcessHandler
{
[StructLayout(LayoutKind.Sequential)]
struct RM_UNIQUE_PROCESS
{
public int dwProcessId;
public System.Runtime.InteropServices.ComTypes.FILETIME ProcessStartTime;
}
const int RmRebootReasonNone = 0;
const int CCH_RM_MAX_APP_NAME = 255;
const int CCH_RM_MAX_SVC_NAME = 63;
enum RM_APP_TYPE
{
RmUnknownApp = 0,
RmMainWindow = 1,
RmOtherWindow = 2,
RmService = 3,
RmExplorer = 4,
RmConsole = 5,
RmCritical = 1000
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
struct RM_PROCESS_INFO
{
public RM_UNIQUE_PROCESS Process;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_APP_NAME + 1)]
public string strAppName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_SVC_NAME + 1)]
public string strServiceShortName;
public RM_APP_TYPE ApplicationType;
public uint AppStatus;
public uint TSSessionId;
[MarshalAs(UnmanagedType.Bool)]
public bool bRestartable;
}
[DllImport("rstrtmgr.dll", CharSet = CharSet.Unicode)]
static extern int RmRegisterResources(uint pSessionHandle,
UInt32 nFiles,
string[] rgsFilenames,
UInt32 nApplications,
[In] RM_UNIQUE_PROCESS[] rgApplications,
UInt32 nServices,
string[] rgsServiceNames);
[DllImport("rstrtmgr.dll", CharSet = CharSet.Auto)]
static extern int RmStartSession(out uint pSessionHandle, int dwSessionFlags, string strSessionKey);
[DllImport("rstrtmgr.dll")]
static extern int RmEndSession(uint pSessionHandle);
[DllImport("rstrtmgr.dll")]
static extern int RmGetList(uint dwSessionHandle,
out uint pnProcInfoNeeded,
ref uint pnProcInfo,
[In, Out] RM_PROCESS_INFO[] rgAffectedApps,
ref uint lpdwRebootReasons);
/// <summary>
/// Find out what process(es) have a lock on the specified file.
/// </summary>
/// <param name="path">Path of the file.</param>
/// <returns>Processes locking the file</returns>
/// <remarks>See also:
/// http://msdn.microsoft.com/en-us/library/windows/desktop/aa373661(v=vs.85).aspx
/// http://wyupdate.googlecode.com/svn-history/r401/trunk/frmFilesInUse.cs (no copyright in code at time of viewing)
///
/// </remarks>
static public List<Process> WhoIsLocking(string path)
{
uint handle;
string key = Guid.NewGuid().ToString();
List<Process> processes = new List<Process>();
int res = RmStartSession(out handle, 0, key);
if (res != 0) throw new Exception("Could not begin restart session. Unable to determine file locker.");
try
{
const int ERROR_MORE_DATA = 234;
uint pnProcInfoNeeded = 0,
pnProcInfo = 0,
lpdwRebootReasons = RmRebootReasonNone;
string[] resources = new string[] { path }; // Just checking on one resource.
res = RmRegisterResources(handle, (uint)resources.Length, resources, 0, null, 0, null);
if (res != 0) throw new Exception("Could not register resource.");
//Note: there's a race condition here -- the first call to RmGetList() returns
// the total number of process. However, when we call RmGetList() again to get
// the actual processes this number may have increased.
res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, null, ref lpdwRebootReasons);
if (res == ERROR_MORE_DATA)
{
// Create an array to store the process results
RM_PROCESS_INFO[] processInfo = new RM_PROCESS_INFO[pnProcInfoNeeded];
pnProcInfo = pnProcInfoNeeded;
// Get the list
res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, processInfo, ref lpdwRebootReasons);
if (res == 0)
{
processes = new List<Process>((int)pnProcInfo);
// Enumerate all of the results and add them to the
// list to be returned
for (int i = 0; i < pnProcInfo; i++)
{
try
{
processes.Add(Process.GetProcessById(processInfo[i].Process.dwProcessId));
}
// catch the error -- in case the process is no longer running
catch (ArgumentException) { }
}
}
else throw new Exception("Could not list processes locking resource.");
}
else if (res != 0) throw new Exception("Could not list processes locking resource. Failed to get size of result.");
}
finally
{
RmEndSession(handle);
}
return processes;
}
public static void remoteProcessKill(string computerName, string userName, string pword, string processName)
{
var connectoptions = new ConnectionOptions();
connectoptions.Username = userName;
connectoptions.Password = pword;
ManagementScope scope = new ManagementScope(@"\\" + computerName + @"\root\cimv2", connectoptions);
// WMI query
var query = new SelectQuery("select * from Win32_process where name = '" + processName + "'");
using (var searcher = new ManagementObjectSearcher(scope, query))
{
foreach (ManagementObject process in searcher.Get())
{
process.InvokeMethod("Terminate", null);
process.Dispose();
}
}
}
public static void localProcessKill(string processName)
{
foreach (Process p in Process.GetProcessesByName(processName))
{
p.Kill();
}
}
[DllImport("kernel32.dll")]
public static extern bool MoveFileEx(string lpExistingFileName, string lpNewFileName, int dwFlags);
public const int MOVEFILE_DELAY_UNTIL_REBOOT = 0x4;
}
}
This is all you need to know.
int state = 0;
while (state < 3)
{
switch (state)
{
case 0:
// Do State 0 Stuff
if (should_go_to_next_state)
{
state++;
}
break;
case 1:
// Do State 1 Stuff
if (should_go_back)
{
state--;
}
else if (should_go_to_next_state)
{
state++;
}
break;
case 2:
// Do State 2 Stuff
if (should_go_back_two)
{
state -= 2;
}
else if (should_go_to_next_state)
{
state++;
}
break;
default:
break;
}
}
Building on the brilliant logic / code from mathematix and scottyc, I submit:
DECLARE @a INT, @b INT, @c INT = 0
WHILE @c < 100
BEGIN
SET @c += 1
SET @a = ROUND(RAND()*100,0)-50
SET @b = ROUND(RAND()*100,0)-50
SELECT @a AS a, @b AS b,
@a - ( ABS(@a-@b) + (@a-@b) ) / 2 AS MINab,
@a + ( ABS(@b-@a) + (@b-@a) ) / 2 AS MAXab,
CASE WHEN (@a <= @b AND @a = @a - ( ABS(@a-@b) + (@a-@b) ) / 2)
OR (@a >= @b AND @a = @a + ( ABS(@b-@a) + (@b-@a) ) / 2)
THEN 'Success' ELSE 'Failure' END AS Status
END
Although the jump from scottyc's MIN function to the MAX function should have been obvious to me, it wasn't, so I've solved for it and included it here: SELECT @a + ( ABS(@b-@a) + (@b-@a) ) / 2. The randomly generated numbers, while not proof, should at least convince skeptics that both formulae are correct.
You can use static class or Singleton pattern.
Craigslist does have a "bulk posting interface" which allows for multiple posts to happen at once through HTTPS POST. See:
These can all be done with DateTime.Add(TimeSpan)
since it supports positive and negative timespans.
DateTime original = new DateTime(year, month, day, 8, 0, 0);
DateTime updated = original.Add(new TimeSpan(5,0,0));
DateTime original = new DateTime(year, month, day, 17, 0, 0);
DateTime updated = original.Add(new TimeSpan(-2,0,0));
DateTime original = new DateTime(year, month, day, 17, 30, 0);
DateTime updated = original.Add(new TimeSpan(0,45,0));
Or you can also use the DateTime.Subtract(TimeSpan)
method analogously.
If you want to find the upstream for any branch (as opposed to just the one you are on), here is a slight modification to @cdunn2001's answer:
git rev-parse --abbrev-ref --symbolic-full-name YOUR_LOCAL_BRANCH_NAME@{upstream}
That will give you the remote branch name for the local branch named YOUR_LOCAL_BRANCH_NAME
.
Here is a javascript code to add users.
Start mongod
with --auth = true
Access admin database from mongo shell and pass the javascript file.
mongo admin "Filename.js"
"Filename.js"
// Adding admin user
db.addUser("admin_username", " admin_password");
// Authenticate admin user
db.auth("admin_username ", " admin_password ");
// use database code from java script
db = db.getSiblingDB("newDatabase");
// Adding newDatabase database user
db.addUser("database_username ", " database_ password ");
Now user addition is complete, we can verify accessing the database from mongo shell
Select Distinct CAST(FLOOR( CAST(start_date AS FLOAT ) )AS DATETIME) from Table
Here are the ones I can find:
Sources:
If you are on a unixoid operating system and want to extract just a single file you can try the following. The structure of the chrome://cache
pages is URL, parsed HTTP header, hex dump of the HTTP header and then hex dump of the payload.
To extract a file copy all payload lines from a Chrome cache page to the clipboard (starting at the second 00000000: ...
line), paste them into a text editor and save them as a plain text file (e.g. file.txt
). If the payload is a gzipped WOFF file use xxd -r file.txt > file.woff.gz
to convert it back to a binary file and gunzip file.woff.gz
for decompression.
You can then use woff2otf to convert WOFF files to the OTF format or woff2 to convert WOFF 2.0 files to the TTF format. For batch processing this workflow should obviously be scripted.
In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.
EDIT
It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.
var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>"
I submitted a pull request to update this.
Just for the record, you can filter on data with jquery (this question is quite old, and jQuery evolved since then, so it's right to write this solution as well):
$('.navlink[data-selected="true"]');
or, better (for performance):
$('.navlink').filter('[data-selected="true"]');
or, if you want to get all the elements with data-selected
set:
$('[data-selected]')
Note that this method will only work with data that was set via html-attributes. If you set or change data with the .data()
call, this method will no longer work.
As noted by Mattias Nordqvist in the comments below, you can also select the radio button option "Run whether user is logged on or not". When saving the task, you will be prompted once for the user password. bambams noted that this wouldn't grant System permissions to the process, and also seems to hide the command window.
It's not an obvious solution, but to make a Scheduled Task run in the background, change the User running the task to "SYSTEM", and nothing will appear on your screen.
Since Java 15, you can use a non-static string method called String::formatted(Object... args)
Example:
String foo = "foo";
String bar = "bar";
String str = "First %s, then %s".formatted(foo, bar);
Output:
"First foo, then bar"
You can use model class and use setTag() getTag() methods to keep track which items from listview are checked and which not.
More reference for this : listview with checkbox in android
Source code for model
public class Model {
private boolean isSelected;
private String animal;
public String getAnimal() {
return animal;
}
public void setAnimal(String animal) {
this.animal = animal;
}
public boolean getSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
}
put this in your custom adapter
holder.checkBox.setTag(R.integer.btnplusview, convertView);
holder.checkBox.setTag( position);
holder.checkBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
View tempview = (View) holder.checkBox.getTag(R.integer.btnplusview);
TextView tv = (TextView) tempview.findViewById(R.id.animal);
Integer pos = (Integer) holder.checkBox.getTag();
Toast.makeText(context, "Checkbox "+pos+" clicked!", Toast.LENGTH_SHORT).show();
if(modelArrayList.get(pos).getSelected()){
modelArrayList.get(pos).setSelected(false);
}else {
modelArrayList.get(pos).setSelected(true);
}
}
});
whole code for customAdapter is
public class CustomAdapter extends BaseAdapter {
private Context context;
public static ArrayList<Model> modelArrayList;
public CustomAdapter(Context context, ArrayList<Model> modelArrayList) {
this.context = context;
this.modelArrayList = modelArrayList;
}
@Override
public int getViewTypeCount() {
return getCount();
}
@Override
public int getItemViewType(int position) {
return position;
}
@Override
public int getCount() {
return modelArrayList.size();
}
@Override
public Object getItem(int position) {
return modelArrayList.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder(); LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.lv_item, null, true);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.cb);
holder.tvAnimal = (TextView) convertView.findViewById(R.id.animal);
convertView.setTag(holder);
}else {
// the getTag returns the viewHolder object set as a tag to the view
holder = (ViewHolder)convertView.getTag();
}
holder.checkBox.setText("Checkbox "+position);
holder.tvAnimal.setText(modelArrayList.get(position).getAnimal());
holder.checkBox.setChecked(modelArrayList.get(position).getSelected());
holder.checkBox.setTag(R.integer.btnplusview, convertView);
holder.checkBox.setTag( position);
holder.checkBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
View tempview = (View) holder.checkBox.getTag(R.integer.btnplusview);
TextView tv = (TextView) tempview.findViewById(R.id.animal);
Integer pos = (Integer) holder.checkBox.getTag();
Toast.makeText(context, "Checkbox "+pos+" clicked!", Toast.LENGTH_SHORT).show();
if(modelArrayList.get(pos).getSelected()){
modelArrayList.get(pos).setSelected(false);
}else {
modelArrayList.get(pos).setSelected(true);
}
}
});
return convertView;
}
private class ViewHolder {
protected CheckBox checkBox;
private TextView tvAnimal;
}
}
The problem is that you are using SingleOrDefault
. This method will only succeed when the collections contains exactly 0 or 1 element. I believe you are looking for FirstOrDefault
which will succeed no matter how many elements are in the collection.
JSONP is really a simply trick to overcome XMLHttpRequest same domain policy. (As you know one cannot send AJAX (XMLHttpRequest) request to a different domain.)
So - instead of using XMLHttpRequest we have to use script HTMLl tags, the ones you usually use to load JS files, in order for JS to get data from another domain. Sounds weird?
Thing is - turns out script tags can be used in a fashion similar to XMLHttpRequest! Check this out:
script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://www.someWebApiServer.com/some-data";
You will end up with a script segment that looks like this after it loads the data:
<script>
{['some string 1', 'some data', 'whatever data']}
</script>
However this is a bit inconvenient, because we have to fetch this array from script tag. So JSONP creators decided that this will work better (and it is):
script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://www.someWebApiServer.com/some-data?callback=my_callback";
Notice my_callback function over there? So - when JSONP server receives your request and finds callback parameter - instead of returning plain JS array it'll return this:
my_callback({['some string 1', 'some data', 'whatever data']});
See where the profit is: now we get automatic callback (my_callback) that'll be triggered once we get the data. That's all there is to know about JSONP: it's a callback and script tags.
NOTE:
These are simple examples of JSONP usage, these are not production ready scripts.
RAW JavaScript demonstration (simple Twitter feed using JSONP):
<html>
<head>
</head>
<body>
<div id = 'twitterFeed'></div>
<script>
function myCallback(dataWeGotViaJsonp){
var text = '';
var len = dataWeGotViaJsonp.length;
for(var i=0;i<len;i++){
twitterEntry = dataWeGotViaJsonp[i];
text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
}
document.getElementById('twitterFeed').innerHTML = text;
}
</script>
<script type="text/javascript" src="http://twitter.com/status/user_timeline/padraicb.json?count=10&callback=myCallback"></script>
</body>
</html>
Basic jQuery example (simple Twitter feed using JSONP):
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url: 'http://twitter.com/status/user_timeline/padraicb.json?count=10',
dataType: 'jsonp',
success: function(dataWeGotViaJsonp){
var text = '';
var len = dataWeGotViaJsonp.length;
for(var i=0;i<len;i++){
twitterEntry = dataWeGotViaJsonp[i];
text += '<p><img src = "' + twitterEntry.user.profile_image_url_https +'"/>' + twitterEntry['text'] + '</p>'
}
$('#twitterFeed').html(text);
}
});
})
</script>
</head>
<body>
<div id = 'twitterFeed'></div>
</body>
</html>
JSONP stands for JSON with Padding. (very poorly named technique as it really has nothing to do with what most people would think of as “padding”.)
int counter = gridEstimateSales.Rows.Count;
for (int i = 0; i < counter; i++)
{
if (i == counter-1)
{
//this is where your LAST LINE code goes
//row.DefaultCellStyle.BackColor = Color.Yellow;
gridEstimateSales.Rows[i].DefaultCellStyle.BackColor = Color.Red;
}
else
{
//this is your normal code NOT LAST LINE
//row.DefaultCellStyle.BackColor = Color.Red;
gridEstimateSales.Rows[i].DefaultCellStyle.BackColor = Color.White;
}
}
If you're currently on the branch you want to rename:
git branch -m new_name
Or else:
git branch -m old_name new_name
You can check with:
git branch -a
As you can see, only the local name changed Now, to change the name also in the remote you must do:
git push origin :old_name
This removes the branch, then upload it with the new name:
git push origin new_name
In the C standard, a standalone implementation doesn't have to provide all of the library functions that a hosted implementation has to provide. The C standard doesn't care about embedded, but vendors of embedded systems usually provide standalone implementations with whatever amount of libraries they're willing to provide.
C is a widely used general purpose high level programming language mainly intended for system programming.
Embedded C is an extension to C programming language that provides support for developing efficient programs for embedded devices.It is not a part of the C language
You can also refer to the articles below:
You can get MinGW (as others have suggested) but I would recommend getting a simple IDE (not VS Express). You can try Dev C++ http://www.bloodshed.net/devcpp.html Its a simple IDE for C/C++ and uses MinGW internally. In this you can write and compile single C files without creating a full-blown "project".
When you imported the WSDL, you should have an ObjectFactory
class which should have bunch of methods for creating various input parameters.
ObjectFactory factory = new ObjectFactory();
JAXBElement<String> createMessageDescription = factory.createMessageDescription("description");
message.setDescription(createMessageDescription);
You're using message.Length
which returns the number of characters in the string, but you should be using the nubmer of bytes to read. You should use something like:
byte[] messageBytes = uniEncoding.GetBytes(message);
stringAsStream.Write(messageBytes, 0, messageBytes.Length);
You're then reading a single byte and expecting to get a character from it just by casting to char
. UnicodeEncoding
will use two bytes per character.
As Justin says you're also not seeking back to the beginning of the stream.
Basically I'm afraid pretty much everything is wrong here. Please give us the bigger picture and we can help you work out what you should really be doing. Using a StreamWriter
to write and then a StreamReader
to read is quite possibly what you want, but we can't really tell from just the brief bit of code you've shown.
Just use
for i in range(0, 5):
print i
to iterate through your data set and print each value.
For large data sets, you want to use xrange, which has a very similar signature, but works more effectively for larger data sets. http://docs.python.org/library/functions.html#xrange
To setup GruntJS build here is the steps:
Make sure you have setup your package.json
or setup new one:
npm init
Install Grunt CLI as global:
npm install -g grunt-cli
Install Grunt in your local project:
npm install grunt --save-dev
Install any Grunt Module you may need in your build process. Just for sake of this sample I will add Concat module for combining files together:
npm install grunt-contrib-concat --save-dev
Now you need to setup your Gruntfile.js
which will describe your build process. For this sample I just combine two JS files file1.js
and file2.js
in the js
folder and generate app.js
:
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
concat: {
"options": { "separator": ";" },
"build": {
"src": ["js/file1.js", "js/file2.js"],
"dest": "js/app.js"
}
}
});
// Load required modules
grunt.loadNpmTasks('grunt-contrib-concat');
// Task definitions
grunt.registerTask('default', ['concat']);
};
Now you'll be ready to run your build process by following command:
grunt
I hope this give you an idea how to work with GruntJS build.
NOTE:
You can use grunt-init
for creating Gruntfile.js
if you want wizard-based creation instead of raw coding for step 5.
To do so, please follow these steps:
npm install -g grunt-init
git clone https://github.com/gruntjs/grunt-init-gruntfile.git ~/.grunt-init/gruntfile
grunt-init gruntfile
For Windows users: If you are using cmd.exe you need to change ~/.grunt-init/gruntfile
to %USERPROFILE%\.grunt-init\
. PowerShell will recognize the ~
correctly.
If you're using WordPress, I created a plugin that can do this & much more without needing to know how to code anything. All you need to do is add the selector of the link(s) that you want to disable & then choose "Disable all links with this selector in a new tab." from the dropdown menu that appears and click update.
Click here to view a gif that demonstrates this
You can get the free version from the WordPress.org Plugin repository to try it out.
Just to complement @Marcus Ekwall 's answer. Doing like this will get only anchor links. And you aren't going to have problems if you have a mix of anchor links and regular ones.
jQuery(document).ready(function(jQuery) {
var topMenu = jQuery("#top-menu"),
offset = 40,
topMenuHeight = topMenu.outerHeight()+offset,
// All list items
menuItems = topMenu.find('a[href*="#"]'),
// Anchors corresponding to menu items
scrollItems = menuItems.map(function(){
var href = jQuery(this).attr("href"),
id = href.substring(href.indexOf('#')),
item = jQuery(id);
//console.log(item)
if (item.length) { return item; }
});
// so we can get a fancy scroll animation
menuItems.click(function(e){
var href = jQuery(this).attr("href"),
id = href.substring(href.indexOf('#'));
offsetTop = href === "#" ? 0 : jQuery(id).offset().top-topMenuHeight+1;
jQuery('html, body').stop().animate({
scrollTop: offsetTop
}, 300);
e.preventDefault();
});
// Bind to scroll
jQuery(window).scroll(function(){
// Get container scroll position
var fromTop = jQuery(this).scrollTop()+topMenuHeight;
// Get id of current scroll item
var cur = scrollItems.map(function(){
if (jQuery(this).offset().top < fromTop)
return this;
});
// Get the id of the current element
cur = cur[cur.length-1];
var id = cur && cur.length ? cur[0].id : "";
menuItems.parent().removeClass("active");
if(id){
menuItems.parent().end().filter("[href*='#"+id+"']").parent().addClass("active");
}
})
})
Basically i replaced
menuItems = topMenu.find("a"),
by
menuItems = topMenu.find('a[href*="#"]'),
To match all links with anchor somewhere, and changed all that what was necessary to make it work with this
See it in action on jsfiddle
Well, to do this one can also use the freopen function provided in C++ - http://www.cplusplus.com/reference/cstdio/freopen/ and read the file line by line as follows -:
#include<cstdio>
#include<iostream>
using namespace std;
int main(){
freopen("path to file", "rb", stdin);
string line;
while(getline(cin, line))
cout << line << endl;
return 0;
}
Use:
$(document).ready(function() {
// put all your jQuery goodness in here.
});
Check out this for more info: http://www.learningjquery.com/2006/09/introducing-document-ready
Note: This should work as long as the script import for your JQuery library is above this call.
Update:
If for some reason your code is not loading synchronously (which I have never run into, but apparently may be possible from the comment below should not happen), you could code it like the following.
function yourFunctionToRun(){
//Your JQuery goodness here
}
function runYourFunctionWhenJQueryIsLoaded() {
if (window.$){
//possibly some other JQuery checks to make sure that everything is loaded here
yourFunctionToRun();
} else {
setTimeout(runYourFunctionWhenJQueryIsLoaded, 50);
}
}
runYourFunctionWhenJQueryIsLoaded();
You can just have package.json with specific version and do npm install
and it will install that version.
Also you dont need to depend on angular-cli
to develop your project.
I would strongly suggest you start using jQuery. Your code would look like:
$(function() {
$('form[name="myform"]').submit(function(e) {
var username = $('form[name="myform"] input[name="username"]').val();
if ( username == '') {
e.preventDefault();
$('#errors').text('*Please enter a username*');
}
});
});
For my point of view, First thing is to install soap into Centos
yum install php-soap
Second, see if the soap package exist or not
yum search php-soap
third, thus you must see some result of soap package you installed, now type a command in your terminal in the root folder for searching the location of soap for specific path
find -name soap.so
fourth, you will see the exact path where its installed/located, simply copy the path and find the php.ini to add the extension path,
usually the path of php.ini file in centos 6 is in
/etc/php.ini
fifth, add a line of code from below into php.ini file
extension='/usr/lib/php/modules/soap.so'
and then save the file and exit.
sixth run apache restart command in Centos. I think there is two command that can restart your apache ( whichever is easier for you )
service httpd restart
OR
apachectl restart
Lastly, check phpinfo() output in browser, you should see SOAP section where SOAP CLIENT, SOAP SERVER etc are listed and shown Enabled.
When using Code Sense with many keyboards, use control + , to show the list of available completions, control + . to insert the most likely completion, and control + / & shift + control + / to move between placeholder tokens. The keys are all together on the keyboard right under the home row, which is good for muscle memory.
I would say: (simple zero will work, 0px is a zero ;))
<body style="margin: 0;">
but maybe something overwrites your css. (assigns different style after you ;))
If you use Firefox - check out firebug plugin.
And in Chrome - just right-click on the page and chose "inspect element" in the menu. Find BODY in elements tree and check its properties.
If you have multiple applications on heroku and want to add changes to a particular application, run the following command : heroku git:remote -a appname and then run the following. 1) git add . 2)git commit -m "changes" 3)git push heroku master
FileReader r = new FileReader(file);
Use a file reader load the file and then write its contents to a string buffer.
The link above shows you an example of how to accomplish this. As other post to this answer say to load a file into memory you do not need write access as long as you do not plan on making changes to the actual file.
Presuming you're talking about dynamic runtime loading of DLLs, you're looking for LoadLibrary and GetProAddress. There's an example on MSDN.
I am running WHM 10.2.15-MariaDB. To permanently disable strict mode first find out which configuration file our installation prefers. For that, we need the binary’s location:
$ which mysqld
/usr/sbin/mysqld
Then, we use this path to execute the lookup:
$ /usr/sbin/mysqld --verbose --help | grep -A 1 "Default options"
Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf ~/.my.cnf
We can see that the first favored configuration file is one in the root of the etc folder but that there is a second .cnf file hidden - ~/.my.cnf. Adding the following to the ~/.my.cnf file permanently disabled strict mode for me (needs to be within the mysqld section):
[mysqld]
sql_mode=NO_ENGINE_SUBSTITUTION
I found that adding the line to /etc/my.cnf had no effect at all apart from sending me crazy.
My best guess at why you had problems with the ----- covering your first result is that you actually read the input line from a file. That line probably had a \r on the end so you ended up with something like this:
-----------test2-------test3
What happened is the machine actually printed this:
test-------test2-------test3\r-------
That means, because of the carriage return at the end of test3, that the dashes after test3 were printed over the top of the first word (and a few of the existing dashes between test and test2 but you wouldn't notice that because they were already dashes).
You need to use -I
with each directory. But you can still delimit the directories with whitespace if you use (GNU) make's foreach
:
INC=$(DIR1) $(DIR2) ...
INC_PARAMS=$(foreach d, $(INC), -I$d)
The smart thing is not to write the crypto yourself but to use something like passlib: https://bitbucket.org/ecollins/passlib/wiki/Home
It is easy to mess up writing your crypto code in a secure way. The nasty thing is that with non crypto code you often immediately notice it when it is not working since your program crashes. While with crypto code you often only find out after it is to late and your data has been compromised. Therefor I think it is better to use a package written by someone else who is knowledgable about the subject and which is based on battle tested protocols.
Also passlib has some nice features which make it easy to use and also easy to upgrade to a newer password hashing protocol if an old protocol turns out to be broken.
Also just a single round of sha512 is more vulnerable to dictionary attacks. sha512 is designed to be fast and this is actually a bad thing when trying to store passwords securely. Other people have thought long and hard about all this sort issues so you better take advantage of this.
Regarding Wolfwyrd's anwer: "On Error Resume Next" in fact turns error handling off! Not on. On Error Goto 0 turns error-handling back ON because at the least, we want the machine to catch it if we didn't write it in ourselves. Off = leaving it to you to handle it.
If you use On Error Resume Next, you need to be careful about how much code you include after it: remember, the phrase "If Err.Number <> 0 Then" only refers to the most previous error triggered.
If your block of code after "On Error Resume Next" has several places where you might reasonably expect it to fail, then you must place "If Err.number <> 0" after each and every one of those possible failure lines, to check execution.
Otherwise, after "on error resume next" means just what it says - your code can fail on as many lines as it likes and execution will continue merrily along. That's why it's a pain in the ass.
The regex module recommended in python docs, supports this
words = {'he', 'or', 'low'}
p = regex.compile(r"\L<name>", name=words)
m = p.findall('helloworld')
print(m)
output:
['he', 'low', 'or']
Some details on implementation: link
"no suitable driver" usually means that the syntax for the connection URL is incorrect.
http://www.example.com/some/path/to/resource?param1=value1
The part before the question mark must use % encoding (so %20
for space), after the question mark you can use either %20
or +
for a space. If you need an actual +
after the question mark use %2B
.
For something a little more readable, run this command once:
git config --global alias.lg "log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit --date=relative"
so that when you then run:
git lg
you get a nice readout. To show only the last line:
git lg -1
Solution found here
Because of double print function. I suggest you to use return
instead of print
inside the function definition.
def lyrics():
return "The very first line"
print(lyrics())
OR
def lyrics():
print("The very first line")
lyrics()
[ -z "${DEPLOY_ENV}" ]
checks whether DEPLOY_ENV
has length equal to zero. So you could run:
if [[ -z "${DEPLOY_ENV}" ]]; then
MY_SCRIPT_VARIABLE="Some default value because DEPLOY_ENV is undefined"
else
MY_SCRIPT_VARIABLE="${DEPLOY_ENV}"
fi
# or using a short-hand version
[[ -z "${DEPLOY_ENV}" ]] && MyVar='default' || MyVar="${DEPLOY_ENV}"
# or even shorter use
MyVar="${DEPLOY_ENV:-default_value}"
Use this in your batch file:
%~dp0\bin\Iris.exe
%~dp0
resolves to the full path of the folder in which the batch script resides.
Go to project>clean
and select the project which display error from check box and click ok , it will clear the error for you.
Click the tab which display build automatically in the project menu
And if this also does not work than restart the eclipse and try again it will work.
Create a Game model which extends Eloquent and use this:
Game::take(30)->skip(30)->get();
take()
here will get 30 records and skip()
here will offset to 30 records.
In recent Laravel versions you can also use:
Game::limit(30)->offset(30)->get();
You can access the event from onclick like this:
<button onclick="yourFunc(event);">go</button>
and at your javascript function, my advice is adding that first line statement as:
function yourFunc(e) {
e = e ? e : event;
}
then use everywhere e as event variable
Put the name of the column begin returned from the database where "ColumnName"
is. If it is a string, you can use .ToString()
. If it is another type, you need to convert it using System.Convert
.
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string column = rdr["ColumnName"].ToString();
int columnValue = Convert.ToInt32(rdr["ColumnName"]);
}
The following enables all errors:
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);
Also see the following links
%d is print as an int %s is print as a string %f is print as floating point
It should be noted that it is incorrect to say that this is different from Java. Printf stands for print format, if you do a formatted print in Java, this is exactly the same usage. This may allow you to solve interesting and new problems in both C and Java!
Some more detail for completeness in case it helps someone...
Note that the most common reason for this exception these days is attempting to load a 32 bit-specific (/platform:x86
) DLL into a process that is 64 bit or vice versa (viz. load a 64 bit-specific (/platform:x64
) DLL into a process that is 32 bit). If your platform
is non-specific (/platform:AnyCpu
), this won't arise (assuming no referenced dependencies are of the wrong bitness).
In other words, running:
%windir%\Microsoft.NET\Framework\v2.0.50727\installutil.exe
or:
%windir%\Microsoft.NET\Framework64\v2.0.50727\installutil.exe
will not work (substitute in other framework versions: v1.1.4322
(32-bit only, so this issue doesn't arise) and v4.0.30319
as desired in the above).
Obviously, as covered in the other answer, one will also need the .NET version number of the installutil
you are running to be >= (preferably =) that of the EXE/DLL file you are running the installer of.
Finally, note that in Visual Studio 2010, the tooling will default to generating x86 binaries (rather than Any CPU as previously).
Complete details of System.BadImageFormatException (saying the only cause is mismatched bittedness is really a gross oversimplification!).
Another reason for a BadImageFormatException
under an x64 installer is that in Visual Studio 2010, the default .vdproj
Install Project type generates a 32-bit InstallUtilLib
shim, even on an x64 system (Search for "64-bit managed custom actions throw a System.BadImageFormatException exception" on the page).
you can make it using js file and ajax call. while validating data using js file we can read the text of selected dropdown
$("#dropdownid").val(); for value
$("#dropdownid").text(); for selected value
catch these into two variables and take it as inputs to ajax call for a php file
$.ajax
({
url:"callingphpfile.php",//url of fetching php
method:"POST", //type
data:"val1="+value+"&val2="+selectedtext,
success:function(data) //return the data
{
}
and in php you can get it as
if (isset($_POST["val1"])) {
$val1= $_POST["val1"] ;
}
if (isset($_POST["val2"])) {
$selectedtext= $_POST["val1"];
}
First copy the source range then paste-special on target range with Transpose:=True, short sample:
Option Explicit
Sub test()
Dim sourceRange As Range
Dim targetRange As Range
Set sourceRange = ActiveSheet.Range(Cells(1, 1), Cells(5, 1))
Set targetRange = ActiveSheet.Cells(6, 1)
sourceRange.Copy
targetRange.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=True
End Sub
The Transpose function takes parameter of type Varaiant and returns Variant.
Sub transposeTest()
Dim transposedVariant As Variant
Dim sourceRowRange As Range
Dim sourceRowRangeVariant As Variant
Set sourceRowRange = Range("A1:H1") ' one row, eight columns
sourceRowRangeVariant = sourceRowRange.Value
transposedVariant = Application.Transpose(sourceRowRangeVariant)
Dim rangeFilledWithTransposedData As Range
Set rangeFilledWithTransposedData = Range("I1:I8") ' eight rows, one column
rangeFilledWithTransposedData.Value = transposedVariant
End Sub
I will try to explaine the purpose of 'calling transpose twice'. If u have row data in Excel e.g. "a1:h1" then the Range("a1:h1").Value is a 2D Variant-Array with dimmensions 1 to 1, 1 to 8. When u call Transpose(Range("a1:h1").Value) then u get transposed 2D Variant Array with dimensions 1 to 8, 1 to 1. And if u call Transpose(Transpose(Range("a1:h1").Value)) u get 1D Variant Array with dimension 1 to 8.
First Transpose changes row to column and second transpose changes the column back to row but with just one dimension.
If the source range would have more rows (columns) e.g. "a1:h3" then Transpose function just changes the dimensions like this: 1 to 3, 1 to 8 Transposes to 1 to 8, 1 to 3 and vice versa.
Hope i did not confuse u, my english is bad, sorry :-).