If you just want to do this in a specific link, just use the inline attribute list syntax as others have answered, or just use HTML.
If you want to do this in all generated <a>
tags, depends on your Markdown compiler, maybe you need an extension of it.
I am doing this for my blog these days, which is generated by pelican
, which use Python-Markdown
. And I found an extension for Python-Markdown
Phuker/markdown_link_attr_modifier, it works well. Note that an old extension called newtab
seems not work in Python-Markdown 3.x.
This should be called a warning, not an error. At least the email says that the icon file is "recommended" and not "required". You can safely ignore this warning if you target iOS 6. Of course, for iOS 7 you would need the new dimensions and also look out for the new rounding of the icon's corners
You can use the Server object in the System.Web namespace
Server.UrlEncode, Server.UrlDecode, Server.HtmlEncode, and Server.HtmlDecode.
Edit: poster added that this was a windows application and not a web one as one would believe. The items listed above would be available from the HttpUtility class inside System.Web which must be added as a reference to the project.
Passing multiple variables to a Laravel view
//Passing variable to view using compact method
$var1=value1;
$var2=value2;
$var3=value3;
return view('viewName', compact('var1','var2','var3'));
//Passing variable to view using with Method
return view('viewName')->with(['var1'=>value1,'var2'=>value2,'var3'=>'value3']);
//Passing variable to view using Associative Array
return view('viewName', ['var1'=>value1,'var2'=>value2,'var3'=>value3]);
Read here about Passing Data to Views in Laravel
[+*?.] Most special characters have no meaning inside the square brackets. This expression matches any of +, *, ? or the dot.
In the case of Maven project
Try right click on the project then select Maven -> Update Project...
then Ok
In .NET 4.0 there's the Directory.EnumerateFiles method which returns an IEnumerable<string>
and is not loading all the files in memory. It's only once you start iterating over the returned collection that files will be returned and exceptions could be handled.
If you really want a bruteforce algorithm, don't save any big list in the memory of your computer, unless you want a slow algorithm that crashes with a MemoryError.
You could try to use itertools.product like this :
from string import ascii_lowercase
from itertools import product
charset = ascii_lowercase # abcdefghijklmnopqrstuvwxyz
maxrange = 10
def solve_password(password, maxrange):
for i in range(maxrange+1):
for attempt in product(charset, repeat=i):
if ''.join(attempt) == password:
return ''.join(attempt)
solved = solve_password('solve', maxrange) # This worked for me in 2.51 sec
itertools.product(*iterables)
returns the cartesian products of the iterables you entered.
[i for i in product('bar', (42,))]
returns e.g. [('b', 42), ('a', 42), ('r', 42)]
The repeat
parameter allows you to make exactly what you asked :
[i for i in product('abc', repeat=2)]
Returns
[('a', 'a'),
('a', 'b'),
('a', 'c'),
('b', 'a'),
('b', 'b'),
('b', 'c'),
('c', 'a'),
('c', 'b'),
('c', 'c')]
Note:
You wanted a brute-force algorithm so I gave it to you. Now, it is a very long method when the password starts to get bigger because it grows exponentially (it took 62 sec to find the word 'solved').
{ text-decoration: none !important}
EDIT 1:
For you example only a{text-decoration: none}
will works
You can use a class not to interfere with the default behaviour of <a>
tags.
<a href="#" class="nounderline">
<div class="btn-group">
<button class="btn">Text</button>
<button class="btn">Text</button>
</div>
</a>
CSS:
.nounderline {
text-decoration: none !important
}
for Chrome, Firefox, Edge (and other evergreen browsers)
Simply position: sticky; top: 0;
your th
elements:
/* Fix table head */
.tableFixHead { overflow-y: auto; height: 100px; }
.tableFixHead th { position: sticky; top: 0; }
/* Just common table stuff. */
table { border-collapse: collapse; width: 100%; }
th, td { padding: 8px 16px; }
th { background:#eee; }
_x000D_
<div class="tableFixHead">
<table>
<thead>
<tr><th>TH 1</th><th>TH 2</th></tr>
</thead>
<tbody>
<tr><td>A1</td><td>A2</td></tr>
<tr><td>B1</td><td>B2</td></tr>
<tr><td>C1</td><td>C2</td></tr>
<tr><td>D1</td><td>D2</td></tr>
<tr><td>E1</td><td>E2</td></tr>
</tbody>
</table>
</div>
_x000D_
PS: if you need borders for TH elements th {box-shadow: 1px 1px 0 #000; border-top: 0;}
will help (since the default borders are not painted correctly on scroll).
For a variant of the above that uses just a bit of JS in order to accommodate for IE11 see this answer Table fixed header and scrollable body
I encountered the same problem, and I fix it by creating a new subclass of UIButton
and overriding the layoutSubviews:
method as below :
-(void)layoutSubviews {
[super layoutSubviews];
// Center image
CGPoint center = self.imageView.center;
center.x = self.frame.size.width/2;
center.y = self.imageView.frame.size.height/2;
self.imageView.center = center;
//Center text
CGRect newFrame = [self titleLabel].frame;
newFrame.origin.x = 0;
newFrame.origin.y = self.imageView.frame.size.height + 5;
newFrame.size.width = self.frame.size.width;
self.titleLabel.frame = newFrame;
self.titleLabel.textAlignment = UITextAlignmentCenter;
}
I think that the Angel García Olloqui's answer is another good solution, if you place all of them manually with interface builder but I'll keep my solution since I don't have to modify the content insets for each of my button.
NSMutableArray *objMyObject = [NSMutableArray arrayWithArray:[self reverseArray:objArrayToBeReversed]];
// Function reverseArray
-(NSArray *) reverseArray : (NSArray *) myArray {
return [[myArray reverseObjectEnumerator] allObjects];
}
And here's an example of the customizer implemented in Groovy:
Intuitively, we can see that if a problem is in P, then it is in NP. Given a potential answer for a problem in P, we can verify the answer by simply recalculating the answer.
Less obvious, and much more difficult to answer, is whether all problems in NP are in P. Does the fact that we can verify an answer in polynomial time mean that we can compute that answer in polynomial time?
There are a large number of important problems that are known to be NP-complete (basically, if any these problems are proven to be in P, then all NP problems are proven to be in P). If P = NP, then all of these problems will be proven to have an efficient (polynomial time) solution.
Most scientists believe that P!=NP. However, no proof has yet been established for either P = NP or P!=NP. If anyone provides a proof for either conjecture, they will win US $1 million.
Well, REST by design is stateless. By adding session (or anything else of that kind) you are making it stateful and defeating any purpose of having a RESTful API.
The whole idea of RESTful service is that every resource is uniquely addressable using a universal syntax for use in hypermedia links and each HTTP request should carry enough information by itself for its recipient to process it to be in complete harmony with the stateless nature of HTTP".
So whatever you are trying to do with Web API here, should most likely be re-architectured if you wish to have a RESTful API.
With that said, if you are still willing to go down that route, there is a hacky way of adding session to Web API, and it's been posted by Imran here http://forums.asp.net/t/1780385.aspx/1
Code (though I wouldn't really recommend that):
public class MyHttpControllerHandler
: HttpControllerHandler, IRequiresSessionState
{
public MyHttpControllerHandler(RouteData routeData): base(routeData)
{ }
}
public class MyHttpControllerRouteHandler : HttpControllerRouteHandler
{
protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return new MyHttpControllerHandler(requestContext.RouteData);
}
}
public class ValuesController : ApiController
{
public string GET(string input)
{
var session = HttpContext.Current.Session;
if (session != null)
{
if (session["Time"] == null)
{
session["Time"] = DateTime.Now;
}
return "Session Time: " + session["Time"] + input;
}
return "Session is not availabe" + input;
}
}
and then add the HttpControllerHandler to your API route:
route.RouteHandler = new MyHttpControllerRouteHandler();
yes I often need to have 3 or more JVM's installed. For example, I've noticed that sometimes the JRE is slightly different to the JDK version of the JRE.
My go to solution on Windows for a bit of 'packaging' is something like this:
@echo off
setlocal
@rem _________________________
@rem
@set JAVA_HOME=b:\lang\java\jdk\v1.6\u45\x64\jre
@rem
@set JAVA_EXE=%JAVA_HOME%\bin\java
@set VER=test
@set WRK=%~d0%~p0%VER%
@rem
@pushd %WRK%
cd
@echo.
@echo %JAVA_EXE% -jar %WRK%\openmrs-standalone.jar
%JAVA_EXE% -jar %WRK%\openmrs-standalone.jar
@rem
@rem _________________________
popd
endlocal
@exit /b
I think it is straightforward. The main thing is the setlocal and endlocal give your app a "personal environment" for what ever it does -- even if there's other programs to run.
Use Fail module.
- fail: msg="The execution has failed because of errors." when: flag == "failed"
Update:
Use register to store the result of a task like you have shown in your example. Then, use a task like this:
- name: Set flag
set_fact: flag = failed
when: "'FAILED' in command_result.stderr"
By default the database in a project in the Firebase Console is only readable/writeable by administrative users (e.g. in Cloud Functions, or processes that use an Admin SDK). Users of the regular client-side SDKs can't access the database, unless you change the server-side security rules.
You can change the rules so that the database is only readable/writeable by authenticated users:
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}
See the quickstart for the Firebase Database security rules.
But since you're not signing the user in from your code, the database denies you access to the data. To solve that you will either need to allow unauthenticated access to your database, or sign in the user before accessing the database.
The simplest workaround for the moment (until the tutorial gets updated) is to go into the Database panel in the console for you project, select the Rules tab and replace the contents with these rules:
{
"rules": {
".read": true,
".write": true
}
}
This makes your new database readable and writeable by anyone who knows the database's URL. Be sure to secure your database again before you go into production, otherwise somebody is likely to start abusing it.
For a (slightly) more time-consuming, but more secure, solution, call one of the signIn...
methods of Firebase Authentication to ensure the user is signed in before accessing the database. The simplest way to do this is using anonymous authentication:
firebase.auth().signInAnonymously().catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
And then attach your listeners when the sign-in is detected
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var isAnonymous = user.isAnonymous;
var uid = user.uid;
var userRef = app.dataInfo.child(app.users);
var useridRef = userRef.child(app.userid);
useridRef.set({
locations: "",
theme: "",
colorScheme: "",
food: ""
});
} else {
// User is signed out.
// ...
}
// ...
});
You have two choices, either correct your markup so that it uses correct elements and utilizes the Bootstrap grid system:
@import url('http://getbootstrap.com/dist/css/bootstrap.css');
_x000D_
<div class="container">_x000D_
<h1>About Me</h1>_x000D_
<div class="row">_x000D_
<div class="col-md-4">_x000D_
<div class="imgAbt">_x000D_
<img width="220" height="220" src="img/me.jpg" />_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-md-8">_x000D_
<p>Lots of text here...With the four tiers of grids available you're bound to run into issues where, at certain breakpoints, your columns don't clear quite right as one is taller than the other. To fix that, use a combination of a .clearfix and o</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Or, if you wish the text to closely wrap the image, change your markup to:
@import url('http://getbootstrap.com/dist/css/bootstrap.css');
_x000D_
<div class="container">_x000D_
<h1>About Me</h1>_x000D_
<div class="row">_x000D_
<div class="col-md-12">_x000D_
<img style='float:left;width:200px;height:200px; margin-right:10px;' src="img/me.jpg" />_x000D_
<p>Lots of text here...With the four tiers of grids available you're bound to run into issues where, at certain breakpoints, your columns don't clear quite right as one is taller than the other. To fix that, use a combination of a .clearfix and o</p>_x000D_
</div>_x000D_
</div>
_x000D_
Yes you can put the break-point on client side page in Visual studio
First Put the debugger in java-script code and run the page in browser
debugger
After that open your page in browser and view the inspect element you see the following view
I follow Douglas Crockford's code conventions for JavaScript. I also use his JSLint tool to validate following those conventions.
A good alternative is this:
find . -type f | xargs chmod -v 644
and for directories:
find . -type d | xargs chmod -v 755
and to be more explicit:
find . -type f | xargs -I{} chmod -v 644 {}
Assuming that the action button uses the same controller $scope
as the directive, just define function updateMap
on $scope
inside the link function. Your controller can then call that function when the action button is clicked.
<div ng-controller="MyCtrl">
<map></map>
<button ng-click="updateMap()">call updateMap()</button>
</div>
app.directive('map', function() {
return {
restrict: 'E',
replace: true,
template: '<div></div>',
link: function($scope, element, attrs) {
$scope.updateMap = function() {
alert('inside updateMap()');
}
}
}
});
As per @FlorianF's comment, if the directive uses an isolated scope, things are more complicated. Here's one way to make it work: add a set-fn
attribute to the map
directive which will register the directive function with the controller:
<map set-fn="setDirectiveFn(theDirFn)"></map>
<button ng-click="directiveFn()">call directive function</button>
scope: { setFn: '&' },
link: function(scope, element, attrs) {
scope.updateMap = function() {
alert('inside updateMap()');
}
scope.setFn({theDirFn: scope.updateMap});
}
function MyCtrl($scope) {
$scope.setDirectiveFn = function(directiveFn) {
$scope.directiveFn = directiveFn;
};
}
queryParams
queryParams
is another input of routerLink
where they can be passed like
<a [routerLink]="['../']" [queryParams]="{prop: 'xxx'}">Somewhere</a>
fragment
<a [routerLink]="['../']" [queryParams]="{prop: 'xxx'}" [fragment]="yyy">Somewhere</a>
routerLinkActiveOptions
To also get routes active class set on parent routes:
[routerLinkActiveOptions]="{ exact: false }"
To pass query parameters to this.router.navigate(...)
use
let navigationExtras: NavigationExtras = {
queryParams: { 'session_id': sessionId },
fragment: 'anchor'
};
// Navigate to the login page with extras
this.router.navigate(['/login'], navigationExtras);
See also https://angular.io/guide/router#query-parameters-and-fragments
Normally, When you copy a cell you will find the below statement written down in the status bar (in the bottom of your sheet)
"Select destination and Press Enter or Choose Paste"
Then you press whether Enter or choose paste to paste the value of the cell.
If you didn't press Esc afterwards you will be able to paste the value of the cell several times
Application.CutCopyMode = False does the same like the Esc button, if you removed it from your code you will find that you are able to paste the cell value several times again.
And if you closed the Excel without pressing Esc you will get the warning 'There is a large amount of information on the Clipboard....'
I'm not sure why your current code is failing (what is the Exception you get?), but I would like to point out this approach performs O(N-squared). Consider pre-sorting your input arrays (if they are not defined to be pre-sorted) and merging the sorted arrays:
http://www.algolist.net/Algorithms/Merge/Sorted_arrays
Sorting is generally O(N logN) and the merge is O(m+n).
You want this:
AAPL:
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
The YAML equivalent of a JSON object is a mapping, which looks like these:
# flow style
{ foo: 1, bar: 2 }
# block style
foo: 1
bar: 2
Note that the first characters of the keys in a block mapping must be in the same column. To demonstrate:
# OK
foo: 1
bar: 2
# Parse error
foo: 1
bar: 2
The equivalent of a JSON array in YAML is a sequence, which looks like either of these (which are equivalent):
# flow style
[ foo bar, baz ]
# block style
- foo bar
- baz
In a block sequence the -
s must be in the same column.
Let's turn your JSON into YAML. Here's your JSON:
{"AAPL": [
{
"shares": -75.088,
"date": "11/27/2015"
},
{
"shares": 75.088,
"date": "11/26/2015"
},
]}
As a point of trivia, YAML is a superset of JSON, so the above is already valid YAML—but let's actually use YAML's features to make this prettier.
Starting from the inside out, we have objects that look like this:
{
"shares": -75.088,
"date": "11/27/2015"
}
The equivalent YAML mapping is:
shares: -75.088
date: 11/27/2015
We have two of these in an array (sequence):
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
Note how the -
s line up and the first characters of the mapping keys line up.
Finally, this sequence is itself a value in a mapping with the key AAPL
:
AAPL:
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
Parsing this and converting it back to JSON yields the expected result:
{
"AAPL": [
{
"date": "11/27/2015",
"shares": -75.088
},
{
"date": "11/26/2015",
"shares": 75.088
}
]
}
You can see it (and edit it interactively) here.
I have try this my new code and it might be helpful to you, it works perfectly in google chromr
hr {
color: #f00;
background: #f00;
width: 75%;
height: 5px;
}
To keep line breaks when pasting in notepad, replace this line in the macro:
strTemp = ActiveCell.Value
by:
strTemp = Replace(ActiveCell.Value, Chr(10), vbCrLf)
For solving your Base Table or view not found error you can do As @Alexey Mezenin said that change table name category_post
to category_posts
,
but if you don't want to change the name like in my case i am using inventory
table so i don't want to suffix it by s
so i will provide table name in model as protected $table = 'Table_name_as_you_want'
and then there is no need to change table name:
Change your Model of the module in which you are getting error for example:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Inventory extends Model
{
protected $table = 'inventory';
protected $fillable = [
'supply', 'order',
];
}
you have to provide table name in model then it will not give error.
I have just started checking out Angular(so im quite sure there are other ways to get it done which are more optimum), and i came across this question while searching for examples of ng-repeat.
The requirement by the poser(with the update):
"...but my real requirement is display the items as shown below.."
looked real-world enough (and simple), so i thought ill give it a spin and attempt to get the exact desired structure.
angular.module('appTest', [])_x000D_
.controller("repeatCtrl", function($scope) {_x000D_
$scope.items = [{_x000D_
Name: "Soap",_x000D_
Price: "25",_x000D_
Quantity: "10"_x000D_
}, {_x000D_
Name: "Bag",_x000D_
Price: "100",_x000D_
Quantity: "15"_x000D_
}, {_x000D_
Name: "Pen",_x000D_
Price: "15",_x000D_
Quantity: "13"_x000D_
}];_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<body ng-app="appTest">_x000D_
<section ng-controller="repeatCtrl">_x000D_
<table>_x000D_
<thead>_x000D_
<tr ng-repeat="item in items | limitTo:1">_x000D_
<th ng-repeat="(key, val) in item">_x000D_
{{key}}_x000D_
</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr ng-repeat="item in items">_x000D_
<td ng-repeat="(key, val) in item">_x000D_
{{val}}_x000D_
</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
</section>_x000D_
</body>
_x000D_
The limitTo:(n) filter is the key. Im still not sure if having multiple ng-repeat is an optimum way to go about it, but can't think of another alternative currently.
You can use getElementsByTagName function, it returns a HTMLCollection of elements with the given tag name.
var elements = document.getElementsByTagName("input")
for (var i = 0; i < elements.length; i++) {
if(elements[i].value == "") {
alert('empty');
//Do something here
}
}
You can also use document.myform.getElementsByTagName
provided you have given a name to yoy form
This happens generally when you try access another domain's resources.
This is a security feature for avoiding everyone freely accessing any resources of that domain (which can be accessed for example to have an exact same copy of your website on a pirate domain).
The header of the response, even if it's 200OK do not allow other origins (domains, port) to access the ressources.
You can fix this problem if you are the owner of both domains:
To change that, you can write this in the .htaccess of the requested domain file:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
If you only want to give access to one domain, the .htaccess should look like this:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin 'https://my-domain.tdl'
</IfModule>
If you set this into the response header of the requested file, you will allow everyone to access the ressources:
Access-Control-Allow-Origin : *
OR
Access-Control-Allow-Origin : http://www.my-domain.com
Peace and code ;)
It's the same problem with managed and easy to use programming language as always - they are slow (and sometimes memory-eating).
These are languages to do control rather than processing. If I would have to write application to transform images and had to use Python too all the processing could be written in C++ and connected to Python via bindings while interface and process control would be definetely Python.
If your using a new version of larval 7 >= you can use from your homested directory vagrant provision
I met the same problem. (Window 10 environment) I solved it by deleting the JAVA_HOME="C:\Program Files\Java\jdk1.8.0_161\bin" in the User Variables instead of adding to the System Variables directly.
Then I test that editing JAVA_HOME="C:\Program Files\Java\jdk1.8.0_161\" worked too. When I run "mvn -version" in command prompt window, it shows "Java home: C:\Program Files\Java\jdk1.8.0_161\jre".
In conclusion, I guess the JAVA_HOME shouldn't include bin directory.
Look at the types of those properties:
In [1]: import datetime
In [2]: d = datetime.date.today()
In [3]: type(d.month)
Out[3]: <type 'int'>
In [4]: type(d.day)
Out[4]: <type 'int'>
Both are integers. So there is no automatic way to do what you want. So in the narrow sense, the answer to your question is no.
If you want leading zeroes, you'll have to format them one way or another. For that you have several options:
In [5]: '{:02d}'.format(d.month)
Out[5]: '03'
In [6]: '%02d' % d.month
Out[6]: '03'
In [7]: d.strftime('%m')
Out[7]: '03'
In [8]: f'{d.month:02d}'
Out[8]: '03'
For longitudes use: Decimal(9,6)
, and latitudes use: Decimal(8,6)
If you're not used to precision and scale parameters, here's a format string visual:
###.######
and ##.######
Here is what backup in this sense really means:
Android's backup service allows you to copy your persistent application data to remote "cloud" storage, in order to provide a restore point for the application data and settings. If a user performs a factory reset or converts to a new Android-powered device, the system automatically restores your backup data when the application is re-installed. This way, your users don't need to reproduce their previous data or application settings.
~Taken from http://developer.android.com/guide/topics/data/backup.html
You can register for this backup service as a developer here: https://developer.android.com/google/backup/signup.html
The type of data that can be backed up are files, databases, sharedPreferences, cache, and lib. These are generally stored in your device's /data/data/[com.myapp] directory, which is read-protected and cannot be accessed unless you have root privileges.
UPDATE: You can see this flag listed on BackupManager's api doc: BackupManager
This is not an answer to the original question "What are the differences between .gitignore and .gitkeep?" but posting here to help people to keep track of empty dir in a simple fashion. To track empty directory and knowling that .gitkeep
is not official part of git,
just add a empty (with no content) .gitignore
file in it.
So for e.g. if you have /project/content/posts
and sometimes posts
directory might be empty then create empty file /project/content/posts/.gitignore
with no content to track that directory and its future files in git.
Yes, but you need to move the variable assignment into the query:
SET @user := 123456;
SELECT @group := `group` FROM user WHERE user = @user;
SELECT * FROM user WHERE `group` = @group;
Test case:
CREATE TABLE user (`user` int, `group` int);
INSERT INTO user VALUES (123456, 5);
INSERT INTO user VALUES (111111, 5);
Result:
SET @user := 123456;
SELECT @group := `group` FROM user WHERE user = @user;
SELECT * FROM user WHERE `group` = @group;
+--------+-------+
| user | group |
+--------+-------+
| 123456 | 5 |
| 111111 | 5 |
+--------+-------+
2 rows in set (0.00 sec)
Note that for SET
, either =
or :=
can be used as the assignment operator. However inside other statements, the assignment operator must be :=
and not =
because =
is treated as a comparison operator in non-SET statements.
UPDATE:
Further to comments below, you may also do the following:
SET @user := 123456;
SELECT `group` FROM user LIMIT 1 INTO @group;
SELECT * FROM user WHERE `group` = @group;
I know this thread is a bit old, but it took me some time to get to the heart of this, so I wanted to share.
In my project, I had the main script in a parent directory, and, to differentiate the modules, I put all the supporting modules in a sub-folder called "modules". In my main script, I import these modules like this (for a module called report.py):
from modules.report import report, reportError
If I call my main script, this works. HOWEVER, I wanted to test each module by including a main()
in each, and calling each directly, as:
python modules/report.py
Now Python complains that it can't find "a module called modules". The key here is that, by default, Python includes the folder of the script in its search path, BUT NOT THE CWD. So what this error says, really, is "I can't find a modules subfolder". The is because there is no "modules" subdirectory from the directory where the report.py module resides.
I find that the neatest solution to this is to append the CWD in Python search path by including this at the top:
import sys
sys.path.append(".")
Now Python searches the CWD (current directory), finds the "modules" sub-folder, and all is well.
If you ever wondered how to do it using the new BDD style of Mockito:
willThrow(new Exception()).given(mockedObject).methodReturningVoid(...));
And for future reference one may need to throw exception and then do nothing:
willThrow(new Exception()).willDoNothing().given(mockedObject).methodReturningVoid(...));
Some people mentioning sc delete
as an answer. This is how I did it, but it took me a while to find the <service-name>
parameter.
The command sc query type= service
(note, it's very particular with formatting, the space before "service" is necessary) will output a list of Windows services installed, complete with their qualified name to be used with sc delete <service-name>
command.
The list is quite long so you may consider piping the output to a text file (i.e. >> C:\test.txt
) and then searching through that.
The SERVICE_NAME
is the one to use with sc delete <service-name>
command.
Have you tried this in your application.properties?
spring.jackson.time-zone= # Time zone used when formatting dates. For instance `America/Los_Angeles`
Every method in Web API will return data (JSON) without serialization.
However, in order to return JSON Data in MVC controllers, we will set the returned Action Result type to JsonResult and call the Json method on our object to ensure it is packaged in JSON.
For me the issue is resolved by adding domain name in user name as follow:
string userName="yourUserName";
string password="passowrd";
string hostName="LdapServerHostName";
string domain="yourDomain";
System.DirectoryServices.AuthenticationTypes option = System.DirectoryServices.AuthenticationTypes.SecureSocketsLayer;
string userNameWithDomain = string.Format("{0}@{1}",userName , domain);
DirectoryEntry directoryOU = new DirectoryEntry("LDAP://" + hostName, userNameWithDomain, password, option);
This answer is all about authorization and it is a complement of my previous answer about authentication
Why another answer? I attempted to expand my previous answer by adding details on how to support JSR-250 annotations. However the original answer became the way too long and exceeded the maximum length of 30,000 characters. So I moved the whole authorization details to this answer, keeping the other answer focused on performing authentication and issuing tokens.
@Secured
annotationBesides authentication flow shown in the other answer, role-based authorization can be supported in the REST endpoints.
Create an enumeration and define the roles according to your needs:
public enum Role {
ROLE_1,
ROLE_2,
ROLE_3
}
Change the @Secured
name binding annotation created before to support roles:
@NameBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface Secured {
Role[] value() default {};
}
And then annotate the resource classes and methods with @Secured
to perform the authorization. The method annotations will override the class annotations:
@Path("/example")
@Secured({Role.ROLE_1})
public class ExampleResource {
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response myMethod(@PathParam("id") Long id) {
// This method is not annotated with @Secured
// But it's declared within a class annotated with @Secured({Role.ROLE_1})
// So it only can be executed by the users who have the ROLE_1 role
...
}
@DELETE
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
@Secured({Role.ROLE_1, Role.ROLE_2})
public Response myOtherMethod(@PathParam("id") Long id) {
// This method is annotated with @Secured({Role.ROLE_1, Role.ROLE_2})
// The method annotation overrides the class annotation
// So it only can be executed by the users who have the ROLE_1 or ROLE_2 roles
...
}
}
Create a filter with the AUTHORIZATION
priority, which is executed after the AUTHENTICATION
priority filter defined previously.
The ResourceInfo
can be used to get the resource Method
and resource Class
that will handle the request and then extract the @Secured
annotations from them:
@Secured
@Provider
@Priority(Priorities.AUTHORIZATION)
public class AuthorizationFilter implements ContainerRequestFilter {
@Context
private ResourceInfo resourceInfo;
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
// Get the resource class which matches with the requested URL
// Extract the roles declared by it
Class<?> resourceClass = resourceInfo.getResourceClass();
List<Role> classRoles = extractRoles(resourceClass);
// Get the resource method which matches with the requested URL
// Extract the roles declared by it
Method resourceMethod = resourceInfo.getResourceMethod();
List<Role> methodRoles = extractRoles(resourceMethod);
try {
// Check if the user is allowed to execute the method
// The method annotations override the class annotations
if (methodRoles.isEmpty()) {
checkPermissions(classRoles);
} else {
checkPermissions(methodRoles);
}
} catch (Exception e) {
requestContext.abortWith(
Response.status(Response.Status.FORBIDDEN).build());
}
}
// Extract the roles from the annotated element
private List<Role> extractRoles(AnnotatedElement annotatedElement) {
if (annotatedElement == null) {
return new ArrayList<Role>();
} else {
Secured secured = annotatedElement.getAnnotation(Secured.class);
if (secured == null) {
return new ArrayList<Role>();
} else {
Role[] allowedRoles = secured.value();
return Arrays.asList(allowedRoles);
}
}
}
private void checkPermissions(List<Role> allowedRoles) throws Exception {
// Check if the user contains one of the allowed roles
// Throw an Exception if the user has not permission to execute the method
}
}
If the user has no permission to execute the operation, the request is aborted with a 403
(Forbidden).
To know the user who is performing the request, see my previous answer. You can get it from the SecurityContext
(which should be already set in the ContainerRequestContext
) or inject it using CDI, depending on the approach you go for.
If a @Secured
annotation has no roles declared, you can assume all authenticated users can access that endpoint, disregarding the roles the users have.
Alternatively to defining the roles in the @Secured
annotation as shown above, you could consider JSR-250 annotations such as @RolesAllowed
, @PermitAll
and @DenyAll
.
JAX-RS doesn't support such annotations out-of-the-box, but it could be achieved with a filter. Here are a few considerations to keep in mind if you want to support all of them:
@DenyAll
on the method takes precedence over @RolesAllowed
and @PermitAll
on the class.@RolesAllowed
on the method takes precedence over @PermitAll
on the class.@PermitAll
on the method takes precedence over @RolesAllowed
on the class.@DenyAll
can't be attached to classes.@RolesAllowed
on the class takes precedence over @PermitAll
on the class.So an authorization filter that checks JSR-250 annotations could be like:
@Provider
@Priority(Priorities.AUTHORIZATION)
public class AuthorizationFilter implements ContainerRequestFilter {
@Context
private ResourceInfo resourceInfo;
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
Method method = resourceInfo.getResourceMethod();
// @DenyAll on the method takes precedence over @RolesAllowed and @PermitAll
if (method.isAnnotationPresent(DenyAll.class)) {
refuseRequest();
}
// @RolesAllowed on the method takes precedence over @PermitAll
RolesAllowed rolesAllowed = method.getAnnotation(RolesAllowed.class);
if (rolesAllowed != null) {
performAuthorization(rolesAllowed.value(), requestContext);
return;
}
// @PermitAll on the method takes precedence over @RolesAllowed on the class
if (method.isAnnotationPresent(PermitAll.class)) {
// Do nothing
return;
}
// @DenyAll can't be attached to classes
// @RolesAllowed on the class takes precedence over @PermitAll on the class
rolesAllowed =
resourceInfo.getResourceClass().getAnnotation(RolesAllowed.class);
if (rolesAllowed != null) {
performAuthorization(rolesAllowed.value(), requestContext);
}
// @PermitAll on the class
if (resourceInfo.getResourceClass().isAnnotationPresent(PermitAll.class)) {
// Do nothing
return;
}
// Authentication is required for non-annotated methods
if (!isAuthenticated(requestContext)) {
refuseRequest();
}
}
/**
* Perform authorization based on roles.
*
* @param rolesAllowed
* @param requestContext
*/
private void performAuthorization(String[] rolesAllowed,
ContainerRequestContext requestContext) {
if (rolesAllowed.length > 0 && !isAuthenticated(requestContext)) {
refuseRequest();
}
for (final String role : rolesAllowed) {
if (requestContext.getSecurityContext().isUserInRole(role)) {
return;
}
}
refuseRequest();
}
/**
* Check if the user is authenticated.
*
* @param requestContext
* @return
*/
private boolean isAuthenticated(final ContainerRequestContext requestContext) {
// Return true if the user is authenticated or false otherwise
// An implementation could be like:
// return requestContext.getSecurityContext().getUserPrincipal() != null;
}
/**
* Refuse the request.
*/
private void refuseRequest() {
throw new AccessDeniedException(
"You don't have permissions to perform this action.");
}
}
Note: The above implementation is based on the Jersey RolesAllowedDynamicFeature
. If you use Jersey, you don't need to write your own filter, just use the existing implementation.
This method works fine both in http and https. Just one line :)
if (Uri.IsWellFormedUriString("https://www.google.com", UriKind.Absolute))
MSDN: IsWellFormedUriString
You can use the key
parameter to list.sort()
:
my_list.sort(key=lambda x: x[1])
or, slightly faster,
my_list.sort(key=operator.itemgetter(1))
(As with any module, you'll need to import operator
to be able to use it.)
I use com0com - With Signed Driver, on windows 7 x64 to emulate COM3 AND COM4 as a pair.
Then i use COM Dataport Emulator to recieve from COM4.
Then i open COM3 with the app im developping (c#) and send data to COM3.
The data sent thru COM3 is received by COM4 and shown by 'COM Dataport Emulator' who can also send back a response (not automated).
So with this 2 great programs i managed to emulate Serial RS-232 comunication.
Hope it helps.
Both programs are free!!!!!
Direct link to the .Net-3.5-Full-Setup
http://download.microsoft.com/download/6/0/f/60fc5854-3cb8-4892-b6db-bd4f42510f28/dotnetfx35.exe
Direct link to the .Net-3.5-SP1-Full-Setup
http://download.microsoft.com/download/2/0/e/20e90413-712f-438c-988e-fdaa79a8ac3d/dotnetfx35.exe
Thanks to Dzmitry Lahoda!
I have a PowerShell script I have to run on a computer so out of date that it doesn't have [String]::IsNullOrWhiteSpace(), so I wrote my own.
function IsNullOrWhitespace($str)
{
if ($str)
{
return ($str -replace " ","" -replace "`t","").Length -eq 0
}
else
{
return $TRUE
}
}
The log file will be where the configuration file (usually /etc/redis/redis.conf
) says it is :)
By default, logfile stdout
which probably isn't what you are looking for. If redis is running daemonized, then that log configuration means logs will be sent to /dev/null
, i.e. discarded.
Summary: set logfile /path/to/my/log/file.log
in your config and redis logs will be written to that file.
The solution I found is very simple. Use Window's WMIC & Java's Runtime to locate & kill the process.
Part 1: You need to put some sort of identifier into your app's startup command line. E.g. something like:
String id = "com.domain.app";
Part 2: When you run your app, make sure to include the string. Let's say you start it from within Java, do the following:
Runtime.getRuntime().exec(
"C:\...\javaw.exe -cp ... -Dwhatever=" + id + " com.domain.app.Main"
);
Part 3: To kill the process, use Window's WMIC. Just make sure you app was started containing your id from above:
Runtime.getRuntime().exec(
"wmic process Where \"CommandLine Like '%" + id + "%'\" Call Terminate"
);
A good example of using both in a function is:
>>> def foo(*arg,**kwargs):
... print arg
... print kwargs
>>>
>>> a = (1, 2, 3)
>>> b = {'aa': 11, 'bb': 22}
>>>
>>>
>>> foo(*a,**b)
(1, 2, 3)
{'aa': 11, 'bb': 22}
>>>
>>>
>>> foo(a,**b)
((1, 2, 3),)
{'aa': 11, 'bb': 22}
>>>
>>>
>>> foo(a,b)
((1, 2, 3), {'aa': 11, 'bb': 22})
{}
>>>
>>>
>>> foo(a,*b)
((1, 2, 3), 'aa', 'bb')
{}
Solution:
Actually, all unshift
/push
and shift
/pop
mutate the origin array.
The unshift
/push
add an item to the existed array from begin/end and shift
/pop
remove an item from the beginning/end of an array.
But there are few ways to add items to an array without a mutation. the result is a new array, to add to the end of array use below code:
const originArray = ['one', 'two', 'three'];
const newItem = 4;
const newArray = originArray.concat(newItem); // ES5
const newArray2 = [...originArray, newItem]; // ES6+
To add to begin of original array use below code:
const originArray = ['one', 'two', 'three'];
const newItem = 0;
const newArray = (originArray.slice().reverse().concat(newItem)).reverse(); // ES5
const newArray2 = [newItem, ...originArray]; // ES6+
With the above way, you add to the beginning/end of an array without a mutation.
Different versions of react between my shared libraries seemed to be the problem (16 and 17), changed both to 16.
I do not have a USB serial device, but there must be a way to find the real ports using the HAL libraries directly:
====================================================================
#! /usr/bin/env bash
#
# Uses HAL to find existing serial hardware
#
for sport in $(hal-find-by-capability --capability serial) ; do
hal-get-property --udi "${sport}" --key serial.device
done
====================================================================
The posted python-dbus code nor this sh script lists the bluetooth /dev/rfcomm* devices, so it is not the best solution.
Note that on other unix platforms, the serial ports are not named ttyS? and even in linux, some serial cards allow you to name the devices. Assuming a pattern in the serial devices names is wrong.
Usinge the file
argument in the print
function, you can have different files per print:
print('Redirect output to file', file=open('/tmp/example.log', 'w'))
Change your input to a button element and you can use the Font Awesome classes on it. The alignment of the glyph isn't great in the demo, but you get the idea:
<div id="search-bar">
<form method="get" action="search.php" autocomplete="off" name="form_search">
<input type="hidden" name="type" value="videos" />
<input autocomplete="on" id="keyword" name="keyword" value="Search Videos" onclick="clickclear(this,
'Search Videos')" onblur="clickrecall(this,'Search Videos')" style="font-family: verdana; font-weight:bold;
font-size: 10pt; height: 28px; width:186px; color: #000000; padding-left: 2px; border: 1px solid black; background-color:
#ffffff" /><!--
--><button class="icon-search">Search</button>
<div id="searchBoxSuggestions"></div>
</form>
</div>
#search-bar .icon-search {
width: 30px;
height: 30px;
background: black;
color: white;
border: none;
overflow: hidden;
vertical-align: middle;
padding: 0;
}
#search-bar .icon-search:before {
display: inline-block;
width: 30px;
height: 30px;
}
The advantage here is that the form is still fully functional without having to add event handlers for elements that aren't buttons but look like one.
Considering that a LocalDb instance only intended for use in development. LocalDb is not available for production servers When you deploy the final result.
I think your connection string is pointing to a LocalDb instance and you need to take certain steps to turn it into the SQL Server database. It's not just a matter of copying an mdf file either. It will possibly differ from one hosting company to another, but typically, you need to create a backup of your existing database (a .bak file) and then restore that to the hosting company's SQL Server. You should ask them where you can find instructions on deploying your database into production.
sql = ("select field1, field2, field3, field4 "
"from table "
"where condition1={} "
"and condition2={}").format(1, 2)
Output: 'select field1, field2, field3, field4 from table
where condition1=1 and condition2=2'
if the value of condition should be a string, you can do like this:
sql = ("select field1, field2, field3, field4 "
"from table "
"where condition1='{0}' "
"and condition2='{1}'").format('2016-10-12', '2017-10-12')
Output: "select field1, field2, field3, field4 from table where
condition1='2016-10-12' and condition2='2017-10-12'"
syntax is:
sheet.addMergedRegion(new CellRangeAddress(start-col,end-col,start-cell,end-cell));
Example:
sheet.addMergedRegion(new CellRangeAddress(4, 4, 0, 5));
Here the cell 0 to cell 5 will be merged of the 4th row.
Some of the links provided are only settings for Windows 2003's version of "Scheduled Tasks"
In Windows Server 2008 the "Tasks" setup only has a box with options for "5 Minutes, 10 minutes, 15 minutes, 30 mins, and 1 hour" (screen shot: http://i46.tinypic.com/2gwx7r8.jpg)... where the Window 2003 was a "enter whatever number you want" textbox.
I thought doing an "Export" and editing the XML from: PT30M to PT2M
and importing that as a new task would "trick" Tasks into repeating every 2 mins, but it didn't like that
My workaround for getting a task to run every 2 mins in Windows 2008 was to (ugggh) setup 30 different "triggers" for my task repeating every hour but staring at :00, :02, :04, :06 and so on and so on.... took me 8-10 mins to setup but I only had to do it once :-)
Same as @axtavt, but you can use also the RequestDispatcher constant.
request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);
executes a command and never returns.
It's like a return
statement in a function.
If the command is not found exec
returns false.
It never returns true, because if the command is found it never returns at all.
There is also no point in returning STDOUT
, STDERR
or exit status of the command.
You can find documentation about it in perlfunc
,
because it is a function.
executes a command and your Perl script is continued after the command has finished.
The return value is the exit status of the command.
You can find documentation about it in perlfunc
.
like system
executes a command and your perl script is continued after the command has finished.
In contrary to system
the return value is STDOUT
of the command.
qx//
is equivalent to backticks.
You can find documentation about it in perlop
, because unlike system
and exec
it is an operator.
What is missing from the above is a way to execute a command asynchronously.
That means your perl script and your command run simultaneously.
This can be accomplished with open
.
It allows you to read STDOUT
/STDERR
and write to STDIN
of your command.
It is platform dependent though.
There are also several modules which can ease this tasks.
There is IPC::Open2
and IPC::Open3
and IPC::Run
, as well as
Win32::Process::Create
if you are on windows.
You could also use a dummy form arround it like:
<mat-card-footer>
<form (submit)="search(ref, id, forename, surname, postcode)" action="#">
<button mat-raised-button type="submit" class="successButton" id="invSearch" title="Click to perform search." >Search</button>
</form>
</mat-card-footer>
the search function has to return false
to make sure that the action doesn't get executed.
Just make sure the form is focused (should be when you have the input in the form) when you press enter.
Ensure that your network is brought down before loading module:
sudo stop networking
It helped me - https://help.ubuntu.com/community/UbuntuBonding
Quoting spaces inside variables such that the shell will re-interpret things properly is hard. It's this type of thing that prompts me to reach for a stronger language. Whether that's perl or python or ruby or whatever (I choose perl, but that's not always for everyone), it's just something that will allow you to bypass the shell for quoting.
It's not that I've never managed to get it right with liberal doses of eval, but just that eval gives me the eebie-jeebies (becomes a whole new headache when you want to take user input and eval it, though in this case you'd be taking stuff that you wrote and evaling that instead), and that I've gotten headaches in debugging.
With perl, as my example, I'd be able to do something like:
@tar_cmd = ( qw(tar cv), $directory );
@encrypt_cmd = ( qw(openssl des3 -salt) );
@split_cmd = ( qw(split -b 1024m -), $backup_file );
The hard part here is doing the pipes - but a bit of IO::Pipe, fork, and reopening stdout and stderr, and it's not bad. Some would say that's worse than quoting the shell properly, and I understand where they're coming from, but, for me, this is easier to read, maintain, and write. Heck, someone could take the hard work out of this and create a IO::Pipeline module and make the whole thing trivial ;-)
Try this:
You need to add left: 0
and right: 0
(not supported by IE6). Or specify a width
In response to the other question which was marked as duplicate (see here) I figured out a quick and easy solution based on the answer of Soren:
data.Tasks.AddRange(
data.Task.AsEnumerable().Select(t => new Task{
creator_id = t.ID,
start_date = t.Incident.DateOpened,
end_date = t.Incident.DateCLosed,
product_code = t.Incident.ProductCode
// so on...
})
);
data.SaveChanges();
Note: This solution only works if you have a navigation property (foreign key) on the Task class (here called 'Incident'). If you don't have that, you can just use one of the other posted solutions with "AsQueryable()".
Disable:
$('input').attr('readonly', true); // Disable it.
$('input').addClass('text-muted'); // Gray it out with bootstrap.
Enable:
$('input').attr('readonly', false); // Enable it.
$('input').removeClass('text-muted'); // Back to normal color with bootstrap.
You can simply make the start_date required using
<input type="submit" value="Submit" required />
You don't even need the checkform() then.
Thanks
Parenthesis is not required to instantiate a class object when you don't intend to use a parameterised constructor.
Just use Foo foo2;
It will work.
This is my first post which support only a single page http://www.techumber.com/html-to-pdf-conversion-using-javascript/
Now, the second one will support the multiple pages. http://www.techumber.com/how-to-convert-html-to-pdf-using-javascript-multipage/
A more elegant solution than creating an anonymous function who's sole purpose is to wrap another, is to use es5's bind
function. The bind function creates a new function that, when called, has its this
keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
Instead of:
expect(function () { parser.parse(raw, config); } ).toThrow("Parsing is not possible");
Consider:
expect(parser.parse.bind(parser, raw, config)).toThrow("Parsing is not possible");
The bind syntax allows you to test functions with different this
values, and in my opinion makes the test more readable. See also: https://stackoverflow.com/a/13233194/1248889
You should use font-size for controlling the height, it is widely supported amongst browsers. And in order to add spacing, you should use padding. Forexample,
.inputField{
font-size: 30px;
padding-top: 10px;
padding-bottom: 10px;
}
I think process.communicate() would be suitable for output having small size. For larger output it would not be the best approach.
1-> Using File Default Config- Angular-cli comes from the ember-cli project. To run the application on specific port, create an .ember-cli file in the project root. Add your JSON config in there:
{ "port": 1337 }
2->Using Command Line Tool Run this command in Angular-Cli
ng serve --port 1234
To change the port number permanently:
Goto
node_modules/angular-cli/commands/server.js
Search for var defaultPort = process.env.PORT || 4200;
(change 4200 to anything else you want).
Arrays in JavaScript don't use strings as keys. You will probably find that the value is there, but the key is an integer.
If you make Dict
into an object, this will work:
var dict = {};
var addPair = function (myKey, myValue) {
dict[myKey] = myValue;
};
var giveValue = function (myKey) {
return dict[myKey];
};
The myKey
variable is already a string, so you don't need more quotes.
Change Background Color using on click button jquery
Below is the code of jquery, which you can put in your head tag.
jQuery Code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").addClass("myclass");
});
});
</script>
CSS Code:
<style>
.myclass {
background-color: red;
padding: 100px;
color: #fff;
}
</style>
HTML Code:
<body>
<div>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</div>
<button>Click Here</button>
</body>
like say a class .c1 has height:40px; how do I get rid of this height property?
Sadly, you can't. CSS doesn't have a "default" placeholder.
In that case, you would reset the property using
height: auto;
as @Ben correctly points out, in some cases, inherit
is the correct way to go, for example when resetting the text colour of an a
element (that property is inherited from the parent element):
a { color: inherit }
Either:
"ME" + str(i)
Or:
"ME%d" % i
The second one is usually preferred, especially if you want to build a string from several tokens.
I use this URL to enter phpMyAdmin http://localhost:2145/phpmyadmin but get the following error:
"phpMyAdmin tried to connect to the MySQL server, and the server rejected the connection. You should check the host, username and password in your configuration and make sure that they correspond to the information given by the administrator of the MySQL server"
my config.inc.php file is
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';
$cfg['Servers'][$i]['host'] = 'localhost:2145';
$cfg['Servers'][$i]['connect_type'] = 'cookie';
$cfg['Servers'][$i]['compress'] = false;
$cfg['Servers'][$i]['AllowNoPassword'] = true;
/* User used to manipulate with storage */
// $cfg['Servers'][$i]['controlhost'] = '';
// $cfg['Servers'][$i]['controlport'] = '';
$cfg['Servers'][$i]['controluser'] = '';
$cfg['Servers'][$i]['controlpass'] = '';
this change resolve the mistake for me
$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = '';
/* Server parameters */
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
$cfg['Servers'][$i]['AllowNoPassword'] = true;
and then
sudo service mysql stop
/opt/lampp/lampp start
and problem solved
On a 64-bit Windows system, the reading of the various environment variables and some Windows Registry keys is redirected to different sources, depending whether the process doing the reading is 32-bit or 64-bit.
The table below lists these data sources:
X = HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion
Y = HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion
Z = HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
READING ENVIRONMENT VARIABLES: Source for 64-bit process Source for 32-bit process
-------------------------------|----------------------------------------|--------------------------------------------------------------
%ProgramFiles% : X\ProgramW6432Dir X\ProgramFilesDir (x86)
%ProgramFiles(x86)% : X\ProgramFilesDir (x86) X\ProgramFilesDir (x86)
%ProgramW6432% : X\ProgramW6432Dir X\ProgramW6432Dir
%CommonProgramFiles% : X\CommonW6432Dir X\CommonFilesDir (x86)
%CommonProgramFiles(x86)% : X\CommonFilesDir (x86) X\CommonFilesDir (x86)
%CommonProgramW6432% : X\CommonW6432Dir X\CommonW6432Dir
%ProgramData% : Z\ProgramData Z\ProgramData
READING REGISTRY VALUES: Source for 64-bit process Source for 32-bit process
-------------------------------|----------------------------------------|--------------------------------------------------------------
X\ProgramFilesDir : X\ProgramFilesDir Y\ProgramFilesDir
X\ProgramFilesDir (x86) : X\ProgramFilesDir (x86) Y\ProgramFilesDir (x86)
X\ProgramFilesPath : X\ProgramFilesPath = %ProgramFiles% Y\ProgramFilesPath = %ProgramFiles(x86)%
X\ProgramW6432Dir : X\ProgramW6432Dir Y\ProgramW6432Dir
X\CommonFilesDir : X\CommonFilesDir Y\CommonFilesDir
X\CommonFilesDir (x86) : X\CommonFilesDir (x86) Y\CommonFilesDir (x86)
X\CommonW6432Dir : X\CommonW6432Dir Y\CommonW6432Dir
So for example, for a 32-bit process, the source of the data for the %ProgramFiles%
and %ProgramFiles(x86)%
environment variables is the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir (x86)
.
However, for a 64-bit process, the source of the data for the %ProgramFiles%
environment variable is the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramW6432Dir
...and the source of the data for the %ProgramFiles(x86)%
environment variable is the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir (x86)
Most default Windows installation put a string like C:\Program Files (x86)
into the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir (x86)
but this (and others) can be changed.
Whatever is entered into these Windows Registry values will be read by Windows Explorer into respective Environment Variables upon login and then copied to any child process that it subsequently spawns.
The registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesPath
is especially noteworthy because most Windows installations put the string %ProgramFiles%
into it, to be read by 64-bit processes. This string refers to the environment variable %ProgramFiles%
which in turn, takes its data from the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramW6432Dir
...unless some program changes the value of this environment variable apriori.
I have written a small utility, which displays these environment variables for 64-bit and 32-bit processes. You can download it here.
The source code for VisualStudio 2017 is included and the compiled 64-bit and 32-bit binary executables are in the directories ..\x64\Release
and ..\x86\Release
, respectively.
Short answer: It's just not worth it.
Longer answer: It's just not worth it, even if sequential element order and optimal performance aren't required.
Long answer: It's just not worth it...
for (var property in array)
will cause array
to be iterated over as an object, traversing the object prototype chain and ultimately performing slower than an index-based for
loop.for (... in ...)
is not guaranteed to return the object properties in sequential order, as one might expect.hasOwnProperty()
and !isNaN()
checks to filter the object properties is an additional overhead causing it to perform even slower and negates the key reason for using it in the first place, i.e. because of the more concise format.For these reasons an acceptable trade-off between performance and convenience doesn't even exist. There's really no benefit unless the intent is to handle the array as an object and perform operations on the object properties of the array.
when you manually open the IP address (via the RUN command or mapping a network drive), your PC will send your credentials over the pipe and the file server will receive authorization from the DC.
When ASP.Net tries, then it is going to try to use the IIS worker user (unless impersonation is turned on which will list a few other issues). Traditionally, the IIS worker user does not have authorization to work across servers (or even in other folders on the web server).
For Android Studio 3 I need to update two files to fix the error:--
1. app/build.gradle
buildscript {
repositories {
jcenter()
mavenCentral()
maven {
url 'https://maven.google.com/'
name 'Google'
}
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
}
}
2. app/gradle/wrapper/gradle-wrapper.properties
distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip
If it is a windows system, then it may be because you are using 32 bit winpcap library in a 64 bit pc or vie versa. If it is a 64 bit pc then copy the winpcap library and header packet.lib and wpcap.lib from winpcap/lib/x64 to the winpcap/lib directory and overwrite the existing
The LogManager
class determines which log4j config to use in a static block which runs when the class is loaded. There are three options intended for end-users:
log4j.defaultInitOverride
to false, it will not configure log4j at all.Specify the path to the configuration file manually yourself and override the classpath search. You can specify the location of the configuration file directly by using the following argument to java
:
-Dlog4j.configuration=<path to properties file>
in your test runner configuration.
Allow log4j to scan the classpath for a log4j config file during your test. (the default)
See also the online documentation.
An additional option is to apply absolute positioning via styling, setting the hidden component in out-of-screen coordinates:
<TextInput
onFocus={this.showCancel()}
onChangeText={(text) => this.doSearch({input: text})}
style={this.state.hide ? {position: 'absolute', top: -200} : {}}
/>
Unlike in some of the previous suggestions, this would hide your component from view BUT will also render it (keep it in the DOM), thus making it truly invisible.
Absolutely position divs over the text area with a z-index higher and give these divs a transparent GIF background graphic.
Note after a bit more thought - You'd need to have these 'covers' be linked so clicking on them would take you to where the tab was supposed to, which means you could/should do this with the anchor element set to display:box
, width and height set as well as the transparent background image.
Use the .Clear
method.
Sheets("Test").Range("A1:C3").Clear
If your RESTFul call sends XML Messages back and forth embedded in the Html Body of the HTTP request, you should be able to have all the benefits of WS-Security such as XML encryption, Cerificates, etc in your XML messages while using whatever security features are available from http such as SSL/TLS encryption.
Just to clarify, this is correct.
Cannot convert 'NodeList' to 'HTMLScriptElement[]'
as a NodeList
is not an actual array (e.g. it doesn't contain .forEach
, .slice
, .push
, etc...).
Thus if it did convert to HTMLScriptElement[]
in the type system, you'd get no type errors if you tried to call Array.prototype
members on it at compile time, but it would fail at run time.
Here is the simple and single line of code
For this use the SQL Inbuild RAND() function.
Here is the formula to generate random number between two number (RETURN INT Range)
Here a is your First Number (Min) and b is the Second Number (Max) in Range
SELECT FLOOR(RAND()*(b-a)+a)
Note: You can use CAST or CONVERT function as well to get INT range number.
( CAST(RAND()*(25-10)+10 AS INT) )
Example:
SELECT FLOOR(RAND()*(25-10)+10);
Here is the formula to generate random number between two number (RETURN DECIMAL Range)
SELECT RAND()*(b-a)+a;
Example:
SELECT RAND()*(25-10)+10;
More details check this: https://www.techonthenet.com/sql_server/functions/rand.php
Here you have one nice and simple recursion for deleting all files in source directory including that directory:
function delete_dir($src) {
$dir = opendir($src);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($src . '/' . $file) ) {
delete_dir($src . '/' . $file);
}
else {
unlink($src . '/' . $file);
}
}
}
closedir($dir);
rmdir($src);
}
Function is based on recursion made for copying directory. You can find that function here: Copy entire contents of a directory to another using php
“JSONP is JSON with extra code” would be too easy for the real world. No, you gotta have little discrepancies. What’s the fun in programming if everything just works?
Turns out JSON is not a subset of JavaScript. If all you do is take a JSON object and wrap it in a function call, one day you will be bitten by strange syntax errors, like I was today.
Well, I don't know how dynamic this is is, but sometimes this might save your debugging life:
var daString="<div id=\'block\' class=\'block\'><div class=\'block-2\'></div></div>";
var daParent=document.getElementById("the ID of whatever your parent is goes in here");
daParent.innerHTML=daString;
"Rat javascript" If I did it correctly. Works for me directly when the div and contents are not themselves dynamic of course, or you can even manipulate the string to change that too, though the string manipulating is complex than the "element.property=bla" approach, this gives some very welcome flexibility, and is a great debugging tool too :) Hope it helps.
Please try this command node --version or node -v, either of which should return something like v4.4.5
.
Let me propose this solution for you. So in your managed bean, do this
public String convertTime(long time){
Date date = new Date(time);
Format format = new SimpleDateFormat("yyyy MM dd HH:mm:ss");
return format.format(date);
}
so in your JSF page, you can do this (assuming foo
is the object that contain your time
)
<h:dataTable value="#{myBean.convertTime(myBean.foo.time)}" />
If you have multiple pages that want to utilize this method, you can put this in an abstract class
and have your managed bean extend this abstract class
.
EDIT: Return time with TimeZone
unfortunately, I think SimpleDateFormat
will always format the time in local time, so we can't use SimpleDateFormat
anymore. So to display time in different TimeZone, we can do this
public String convertTimeWithTimeZome(long time){
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
cal.setTimeInMillis(time);
return (cal.get(Calendar.YEAR) + " " + (cal.get(Calendar.MONTH) + 1) + " "
+ cal.get(Calendar.DAY_OF_MONTH) + " " + cal.get(Calendar.HOUR_OF_DAY) + ":"
+ cal.get(Calendar.MINUTE));
}
A better solution is to utilize JodaTime
. In my opinion, this API is much better than Calendar (lighter weight, faster and provide more functionality). Plus Calendar.Month
of January
is 0
, that force developer to add 1
to the result, and you have to format the time yourself. Using JodaTime
, you can fix all of that. Correct me if I am wrong, but I think JodaTime
is incorporated in JDK7
render: function(){
return(
<div>
<input type="text" id="one" onKeyDown={this.add} />
</div>
);
}
onKeyDown
detects keyCode
events.
If you want only the hour of your datetime, then you can use DATEPART()
- SQL Server:
declare @dt datetime
set @dt = '2012-09-10 08:25:53'
select datepart(hour, @dt) -- returns 8
In SQL Server 2008+ you can CAST()
as time:
declare @dt datetime
set @dt = '2012-09-10 08:25:53'
select CAST(@dt as time) -- returns 08:25:53
Use this one to add background---
background-image: url('images-path');
You can also add repeat or no-repeat function in it!
background: url('images-path') no-repeat 00;
You can use the below code. In the following code a database insertion occurs during the startup of the spring boot application.
@SpringBootApplication
public class Application implements CommandLineRunner {
@Autowired
private IService<Car> service;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String... args) throws Exception {
for(int i=1; i<=1000; i++) {
Car car = new Car();
car.setName("Car Name "+i);
book.setPrice(50 + i);
service.saveOrUpdate(car);
}
}
}
i had also encountered this issue. . This Solution worked for me....
windows->navigation->maximize active View or Editor(ctrl + M) . in the screen you can see on left side navigation menus ... now click on those buttons one by one ....you will get your solution...
Here's an old discussion thread where I listed the main differences and the conditions in which you should use each of these methods. I think you may find it useful to go through the discussion.
To explain the differences as relevant to your posted example:
a. When you use RegisterStartupScript
, it will render your script after all the elements in the page (right before the form's end tag). This enables the script to call or reference page elements without the possibility of it not finding them in the Page's DOM.
Here is the rendered source of the page when you invoke the RegisterStartupScript
method:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
<form name="form1" method="post" action="StartupScript.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
</div>
<div> <span id="lblDisplayDate">Label</span>
<br />
<input type="submit" name="btnPostback" value="Register Startup Script" id="btnPostback" />
<br />
<input type="submit" name="btnPostBack2" value="Register" id="btnPostBack2" />
</div>
<div>
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="someViewstategibberish" />
</div>
<!-- Note this part -->
<script language='javascript'>
var lbl = document.getElementById('lblDisplayDate');
lbl.style.color = 'red';
</script>
</form>
<!-- Note this part -->
</body>
</html>
b. When you use RegisterClientScriptBlock
, the script is rendered right after the Viewstate tag, but before any of the page elements. Since this is a direct script (not a function that can be called, it will immediately be executed by the browser. But the browser does not find the label in the Page's DOM at this stage and hence you should receive an "Object not found" error.
Here is the rendered source of the page when you invoke the RegisterClientScriptBlock
method:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
<form name="form1" method="post" action="StartupScript.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
</div>
<script language='javascript'>
var lbl = document.getElementById('lblDisplayDate');
// Error is thrown in the next line because lbl is null.
lbl.style.color = 'green';
Therefore, to summarize, you should call the latter method if you intend to render a function definition. You can then render the call to that function using the former method (or add a client side attribute).
Edit after comments:
For instance, the following function would work:
protected void btnPostBack2_Click(object sender, EventArgs e)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script language='javascript'>function ChangeColor() {");
sb.Append("var lbl = document.getElementById('lblDisplayDate');");
sb.Append("lbl.style.color='green';");
sb.Append("}</script>");
//Render the function definition.
if (!ClientScript.IsClientScriptBlockRegistered("JSScriptBlock"))
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "JSScriptBlock", sb.ToString());
}
//Render the function invocation.
string funcCall = "<script language='javascript'>ChangeColor();</script>";
if (!ClientScript.IsStartupScriptRegistered("JSScript"))
{
ClientScript.RegisterStartupScript(this.GetType(), "JSScript", funcCall);
}
}
int[,] arr = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for(int i = 0; i < arr.GetLength(0); i++){
for (int j = 0; j < arr.GetLength(1); j++)
Console.Write( "{0}\t",arr[i, j]);
Console.WriteLine();
}
output: 1 2 3
4 5 6
7 8 9
If you know there are three li's in the list you're looking at, for example, you could do this:
li + li + li { /* Selects third to last li */
}
In IE6 you can use expressions:
li {
color: expression(this.previousSibling ? 'red' : 'green'); /* 'green' if last child */
}
I would recommend using a specialized class or Javascript (not IE6 expressions), though, until the :last-child
selector gets better support.
>>> s1 ='arbit'
>>> s2 = 'hello world '.join( [s]*3 )
>>> print s2
arbit hello world arbit hello world arbit
Class method can modify the class state,it bound to the class and it contain cls as parameter.
Static method can not modify the class state,it bound to the class and it does't know class or instance
class empDetails:
def __init__(self,name,sal):
self.name=name
self.sal=sal
@classmethod
def increment(cls,name,none):
return cls('yarramsetti',6000 + 500)
@staticmethod
def salChecking(sal):
return sal > 6000
emp1=empDetails('durga prasad',6000)
emp2=empDetails.increment('yarramsetti',100)
# output is 'durga prasad'
print emp1.name
# output put is 6000
print emp1.sal
# output is 6500,because it change the sal variable
print emp2.sal
# output is 'yarramsetti' it change the state of name variable
print emp2.name
# output is True, because ,it change the state of sal variable
print empDetails.salChecking(6500)
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope) {
//This will hide the DIV by default.
$scope.IsVisible = false;
$scope.ShowHide = function () {
//If DIV is visible it will be hidden and vice versa.
$scope.IsVisible = $scope.IsVisible ? false : true;
}
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
<input type="button" value="Show Hide DIV" ng-click="ShowHide()" />
<br />
<br />
<div ng-show = "IsVisible">My DIV</div>
</div>
</body>
</html>
EXAMPLE : - http://jsfiddle.net/mafais/4WK7R/380/
Off the top of my head:
To me, the biggest difference is the model system. Obj-C lets you do messaging and introspection, but C++ has the ever-so-powerful templates.
Each have their strengths.
Here is another dirty hack :)
.application-title > img {
display: none;
}
.application-title::before {
content: url(path/example.jpg);
}
Here's what it looks like using docker-compose
when building a custom Dockerfile
.
docker build -t imagename:version .
This will store your new version locally.docker-compose down
docker-compose.yml
file to reflect the new image name you set at step 1.docker-compose up -d
. It will look locally for the image and use your upgraded one.-EDIT-
My steps above are more verbose than they need to be. I've optimized my workflow by including the build: .
parameter to my docker-compose file. The steps looks this now:
docker-compose build
docker-compose up -d
I didn't realize at the time, but docker-compose is smart enough to simply update my container to the new image with the one command, instead of having to bring it down first.
The guy who solved this posted it as LGPL and you're not allowed to modify it. I didn't even click on it when I saw that. Here's my version. This needs to be tested. There are probably bugs. Please post any updates. No warranty. You can modify this all you want, call it your own, print it out on a piece of paper and use it for kennel scrap, ... don't care.
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
namespace DigitalBoundaryGroup
{
class HttpNameValueCollection
{
public class File
{
private string _fileName;
public string FileName { get { return _fileName ?? (_fileName = ""); } set { _fileName = value; } }
private string _fileData;
public string FileData { get { return _fileData ?? (_fileName = ""); } set { _fileData = value; } }
private string _contentType;
public string ContentType { get { return _contentType ?? (_contentType = ""); } set { _contentType = value; } }
}
private NameValueCollection _post;
private Dictionary<string, File> _files;
private readonly HttpListenerContext _ctx;
public NameValueCollection Post { get { return _post ?? (_post = new NameValueCollection()); } set { _post = value; } }
public NameValueCollection Get { get { return _ctx.Request.QueryString; } }
public Dictionary<string, File> Files { get { return _files ?? (_files = new Dictionary<string, File>()); } set { _files = value; } }
private void PopulatePostMultiPart(string post_string)
{
var boundary_index = _ctx.Request.ContentType.IndexOf("boundary=") + 9;
var boundary = _ctx.Request.ContentType.Substring(boundary_index, _ctx.Request.ContentType.Length - boundary_index);
var upper_bound = post_string.Length - 4;
if (post_string.Substring(2, boundary.Length) != boundary)
throw (new InvalidDataException());
var current_string = new StringBuilder();
for (var x = 4 + boundary.Length; x < upper_bound; ++x)
{
if (post_string.Substring(x, boundary.Length) == boundary)
{
x += boundary.Length + 1;
var post_variable_string = current_string.Remove(current_string.Length - 4, 4).ToString();
var end_of_header = post_variable_string.IndexOf("\r\n\r\n");
if (end_of_header == -1) throw (new InvalidDataException());
var filename_index = post_variable_string.IndexOf("filename=\"", 0, end_of_header);
var filename_starts = filename_index + 10;
var content_type_starts = post_variable_string.IndexOf("Content-Type: ", 0, end_of_header) + 14;
var name_starts = post_variable_string.IndexOf("name=\"") + 6;
var data_starts = end_of_header + 4;
if (filename_index != -1)
{
var filename = post_variable_string.Substring(filename_starts, post_variable_string.IndexOf("\"", filename_starts) - filename_starts);
var content_type = post_variable_string.Substring(content_type_starts, post_variable_string.IndexOf("\r\n", content_type_starts) - content_type_starts);
var file_data = post_variable_string.Substring(data_starts, post_variable_string.Length - data_starts);
var name = post_variable_string.Substring(name_starts, post_variable_string.IndexOf("\"", name_starts) - name_starts);
Files.Add(name, new File() { FileName = filename, ContentType = content_type, FileData = file_data });
}
else
{
var name = post_variable_string.Substring(name_starts, post_variable_string.IndexOf("\"", name_starts) - name_starts);
var value = post_variable_string.Substring(data_starts, post_variable_string.Length - data_starts);
Post.Add(name, value);
}
current_string.Clear();
continue;
}
current_string.Append(post_string[x]);
}
}
private void PopulatePost()
{
if (_ctx.Request.HttpMethod != "POST" || _ctx.Request.ContentType == null) return;
var post_string = new StreamReader(_ctx.Request.InputStream, _ctx.Request.ContentEncoding).ReadToEnd();
if (_ctx.Request.ContentType.StartsWith("multipart/form-data"))
PopulatePostMultiPart(post_string);
else
Post = HttpUtility.ParseQueryString(post_string);
}
public HttpNameValueCollection(ref HttpListenerContext ctx)
{
_ctx = ctx;
PopulatePost();
}
}
}
There is definitly a problem with the destination folder path.
Your above error message says, it wants to put the contents to a file in the directory /files/grantapps/
, which would be beyond your vhost
, but somewhere in the system (see the leading absolute slash )
You should double check:
/home/username/public_html/files/grantapps/
really present./home/username/public_html/files/grantapps/
In case you are using RabbitMQ with Docker your steps should be:
The above method works good.
Another method (I am assuming web here) is to create your page. Add controls to the page. Then while in design mode go to: Tools > Generate Local Resource. A resource file will automatically appear in the solution with all the controls in the page mapped in the resource file.
To create resources for other languages, append the 4 character language to the end of the file name, before the extension (Account.aspx.en-US.resx, Account.aspx.es-ES.resx...etc).
To retrieve specific entries in the code-behind, simply call this method: GetLocalResourceObject([resource entry key/name])
.
A simple way to remove the back button in the AppBar is to set automaticallyImplyLeading
to false
.
appBar: AppBar(
title: Text("App Bar without Back Button"),
automaticallyImplyLeading: false,
),
Pass class to input tag and access the name value by using class.
<input class="test-class" name='xxxxx' value=1>
<script>
$('.test-class').attr('name');
</script>
Or you can also access the value using id.
<input id="test-id" name='xxxxx' value=1>
<script>
$('#test-id').attr('name');
</script>
In addition to the solution that other people provided (which are good, and correct), there is a way to specify the ViewModel in XAML, yet still separate the specific ViewModel from the View. Separating them is useful for when you want to write isolated test cases.
In App.xaml:
<Application
x:Class="BuildAssistantUI.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:BuildAssistantUI.ViewModels"
StartupUri="MainWindow.xaml"
>
<Application.Resources>
<local:MainViewModel x:Key="MainViewModel" />
</Application.Resources>
</Application>
In MainWindow.xaml:
<Window x:Class="BuildAssistantUI.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{StaticResource MainViewModel}"
/>
If the PATH value would be too long after your user's PATH variable has been concatenated onto the environment PATH variable, Windows will silently fail to concatenate the user PATH variable.
This can easily happen after new software is installed and adds something to PATH, thereby breaking existing installed software. Windows fail!
The best fix is to edit one of the PATH variables in the Control Panel and remove entries you don't need. Then open a new CMD window and see if all entries are shown in "echo %PATH%".
in support to @jean.timex solution, use below code if you want to open one section at any time. create a variable like: var expandedSection = -1;
func toggleSection(_ header: CollapsibleTableViewHeader, section: Int) {
let collapsed = !sections[section].collapsed
// Toggle collapse
sections[section].collapsed = collapsed
header.setCollapsed(collapsed)
tableView.reloadSections(NSIndexSet(index: section) as IndexSet, with: .automatic)
if (expandedSection >= 0 && expandedSection != section){
sections[expandedSection].collapsed = true
tableView.reloadSections(NSIndexSet(index: expandedSection) as IndexSet, with: .automatic)
}
expandedSection = section;
}
With IntelliJ, you can do this from the test configuration. Once you open this window, you can choose to run the test any number of times you want,.
when you run the test, intellij will execute all tests you have selected for the number of times you specified.
I had this error message:
Error: Can't open display: localhost:13.0
This fixed it for me:
export DISPLAY="localhost:10.0"
You can use this too:
export DISPLAY="127.0.0.1:10.0"
This should work:
window.location.href = window.location.href.split( '#' )[0];
or
var x = window.location.href;
x = x.split( '#' );
window.location.href = x[0];
I prefer this for the following reasons:
Alternatively, you may use the most recent official method for this task
window.location.reload()
The simplest and also the most compact solution (for v2.3.3):
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.writeValueAsString(obj)
Created the Data frame:
import pandas as pd
dk=pd.DataFrame({"BrandName":['A','B','ABC','D','AB'],"Specialty":['H','I','J','K','L']})
Now use DataFrame.replace()
function:
dk.BrandName.replace(to_replace=['ABC','AB'],value='A')
Front :
<Image Name="camImage"/>
Back:
public async void Base64ToImage(string base64String)
{
// read stream
var bytes = Convert.FromBase64String(base64String);
var image = bytes.AsBuffer().AsStream().AsRandomAccessStream();
// decode image
var decoder = await BitmapDecoder.CreateAsync(image);
image.Seek(0);
// create bitmap
var output = new WriteableBitmap((int)decoder.PixelHeight, (int)decoder.PixelWidth);
await output.SetSourceAsync(image);
camImage.Source = output;
}
The error is because you are including the script links at two places which will do the override and re-initialization of date-picker
<meta charset="utf-8">_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />_x000D_
_x000D_
_x000D_
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>_x000D_
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>_x000D_
_x000D_
<script type="text/javascript">_x000D_
$(document).ready(function() {_x000D_
$('.dateinput').datepicker({ format: "yyyy/mm/dd" });_x000D_
}); _x000D_
</script>_x000D_
_x000D_
<!-- Bootstrap core JavaScript_x000D_
================================================== -->_x000D_
<!-- Placed at the end of the document so the pages load faster -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
_x000D_
So exclude either src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"
or src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"
It will work..
I think this can be generalized like this:
Denote S, M as the initial values for the sum of arithmetic series and multiplication.
S = 1 + 2 + 3 + 4 + ... n=(n+1)*n/2
M = 1 * 2 * 3 * 4 * .... * n
I should think about a formula to calculate this, but that is not the point. Anyway, if one number is missing, you already provided the solution. However, if two numbers are missing then, let's denote the new sum and total multiple by S1 and M1, which will be as follows:
S1 = S - (a + b)....................(1)
Where a and b are the missing numbers.
M1 = M - (a * b)....................(2)
Since you know S1, M1, M and S, the above equation is solvable to find a and b, the missing numbers.
Now for the three numbers missing:
S2 = S - ( a + b + c)....................(1)
Where a and b are the missing numbers.
M2 = M - (a * b * c)....................(2)
Now your unknown is 3 while you just have two equations you can solve from.
//create authentication base 64 encoding string
let PasswordString = "\(txtUserName.text):\(txtPassword.text)"
let PasswordData = PasswordString.dataUsingEncoding(NSUTF8StringEncoding)
let base64EncodedCredential = PasswordData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
//let base64EncodedCredential = PasswordData!.base64EncodedStringWithOptions(nil)
//create authentication url
let urlPath: String = "http://...../auth"
var url: NSURL = NSURL(string: urlPath)
//create and initialize basic authentication request
var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.setValue("Basic \(base64EncodedCredential)", forHTTPHeaderField: "Authorization")
request.HTTPMethod = "GET"
//You can use one of below methods
//1 URL request with NSURLConnectionDataDelegate
let queue:NSOperationQueue = NSOperationQueue()
let urlConnection = NSURLConnection(request: request, delegate: self)
urlConnection.start()
//2 URL Request with AsynchronousRequest
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
}
//2 URL Request with AsynchronousRequest with json output
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var err: NSError
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
println("\(jsonResult)")
})
//3 URL Request with SynchronousRequest
var response: AutoreleasingUnsafePointer<NSURLResponse?>=nil
var dataVal: NSData = NSURLConnection.sendSynchronousRequest(request, returningResponse: response, error:nil)
var err: NSError
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
println("\(jsonResult)")
//4 URL Request with NSURLSession
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let authString = "Basic \(base64EncodedCredential)"
config.HTTPAdditionalHeaders = ["Authorization" : authString]
let session = NSURLSession(configuration: config)
session.dataTaskWithURL(url) {
(let data, let response, let error) in
if let httpResponse = response as? NSHTTPURLResponse {
let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
println(dataString)
}
}.resume()
// you may be get fatal error if you changed the request.HTTPMethod = "POST" when server request GET request
In MVC4 & MVC5 It is little bit different, use following
/App_Start/RouteConfig.cs
namespace MyNamespace
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] {"MyNamespace.Controllers"}
);
}
}
}
and in Areas
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional },
new[] { "MyNamespace.Areas.Admin.Controllers" }
);
The --trace-ascii
option to curl will show the request headers, as well as the response headers and response body.
For example, the command
curl --trace-ascii curl.trace http://www.google.com/
produces a file curl.trace
that starts as follows:
== Info: About to connect() to www.google.com port 80 (#0)
== Info: Trying 209.85.229.104... == Info: connected
== Info: Connected to www.google.com (209.85.229.104) port 80 (#0)
=> Send header, 145 bytes (0x91)
0000: GET / HTTP/1.1
0010: User-Agent: curl/7.16.3 (powerpc-apple-darwin9.0) libcurl/7.16.3
0050: OpenSSL/0.9.7l zlib/1.2.3
006c: Host: www.google.com
0082: Accept: */*
008f:
It also got a response (a 302 response, to be precise but irrelevant) which was logged.
If you only want to save the response headers, use the --dump-header
option:
curl -D file url
curl --dump-header file url
If you need more information about the options available, use curl --help | less
(it produces a couple hundred lines of output but mentions a lot of options). Or find the manual page where there is more explanation of what the options mean.
public IEnumerable<Friend> FindFriends()
{
return userExists ? doc.Descendants("user").Select(user => new Friend
{
ID = user.Element("id").Value,
Name = user.Element("name").Value,
URL = user.Element("url").Value,
Photo = user.Element("photo").Value
}): new List<Friend>();
}
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private Context context;
private List<cardview_widgets> list;
public MyAdapter(Context context, List<cardview_widgets> list) {
this.context = context;
this.list = list;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(this.context).inflate(R.layout.fragment1_one_item,
viewGroup, false);
return new MyViewHolder(view);
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView txtValue;
TextView txtCategory;
ImageView imgInorEx;
ImageView imgCategory;
TextView txtDate;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
txtValue= itemView.findViewById(R.id.id_values);
txtCategory= itemView.findViewById(R.id.id_category);
imgInorEx= itemView.findViewById(R.id.id_inorex);
imgCategory= itemView.findViewById(R.id.id_imgcategory);
txtDate= itemView.findViewById(R.id.id_date);
}
}
@NonNull
@Override
public void onBindViewHolder(@NonNull final MyViewHolder myViewHolder, int i) {
myViewHolder.txtValue.setText(String.valueOf(list.get(i).getValuee()));
myViewHolder.txtCategory.setText(list.get(i).getCategory());
myViewHolder.imgInorEx.setBackgroundColor(list.get(i).getImg_inorex());
myViewHolder.imgCategory.setImageResource(list.get(i).getImg_category());
myViewHolder.txtDate.setText(list.get(i).getDate());
myViewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
list.remove(myViewHolder.getAdapterPosition());
notifyDataSetChanged();
return false;
}
});
}
@Override
public int getItemCount() {
return list.size();
}}
i hope this help you.
#on ubuntu, in /usr/share/jenkins:
sudo service jenkins stop
sudo mv jenkins.war jenkins.war.old
sudo wget https://updates.jenkins-ci.org/latest/jenkins.war
sudo service jenkins start
Shortest Yet!
<button onclick="history.go(-1);">Go back</button>
I prefer the .go(-number)
method as then, for 1 or many 'backs' there's only 1 method to use/remember/update/search for, etc.
Also, using a tag for a back button seems more appropriate than tags with names and types...
References are "hidden pointers" (non-null) to things which can change (lvalues). You cannot define them to a constant. It should be a "variable" thing.
EDIT::
I am thinking of
int &x = y;
as almost equivalent of
int* __px = &y;
#define x (*__px)
where __px
is a fresh name, and the #define x
works only inside the block containing the declaration of x
reference.
As Chris suggests, you can do it like this:
public string GetXMLAsString(XmlDocument myxml)
{
return myxml.OuterXml;
}
Or like this:
public string GetXMLAsString(XmlDocument myxml)
{
StringWriter sw = new StringWriter();
XmlTextWriter tx = new XmlTextWriter(sw);
myxml.WriteTo(tx);
string str = sw.ToString();//
return str;
}
and if you really want to create a new XmlDocument
then do this
XmlDocument newxmlDoc= myxml
If your page really relies on the fact that people won't be able to see that menu, you should know that modern browsers (for example Firefox) let the user decide if he really wants to disable it or not. So you have no guarantee at all that the menu would be really disabled.
Reason seems to be that the public key of the remote host is not stored or different from the stored one. (Be aware of security issues, see Greg Bacon's answer for details.)
I was used to git clone
prompting me in this case:
The authenticity of host 'host.net (10.0.0.42)' can't be established.
ECDSA key fingerprint is 00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00.
Are you sure you want to continue connecting (yes/no)?
Not sure, why this error is thrown instead. Could be the configuration of your shell or the git SSH command.
Anyhow, you can get the same prompt by running ssh [email protected]
.
You can view any existing index by using the below CURL. Please replace the index-name with your actual name before running and it will run as is.
View the index content
curl -H 'Content-Type: application/json' -X GET https://localhost:9200/index_name?pretty
And the output will include an index(see settings in output) and its mappings too and it will look like below output -
{
"index_name": {
"aliases": {},
"mappings": {
"collection_name": {
"properties": {
"test_field": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
},
"settings": {
"index": {
"creation_date": "1527377274366",
"number_of_shards": "5",
"number_of_replicas": "1",
"uuid": "6QfKqbbVQ0Gbsqkq7WZJ2g",
"version": {
"created": "6020299"
},
"provided_name": "index_name"
}
}
}
}
View ALL the data under this index
curl -H 'Content-Type: application/json' -X GET https://localhost:9200/index_name/_search?pretty
@Alistair pointed out in this answer that sometimes users will return to the browser after opening the app. A commenter to that answer indicated that the times values used had to be changed depending on iOS version. When our team had to deal with this, we found that the time values for the initial timeout and telling whether we had returned to the browser had to be tuned, and often didn't work for all users and devices.
Rather than using an arbitrary time difference threshold to determine whether we had returned to the browser, it made sense to detect the "pagehide" and "pageshow" events.
I developed the following web page to help diagnose what was going on. It adds HTML diagnostics as the events unfold, mainly because using techniques like console logging, alerts, or Web Inspector, jsfiddle.net etc all had their drawbacks in this work flow. Rather than using a time threshold, the Javascript counts the number of "pagehide" and "pageshow" events to see whether they have occurred. And I found that the most robust strategy was to use an initial timeout of 1000 (rather than the 25, 50, or 100 reported/suggested by others).
This can be served on a local server, e.g. python -m SimpleHTTPServer
and viewed on iOS Safari.
To play with it, press either the "Open an installed app" or "App not installed" links. These links should cause respectively the Maps app or the App Store to open. You can then return to Safari to see the sequence and timing of the events.
(Note: this will work for Safari only. For other browsers (like Chrome) you'd have to install handlers for the pagehide/show-equivalent events).
Update: As @Mikko has pointed out in the comments, the pageshow/pagehide events we are using are apparently no longer supported in iOS8.
<html>
<head>
</head>
<body>
<a href="maps://" onclick="clickHandler()">Open an installed app</a>
<br/><br/>
<a href="xmapsx://" onclick="clickHandler()">App not installed</a>
<br/>
<script>
var hideShowCount = 0 ;
window.addEventListener("pagehide", function() {
hideShowCount++ ;
showEventTime('pagehide') ;
});
window.addEventListener("pageshow", function() {
hideShowCount++ ;
showEventTime('pageshow') ;
});
function clickHandler(){
var hideShowCountAtClick = hideShowCount ;
showEventTime('click') ;
setTimeout(function () {
showEventTime('timeout function '+(hideShowCount-hideShowCountAtClick)+' hide/show events') ;
if (hideShowCount == hideShowCountAtClick){
// app is not installed, go to App Store
window.location = 'http://itunes.apple.com/app' ;
}
}, 1000);
}
function currentTime()
{
return Date.now()/1000 ;
}
function showEventTime(event){
var time = currentTime() ;
document.body.appendChild(document.createElement('br'));
document.body.appendChild(document.createTextNode(time+' '+event));
}
</script>
</body>
</html>
Use q
flag for quiet mode, and tell wget
to output to stdout with O-
(uppercase o) and redirect to /dev/null
to discard the output:
wget -qO- $url &> /dev/null
>
redirects application output (to a file). if >
is preceded by ampersand, shell redirects all outputs (error and normal) to the file right of >
. If you don't specify ampersand, then only normal output is redirected.
./app &> file # redirect error and standard output to file
./app > file # redirect standard output to file
./app 2> file # redirect error output to file
if file is /dev/null
then all is discarded.
This works as well, and simpler:
wget -O/dev/null -q $url
To understand JavaBean you need to notice the following:
JavaBean is conceptual stuff and can not represent a class of specific things
JavaBean is a development tool can be visualized in the operation of reusable software components
JavaBean is based on the Sun JavaBeans specification and can be reusable components. Its biggest feature is the re-usability.
If your apache tomcat asking for password,then just follow these steps: go to the home directory of apache then go to webapps folder open the META-INF inside that you will find an xml file named context.xml--open it in edit mode
and REMOVE THE COMMENT FROM the VALVE tag.
After that you dont need any user name and password.
I hope this example helps. You ca use the curly braces to make sure you've got everything enclosed in the switcher changer guy (sorry don't know the technical term but the term that precedes the = sign that changes what happens). I think of switch as a more controlled bunch of if () {} else {}
statements.
Each time the switch function is the same but the command we supply changes.
do.this <- "T1"
switch(do.this,
T1={X <- t(mtcars)
colSums(mtcars)%*%X
},
T2={X <- colMeans(mtcars)
outer(X, X)
},
stop("Enter something that switches me!")
)
#########################################################
do.this <- "T2"
switch(do.this,
T1={X <- t(mtcars)
colSums(mtcars)%*%X
},
T2={X <- colMeans(mtcars)
outer(X, X)
},
stop("Enter something that switches me!")
)
########################################################
do.this <- "T3"
switch(do.this,
T1={X <- t(mtcars)
colSums(mtcars)%*%X
},
T2={X <- colMeans(mtcars)
outer(X, X)
},
stop("Enter something that switches me!")
)
Here it is inside a function:
FUN <- function(df, do.this){
switch(do.this,
T1={X <- t(df)
P <- colSums(df)%*%X
},
T2={X <- colMeans(df)
P <- outer(X, X)
},
stop("Enter something that switches me!")
)
return(P)
}
FUN(mtcars, "T1")
FUN(mtcars, "T2")
FUN(mtcars, "T3")
ng g c componentname
By using above command New Component will be created in a folder with
(componentname) you specified above.
In case anyone else is running in to the same problem, the only solution I could find that satisfied me was to have the canvas cover everything and then to raise the Z-index of all clickable elements. You can't draw on them, but at least they are clickable...
you could put the style in container div menu with:
<div style="position:relative; z-index:10">
...
<!--html menu-->
...
</div>
before
after
First, I use:
mysql -u root -p
Giving my current password for the 'root'. Next:
mysql> ALTER USER `root`@`localhost` IDENTIFIED BY 'new_password',
`root`@`localhost` PASSWORD EXPIRE NEVER;
Change 'new_password'
to a new password for the user 'root'.
It solved my problem.
I tried what ChrLipp suggested, but that wasn't the problem, as the image was already installed. What I did was run:
android avd
to start the emulator manually. Then I stopped the emulator, and form that point on the
cca emulate android
app started working, without the "missing a kernel file" error.
The terms "stress testing" and "load testing" are often used interchangeably by software test engineers but they are really quite different.
Stress testing
In Stress testing we tries to break the system under test by overwhelming its resources or by taking resources away from it (in which case it is sometimes called negative testing). The main purpose behind this madness is to make sure that the system fails and recovers gracefully -- this quality is known as recoverability. OR Stress testing is the process of subjecting your program/system under test (SUT) to reduced resources and then examining the SUT’s behavior by running standard functional tests. The idea of this is to expose problems that do not appear under normal conditions.For example, a multi-threaded program may work fine under normal conditions but under conditions of reduced CPU availability, timing issues will be different and the SUT will crash. The most common types of system resources reduced in stress testing are CPU, internal memory, and external disk space. When performing stress testing, it is common to call the tools which reduce these three resources EatCPU, EatMem, and EatDisk respectively.
While on the other hand Load Testing
In case of Load testing Load testing is the process of subjecting your SUT to heavy loads, typically by simulating multiple users( Using Load runner), where "users" can mean human users or virtual/programmatic users. The most common example of load testing involves subjecting a Web-based or network-based application to simultaneous hits by thousands of users. This is generally accomplished by a program which simulates the users. There are two main purposes of load testing: to determine performance characteristics of the SUT, and to determine if the SUT "breaks" gracefully or not.
In the case of a Web site, you would use load testing to determine how many users your system can handle and still have adequate performance, and to determine what happens with an extreme load — will the Web site generate a "too busy" message for users, or will the Web server crash in flames?
Just in case any one else is using creating test users with their automation....
We had this same error and it was because we had recreated the user (as part of the test process). This caused the underlying SID to change which meant that SQL couldn't properly authenticate the user.
We fixed it by adding a drop login command to our testing scripts to ensure that a previously created user (with the same user name) was no longer present on the instance.
@last_run_time
is a 9.4. User-Defined Variables and last_run_time datetime
one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.
Try: SELECT last_run_time;
UPDATE
Example:
/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$
CREATE PROCEDURE `sp_test`()
BEGIN
DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
DECLARE last_run_time DATETIME DEFAULT NULL;
DECLARE current_run_time DATETIME DEFAULT NOW();
-- Define the last run time
SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);
-- if there is no last run time found then use yesterday as starting point
IF(last_run_time IS NULL) THEN
SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
END IF;
SELECT last_run_time;
-- Insert variables in table2
INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$
DELIMITER ;
The other solutions posted here didn't work for me, because:
import *
didn't work for me, as i need a way to override them by choosing another fileSo I ended up using Configparser
and globals().update()
Test file:
#File parametertest.cfg:
[Settings]
#Comments are no Problem
test= True
bla= False #Here neither
#that neither
And that's my demo script:
import ConfigParser
cfg = ConfigParser.RawConfigParser()
cfg.read('parametertest.cfg') # Read file
#print cfg.getboolean('Settings','bla') # Manual Way to acess them
par=dict(cfg.items("Settings"))
for p in par:
par[p]=par[p].split("#",1)[0].strip() # To get rid of inline comments
globals().update(par) #Make them availible globally
print bla
It's just for a file with one section now, but that will be easy to adopt.
Hope it will be helpful for someone :)
We nee to change the values of 'SMTP' in php.ini file php.ini file is located into
EasyPHP-DevServer-14.1VC11\binaries\php\php_runningversion\php.ini
I was experiencing this problem on Samsung devices (fine on others). like zyamys suggested in his/her comment, I added the manifest.permission line but in addition to rather than instead of the original line, so:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.Manifest.permission.READ_PHONE_STATE" />
I'm targeting API 22, so don't need to explicitly ask for permissions.
The best way is use the default method clearFocus()
You know how to solve codes in onTouchListener
right?
Just call EditText.clearFocus()
. It will clear focus in last EditText
.
One point that is missed in a lot of these discussions is how you revert back on the SAME machine on which you shelved your changes. Perhaps obvious to most, but wasn't to me. I believe you perform an Undo Pending Changes - is that right?
I understand the process to be as follows:
So, if you want to start some work which you may need to Shelve, make sure you check-in before you start, as the check-in point is where you'll return to when doing the Undo Pending Changes step above.
One problem with leaving out statement blocks is the else-ambiguity. That is C-inspired languages ignore indentation and so have no way of separating this:
if(one)
if(two)
foo();
else
bar();
From this:
if(one)
if(two)
foo();
else
bar();
you can store the Path into string variable like
string s = choofdlog.FileName;
Try one of this solutions:
1. The browser fails to load the compressed script
This is usually the case if you get the error on IE6, but not on other browsers.
The Script Resource Handler – ScriptResource.axd compresses the scripts before returning them to the browser. In pre-RTM releases, the handler did it all the time for all browsers, and it wasn’t configurable. There is an issue in one of the components of IE6 that prevents it from loading compressed scripts correctly. See KB article here. In RTM builds, we’ve made two fixes for this. One, we don’t compress if IE6 is the browser client. Two, we’ve now made compression configurable. Here’s how you can toggle the web.config.
How do you fix it? First, make sure you are using the AJAX Extensions 1.0 RTM release. That alone should be enough. You can also try turning off compression by editing your web.config to have the following:
<system.web.extensions>
<scripting>
<scriptResourceHandler enableCompression="false" enableCaching="true" />
</scripting>
</system.web.extensions>
2. The required configuration for ScriptResourceHandler doesn’t exist for the web.config for your application
Make sure your web.config contains the entries from the default web.config file provided with the extensions install. (default location: C:\Program Files\Microsoft ASP.NET\ASP.NET 2.0 AJAX Extensions\v1.0.61025)
3. The virtual directory you are using for your web, isn’t correctly marked as an application (thus the configuration isn’t getting loaded) - This would happen for IIS webs.
Make sure that you are using a Web Application, and not just a Virtual Directory
4. ScriptResource.axd requests return 404
This usually points to a mis-configuration of ASP.NET as a whole. On a default installation of ASP.NET, any web request to a resource ending in .axd is passed from IIS to ASP.NET via an isapi mapping. Additionally the mapping is configured to not check if the file exists. If that mapping does not exist, or the check if file exists isn't disabled, then IIS will attempt to find the physical file ScriptResource.axd, won't find it, and return 404.
You can check to see if this is the problem by coipy/pasting the full url to ScriptResource.axd from here, and seeing what it returns
<script src="/MyWebApp/ScriptResource.axd?[snip - long query string]" type="text/javascript"></script>
How do you fix this? If ASP.NET isn't properly installed at all, you can run the "aspnet_regiis.exe" command line tool to fix it up. It's located in C:\WINDOWS\Microsoft.Net\Framework\v2.0.50727. You can run "aspnet_regiis -i -enable", which does the full registration of ASP.NET with IIS and makes sure the ISAPI is enabled in IIS6. You can also run "aspnet_regiis -s w3svc/1/root/MyWebApp" to only fix up the registration for your web application.
5. Resolving the "Sys is undefined" error in ASP.NET AJAX RTM under IIS 7
Put this entry under <system.webServer/><handlers/>
:
<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
and remove the one under <system.web/><httpHandlers/>
.
References: http://weblogs.asp.net/chrisri/demystifying-sys-is-undefined http://geekswithblogs.net/lorint/archive/2007/03/28/110161.aspx
These are the packages that your package needs to run, so they will be installed when people run
npm install PACKAGE-NAME
An example would be if you used jQuery in your project. If someone doesn't have jQuery installed, then it wouldn't work. To save as a dependency, use
npm install --save
These are the dependencies that you use in development, but isn't needed when people are using it, so when people run npm install
, it won't install them since the are not necessary. For example, if you use mocha
to test, people don't need mocha
to run, so npm install
doesn't install it. To save as a dev dependency, use
npm install PACKAGE --save-dev
These can be used if you want to create and publish your own library so that it can be used as a dependency. For example, if you want your package to be used as a dependency in another project, then these will also be installed when someone installs the project which has your project as a dependency. Most of the time you won't use peer dependencies.
For me, the problem was only on certain (long) links within the website and was tracked down to URLScan having the default configuration of a URL length limit of 260.
Here you go (hope this give you the idea):
/*************************************************************************
* Compilation: javac Capitalize.java
* Execution: java Capitalize < input.txt
*
* Read in a sequence of words from standard input and capitalize each
* one (make first letter uppercase; make rest lowercase).
*
* % java Capitalize
* now is the time for all good
* Now Is The Time For All Good
* to be or not to be that is the question
* To Be Or Not To Be That Is The Question
*
* Remark: replace sequence of whitespace with a single space.
*
*************************************************************************/
public class Capitalize {
public static String capitalize(String s) {
if (s.length() == 0) return s;
return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
}
public static void main(String[] args) {
while (!StdIn.isEmpty()) {
String line = StdIn.readLine();
String[] words = line.split("\\s");
for (String s : words) {
StdOut.print(capitalize(s) + " ");
}
StdOut.println();
}
}
}
Kind of an old question, but I thought I should throw in a method which wasn't widely available when this question was asked.
You can reverse the side of the scrollbar in modern browsers using transform: scaleX(-1)
on a parent <div>
, then apply the same transform to reverse a child, "sleeve" element.
HTML
<div class="parent">
<div class="sleeve">
<!-- content -->
</div>
</div>
CSS
.parent {
overflow: auto;
transform: scaleX(-1); //Reflects the parent horizontally
}
.sleeve {
transform: scaleX(-1); //Flips the child back to normal
}
Note: You may need to use an -ms-transform
or -webkit-transform
prefix for browsers as old as IE 9. Check CanIUse and click "show all" to see older browser requirements.
As of 2014, here is a statement from a Microsoft representative (the Scripting Guy):
As much as we might hate to admit it, there are still no Windows PowerShell cmdlets from Microsoft that permit creating local user accounts or local user groups. We finally have a Desired State Configuration (DSC ) provider that can do this—but to date, no cmdlets.
WebElement p= driver.findElement(By.id("your id name"));
p.sendKeys(Keys.chord(Keys.CONTROL, "a"), "55");
To remove elements from an array, use the remove(at:)
,
removeLast()
and removeAll()
.
yourArray = [1,2,3,4]
Remove the value at 2 position
yourArray.remove(at: 2)
Remove the last value from array
yourArray.removeLast()
Removes all members from the set
yourArray.removeAll()
var result = from sc in enumerableOfSomeClass
join soc in enumerableOfSomeOtherClass
on sc.Property1 equals soc.Property2
select new { SomeClass = sc, SomeOtherClass = soc };
Would be equivalent to:
var result = enumerableOfSomeClass
.Join(enumerableOfSomeOtherClass,
sc => sc.Property1,
soc => soc.Property2,
(sc, soc) => new
{
SomeClass = sc,
SomeOtherClass = soc
});
As you can see, when it comes to joins, query syntax is usually much more readable than lambda syntax.
Edit: Saw the responses posted while I was writing, Hash[a.flatten] seems the way to go. Must have missed that bit in the documentation when I was thinking through the response. Thought the solutions that I've written can be used as alternatives if required.
The second form is simpler:
a = [[:apple, 1], [:banana, 2]]
h = a.inject({}) { |r, i| r[i.first] = i.last; r }
a = array, h = hash, r = return-value hash (the one we accumulate in), i = item in the array
The neatest way that I can think of doing the first form is something like this:
a = [:apple, 1, :banana, 2]
h = {}
a.each_slice(2) { |i| h[i.first] = i.last }
To multiply, use mult
for signed multiplication and multu
for unsigned multiplication. Note that the result of the multiplication of two 32-bit numbers yields a 64-number. If you want the result back in $v0
that means that you assume the result will fit in 32 bits.
The 32 most significant bits will be held in the HI
special register (accessible by mfhi
instruction) and the 32 least significant bits will be held in the LO
special register (accessible by the mflo
instruction):
E.g.:
li $a0, 5
li $a1, 3
mult $a0, $a1
mfhi $a2 # 32 most significant bits of multiplication to $a2
mflo $v0 # 32 least significant bits of multiplication to $v0
To divide, use div
for signed division and divu
for unsigned division. In this case, the HI
special register will hold the remainder and the LO
special register will hold the quotient of the division.
E.g.:
div $a0, $a1
mfhi $a2 # remainder to $a2
mflo $v0 # quotient to $v0
The JDK_HOME variable should always point to the base dir of the jdk, not the bin dir:
D:\name\name\core java\software\Java\Java_1.6.0_04_win\jdk1.6.0_04
That defined, fix your path to be
C:\Windows\System32;D:\name\name1\Softwares\Maven\apache-maven-3.0.4\bin;C:\Program Files\Notepad++\;%JDK_HOME%\bin
We are missing the setMaster("local[*]") to set. Once we added then problem get resolved.
Problem:
val spark = SparkSession
.builder()
.appName("Spark Hive Example")
.config("spark.sql.warehouse.dir", warehouseLocation)
.enableHiveSupport()
.getOrCreate()
solution:
val spark = SparkSession
.builder()
.appName("Spark Hive Example")
.config("spark.sql.warehouse.dir", warehouseLocation)
.enableHiveSupport()
.master("local[*]")
.getOrCreate()
See the following snippet, is this what you want?
body {
background: silver;
padding: 0 10px;
}
#content:after {
height: 10px;
display: block;
width: 100px;
background: #808080;
border-right: 1px white;
content: '';
}
#footer:before {
display: block;
content: '';
background: silver;
height: 10px;
margin-top: -20px;
margin-left: 101px;
}
#content {
background: white;
}
#footer {
padding-top: 10px;
background: #404040;
}
p {
padding: 100px;
text-align: center;
}
#footer p {
color: white;
}
_x000D_
<body>
<div id="content"><p>#content</p></div>
<div id="footer"><p>#footer</p></div>
</body>
_x000D_
Yes, this is confusing...
According to this blog post, it looks like this is an omission from WPF.
To make it work you need to use a style:
<Border Name="ClearButtonBorder" Grid.Column="1" CornerRadius="0,3,3,0">
<Border.Style>
<Style>
<Setter Property="Border.Background" Value="Blue"/>
<Style.Triggers>
<Trigger Property="Border.IsMouseOver" Value="True">
<Setter Property="Border.Background" Value="Green" />
</Trigger>
</Style.Triggers>
</Style>
</Border.Style>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="X" />
</Border>
I guess this problem isn't that common as most people tend to factor out this sort of thing into a style, so it can be used on multiple controls.
Putting a whole array into one localStorage entry is very inefficient: the whole thing needs to be re-encoded every time you add something to the array or change one entry.
An alternative is to use http://rhaboo.org which stores any JS object, however deeply nested, using a separate localStorage entry for each terminal value. Arrays are restored much more faithfully, including non-numeric properties and various types of sparseness, object prototypes/constructors are restored in standard cases and the API is ludicrously simple:
var store = Rhaboo.persistent('Some name');
store.write('count', store.count ? store.count+1 : 1);
store.write('somethingfancy', {
one: ['man', 'went'],
2: 'mow',
went: [ 2, { mow: ['a', 'meadow' ] }, {} ]
});
store.somethingfancy.went[1].mow.write(1, 'lawn');
BTW, I wrote it.
SELECT CONCAT (zipcode, ' - ', city, ', ', state) AS COMBINED FROM TABLE
Find id for row N Then get the top M rows that have an id greater than or equal to that
declare @N as int set @N = 2 declare @M as int set @M = 3 declare @Nid as int set @Nid = max(id) from (select top @N * from MyTable order by id) select top @M * from MyTable where id >= @Nid order by id
Something like that ... but I've made some assumptions here (e.g. you want to order by id)
Don't declare function inside a loop (like foreach
, for
, while
...) ! Declare before them.
You should include that file (wherein that function exists) only once. So,
instead of : include ("functions.php");
use: include_once("functions.php");
If none of above helps, before function declaration, add a check to avoid re-declaration:
if (!function_exists('your_function_name')) {
function your_function_name() {
........
}
}
Basically it's OK to store your JWT in your localStorage.
And I think this is a good way. If we are talking about XSS, XSS using CDN, it's also a potential risk of getting your client's login/pass as well. Storing data in local storage will prevent CSRF attacks at least.
You need to be aware of both and choose what you want. Both attacks it's not all you are need to be aware of, just remember: YOUR ENTIRE APP IS ONLY AS SECURE AS THE LEAST SECURE POINT OF YOUR APP.
Once again storing is OK, be vulnerable to XSS, CSRF,... isn't
I'm using AS 3.2.1, and was about to try some of the plugins, but was hesitant realizing the plugins are able to monitor any data..
It's actually really simple doing it via the Terminal tab in AS:
adb tcpip 5555
adb connect 192.168.1.101
The recommended way in Python 3.5 and above is to use subprocess.run()
:
from subprocess import run
output = run("pwd", capture_output=True).stdout
x += 5
is not exactly the same as saying x = x + 5
in Python.
Note here:
In [1]: x = [2, 3, 4]
In [2]: y = x
In [3]: x += 7, 8, 9
In [4]: x
Out[4]: [2, 3, 4, 7, 8, 9]
In [5]: y
Out[5]: [2, 3, 4, 7, 8, 9]
In [6]: x += [44, 55]
In [7]: x
Out[7]: [2, 3, 4, 7, 8, 9, 44, 55]
In [8]: y
Out[8]: [2, 3, 4, 7, 8, 9, 44, 55]
In [9]: x = x + [33, 22]
In [10]: x
Out[10]: [2, 3, 4, 7, 8, 9, 44, 55, 33, 22]
In [11]: y
Out[11]: [2, 3, 4, 7, 8, 9, 44, 55]
See for reference: Why does += behave unexpectedly on lists?
...
for(int i=0;i<3;i++){ //Rows
for(int j=0;j<5;j++){ //Cols
printf("%<...>\t",var);
}
printf("\n");
}
...
considering that <...> would be d,e,f,s,c... etc datatype... X)
As said by jensgram, IE6 does not support attribute selector. You could add a class="disabled" to select the disabled inputs so that this can work in IE6.
I know this is an old thread, but I recently needed this for a large scale project (Python 3.8). It had to work on any mainstream OS, so therefore I went with the solution @Max wrote in the comments.
Code:
import os
print(os.path.expanduser("~"))
Output Windows:
PS C:\Python> & C:/Python38/python.exe c:/Python/test.py
C:\Users\mXXXXX
Output Linux (Ubuntu):
rxxx@xx:/mnt/c/Python$ python3 test.py
/home/rxxx
I also tested it on Python 2.7.17 and that works too.
step -*1
movie_list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/selectableItemBackground"
android:clickable="true"
android:focusable="true"
android:orientation="horizontal"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/row_padding_vertical"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingBottom="@dimen/row_padding_vertical">
<ImageView
android:id="@+id/ivImage"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_marginRight="10dp"
android:src="@mipmap/ic_launcher" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="Hello"
android:textColor="@color/title"
android:textSize="16dp"
android:textStyle="bold" />
<TextView
android:id="@+id/genre"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/title"
android:text="realName" />
</LinearLayout>
<TextView
android:id="@+id/year"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="Team"
android:textColor="@color/year" />
</LinearLayout>
Api.java
import org.json.JSONObject;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
public interface Api {
String BASE_URL = "https://simplifiedcoding.net/demos/";
@GET("marvel")
Call<List<Hero>> getHeroes();
@FormUrlEncoded
@POST("/login")
public void login(@Field("username") String username, @Field("password") String password, Callback<List<Hero>> callback);
}
MoviesAdapter.java import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.List;
public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MyViewHolder> {
private List<Hero> moviesList;
Context context;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, year, genre;
public ImageView ivImage;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
genre = (TextView) view.findViewById(R.id.genre);
year = (TextView) view.findViewById(R.id.year);
ivImage = view.findViewById(R.id.ivImage);
ivImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(context, "-" + moviesList.get(getAdapterPosition()).getName(), Toast.LENGTH_SHORT).show();
}
});
}
}
public MoviesAdapter(List<Hero> moviesList,Context context) {
this.moviesList = moviesList;
this.context = context;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.movie_list_row, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Hero movie = moviesList.get(position);
holder.title.setText(movie.getName());
holder.genre.setText(movie.getRealname());
holder.year.setText(movie.getTeam());
Picasso.get().load("http://i.imgur.com/DvpvklR.png").into(holder.ivImage);
}
@Override
public int getItemCount() {
return moviesList.size();
}
} main activity import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
private List<Hero> movieList = new ArrayList<>();
private RecyclerView recyclerView;
private MoviesAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView=findViewById(R.id.recycler_view);
mAdapter = new MoviesAdapter(movieList,MainActivity.this);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
//calling the method to display the heroes
getHeroes();
}
private void getHeroes() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiInterface.BASE_URL)
.addConverterFactory(GsonConverterFactory.create()) //Here we are using the GsonConverterFactory to directly convert json data to object
.build();
ApiInterface api = retrofit.create(ApiInterface.class);
Call<List<Hero>> call = api.getHeroes();
call.enqueue(new Callback<List<Hero>>() {
@Override
public void onResponse(Call<List<Hero>> call, Response<List<Hero>> response) {
List<Hero> heroList = response.body();
//Creating an String array for the ListView
String[] heroes = new String[heroList.size()];
//looping through all the heroes and inserting the names inside the string array
for (int i = 0; i < heroList.size(); i++) {
//heroes[i] = heroList.get(i).getName();
movieList.add(new Hero( heroList.get(i).getName(), heroList.get(i).getRealname(), heroList.get(i).getTeam()));
}
mAdapter.notifyDataSetChanged();
}
@Override
public void onFailure(Call<List<Hero>> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
Hero.java
package com.example.owner.apipractice;
public class Hero {
private String name;
private String realname;
private String team;
public Hero(String name, String realname, String team) {
this.name = name;
this.realname = realname;
this.team = team;
}
private String firstappearance;
private String createdby;
private String publisher;
private String imageurl;
private String bio;
public Hero(String name, String realname, String team, String firstappearance, String createdby, String publisher, String imageurl, String bio) {
this.name = name;
this.realname = realname;
this.team = team;
this.firstappearance = firstappearance;
this.createdby = createdby;
this.publisher = publisher;
this.imageurl = imageurl;
this.bio = bio;
}
public String getName() {
return name;
}
public String getRealname() {
return realname;
}
public String getTeam() {
return team;
}
public String getFirstappearance() {
return firstappearance;
}
public String getCreatedby() {
return createdby;
}
public String getPublisher() {
return publisher;
}
public String getImageurl() {
return imageurl;
}
public String getBio() {
return bio;
}
}
An example:
log4j.rootLogger=ERROR, logfile
log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.logfile.datePattern='-'dd'.log'
log4j.appender.logfile.File=log/radius-prod.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x - %m\n
log4j.logger.foo.bar.Baz=DEBUG, myappender
log4j.additivity.foo.bar.Baz=false
log4j.appender.myappender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.myappender.datePattern='-'dd'.log'
log4j.appender.myappender.File=log/access-ext-dmz-prod.log
log4j.appender.myappender.layout=org.apache.log4j.PatternLayout
log4j.appender.myappender.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x - %m\n
There is an updated version of Tom Gibara's tutorial. You can change the Webcam Broadcaster to work with JMyron instead of the old JMF.
The new emulator (sdk r15) manage webcams ; but it has some problems with integrated webcams (at least with mine's ^^)
check String before set another EditText
to empty. if Field1
is empty then why need to change again to ( "" )? so you can check the size of Your String with s.lenght() or any other solution
another way that you can check lenght of String is:
String sUsername = Field1.getText().toString();
if (!sUsername.matches(""))
{
// do your job
}
The default configuration of most SMTP servers is not to relay from an untrusted source to outside domains. For example, imagine that you contact the SMTP server for foo.com and ask it to send a message to [email protected]. Because the SMTP server doesn't really know who you are, it will refuse to relay the message. If the server did do that for you, it would be considered an open relay, which is how spammers often do their thing.
If you contact the foo.com mail server and ask it to send mail to [email protected], it might let you do it. It depends on if they trust that you're who you say you are. Often, the server will try to do a reverse DNS lookup, and refuse to send mail if the IP you're sending from doesn't match the IP address of the MX record in DNS. So if you say that you're the bar.com mail server but your IP address doesn't match the MX record for bar.com, then it will refuse to deliver the message.
You'll need to talk to the administrator of that SMTP server to get the authentication information so that it will allow relay for you. You'll need to present those credentials when you contact the SMTP server. Usually it's either a user name/password, or it can use Windows permissions. Depends on the server and how it's configured.
See Unable to send emails to external domain using SMTP for an example of how to send the credentials.