Python has importing and namespacing, which are good. In Python you can import into the current namespace, like:
>>> from test import disp
>>> disp('World!')
Or with a namespace:
>>> import test
>>> test.disp('World!')
To find second max salary from employee,
SELECT MAX(salary) FROM employee
WHERE salary NOT IN (
SELECT MAX (salary) FROM employee
)
To find first and second max salary from employee,
SELECT salary FROM (
SELECT DISTINCT(salary) FROM employee ORDER BY salary DESC
) WHERE rownum<=2
This queries are working fine because i have used
Well firstly C doesn't have public/private/virtual functions. That's C++ and it has different conventions. In C typically you have:
C++ is more complex. I've seen a real mix here. Camel case for class names or lowercase+underscores (camel case is more common in my experience). Structs are used rarely (and typically because a library requires them, otherwise you'd use classes).
You can also remove them by adding code to your global.asax file:
protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
HttpContext.Current.Response.Headers.Remove("X-Powered-By");
HttpContext.Current.Response.Headers.Remove("X-AspNet-Version");
HttpContext.Current.Response.Headers.Remove("X-AspNetMvc-Version");
HttpContext.Current.Response.Headers.Remove("Server");
}
I like using StringBuilder
with Aggregate()
. The "trick" is that Append()
returns the StringBuilder
instance itself:
var sb = arr.Aggregate( new StringBuilder(), ( s, i ) => s.Append( i ) );
var result = sb.ToString();
I am using DBLINK to connect internal database for cross database queries.
Reference taken from this article.
Install DbLink extension.
CREATE EXTENSION dblink;
Verify DbLink:
SELECT pg_namespace.nspname, pg_proc.proname
FROM pg_proc, pg_namespace
WHERE pg_proc.pronamespace=pg_namespace.oid
AND pg_proc.proname LIKE '%dblink%';
Test connection of database:
SELECT dblink_connect('host=localhost user=postgres password=enjoy dbname=postgres');
Unless the OP is using PowerShell Community Extensions which does provide a Start-Process cmdlet along with a bunch of others. If this the case then Glennular's solution works a treat since it matches the positional parameters of pscx\start-process : -path (position 1) -arguments (positon 2).
If you are using XAMPP on Mac, this worked for me:
Moving the CSV/TXT file to /Applications/XAMPP/xamppfiles/htdocs/ as following
LOAD DATA LOCAL INFILE '/Applications/XAMPP/xamppfiles/htdocs/file.csv' INTO TABLE `tablename` FIELDS TERMINATED BY ',' LINES TERMINATED BY ';'
Try:
CREATE TABLE foo SELECT * FROM bar LIMIT 0
Or:
CREATE TABLE foo SELECT * FROM bar WHERE 1=0
In most cases without adding the !important
to the CSS code, it won't work.
!important
a, a:active, a:focus{
outline: none !important; /* Works in Firefox, Chrome, IE8 and above */
}
Or any other code:
button::-moz-focus-inner {
border: 0 !important;
}
You can't actually render markup inside a textarea.
But, you can fake it by carefully positioning a div behind the textarea and adding your highlight markup there.
JavaScript takes care of syncing the content and scroll position.
var $container = $('.container');
var $backdrop = $('.backdrop');
var $highlights = $('.highlights');
var $textarea = $('textarea');
var $toggle = $('button');
var ua = window.navigator.userAgent.toLowerCase();
var isIE = !!ua.match(/msie|trident\/7|edge/);
var isWinPhone = ua.indexOf('windows phone') !== -1;
var isIOS = !isWinPhone && !!ua.match(/ipad|iphone|ipod/);
function applyHighlights(text) {
text = text
.replace(/\n$/g, '\n\n')
.replace(/[A-Z].*?\b/g, '<mark>$&</mark>');
if (isIE) {
// IE wraps whitespace differently in a div vs textarea, this fixes it
text = text.replace(/ /g, ' <wbr>');
}
return text;
}
function handleInput() {
var text = $textarea.val();
var highlightedText = applyHighlights(text);
$highlights.html(highlightedText);
}
function handleScroll() {
var scrollTop = $textarea.scrollTop();
$backdrop.scrollTop(scrollTop);
var scrollLeft = $textarea.scrollLeft();
$backdrop.scrollLeft(scrollLeft);
}
function fixIOS() {
$highlights.css({
'padding-left': '+=3px',
'padding-right': '+=3px'
});
}
function bindEvents() {
$textarea.on({
'input': handleInput,
'scroll': handleScroll
});
}
if (isIOS) {
fixIOS();
}
bindEvents();
handleInput();
_x000D_
@import url(https://fonts.googleapis.com/css?family=Open+Sans);
*,
*::before,
*::after {
box-sizing: border-box;
}
body {
margin: 30px;
background-color: #fff;
caret-color: #000;
}
.container,
.backdrop,
textarea {
width: 460px;
height: 180px;
}
.highlights,
textarea {
padding: 10px;
font: 20px/28px 'Open Sans', sans-serif;
letter-spacing: 1px;
}
.container {
display: block;
margin: 0 auto;
transform: translateZ(0);
-webkit-text-size-adjust: none;
}
.backdrop {
position: absolute;
z-index: 1;
border: 2px solid #685972;
background-color: #fff;
overflow: auto;
pointer-events: none;
transition: transform 1s;
}
.highlights {
white-space: pre-wrap;
word-wrap: break-word;
color: #000;
}
textarea {
display: block;
position: absolute;
z-index: 2;
margin: 0;
border: 2px solid #74637f;
border-radius: 0;
color: transparent;
background-color: transparent;
overflow: auto;
resize: none;
transition: transform 1s;
}
mark {
border-radius: 3px;
color: red;
background-color: transparent;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="backdrop">
<div class="highlights"></div>
</div>
<textarea>All capitalized Words will be highlighted. Try Typing to see how it Works</textarea>
</div>
_x000D_
Original Pen: https://codepen.io/lonekorean/pen/gaLEMR
Swift 3:
let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: [])
let jsonString = String(data: jsonData!, encoding: .utf8)!
print(jsonString)
!foo.dll
in .gitignore, or (every time!) git add -f foo.dll
You can do this simply with a function. For example:
def script():
# program code here...
restart = raw_input("Would you like to restart this program?")
if restart == "yes" or restart == "y":
script()
if restart == "n" or restart == "no":
print "Script terminating. Goodbye."
script()
Of course you can change a lot of things here. What is said, what the script will accept as a valid input, the variable and function names. You can simply nest the entire program in a user-defined function (Of course you must give everything inside an extra indent) and have it restart at anytime using this line of code: myfunctionname()
. More on this here.
JQuery 10.1.2 has a nice show and hide functions that encapsulate the behavior you are talking about. This would save you having to write a new function or keep track of css classes.
$("new").show();
$("new").hide();
The route-map express example matches url paths with objects which in turn matches http verbs with functions. This lays the routing out in a tree, which is concise and easy to read. The apps's entities are also written as objects with the functions as enclosed methods.
var express = require('../../lib/express')
, verbose = process.env.NODE_ENV != 'test'
, app = module.exports = express();
app.map = function(a, route){
route = route || '';
for (var key in a) {
switch (typeof a[key]) {
// { '/path': { ... }}
case 'object':
app.map(a[key], route + key);
break;
// get: function(){ ... }
case 'function':
if (verbose) console.log('%s %s', key, route);
app[key](route, a[key]);
break;
}
}
};
var users = {
list: function(req, res){
res.send('user list');
},
get: function(req, res){
res.send('user ' + req.params.uid);
},
del: function(req, res){
res.send('delete users');
}
};
var pets = {
list: function(req, res){
res.send('user ' + req.params.uid + '\'s pets');
},
del: function(req, res){
res.send('delete ' + req.params.uid + '\'s pet ' + req.params.pid);
}
};
app.map({
'/users': {
get: users.list,
del: users.del,
'/:uid': {
get: users.get,
'/pets': {
get: pets.list,
'/:pid': {
del: pets.del
}
}
}
}
});
app.listen(3000);
If you want to do this in a robust way that works for every possible command line argument (values with spaces, values with newlines, values with literal quote characters, non-printable values, values with glob characters, etc), it gets a bit more interesting.
To write to a file, given an array of arguments:
printf '%s\0' "${arguments[@]}" >file
...replace with "argument one"
, "argument two"
, etc. as appropriate.
To read from that file and use its contents (in bash, ksh93, or another recent shell with arrays):
declare -a args=()
while IFS='' read -r -d '' item; do
args+=( "$item" )
done <file
run_your_command "${args[@]}"
To read from that file and use its contents (in a shell without arrays; note that this will overwrite your local command-line argument list, and is thus best done inside of a function, such that you're overwriting the function's arguments and not the global list):
set --
while IFS='' read -r -d '' item; do
set -- "$@" "$item"
done <file
run_your_command "$@"
Note that -d
(allowing a different end-of-line delimiter to be used) is a non-POSIX extension, and a shell without arrays may also not support it. Should that be the case, you may need to use a non-shell language to transform the NUL-delimited content into an eval
-safe form:
quoted_list() {
## Works with either Python 2.x or 3.x
python -c '
import sys, pipes, shlex
quote = pipes.quote if hasattr(pipes, "quote") else shlex.quote
print(" ".join([quote(s) for s in sys.stdin.read().split("\0")][:-1]))
'
}
eval "set -- $(quoted_list <file)"
run_your_command "$@"
There are two models for implementing classes and instances in JavaScript: the prototyping way, and the closure way. Both have advantages and drawbacks, and there are plenty of extended variations. Many programmers and libraries have different approaches and class-handling utility functions to paper over some of the uglier parts of the language.
The result is that in mixed company you will have a mishmash of metaclasses, all behaving slightly differently. What's worse, most JavaScript tutorial material is terrible and serves up some kind of in-between compromise to cover all bases, leaving you very confused. (Probably the author is also confused. JavaScript's object model is very different to most programming languages, and in many places straight-up badly designed.)
Let's start with the prototype way. This is the most JavaScript-native you can get: there is a minimum of overhead code and instanceof will work with instances of this kind of object.
function Shape(x, y) {
this.x= x;
this.y= y;
}
We can add methods to the instance created by new Shape
by writing them to the prototype
lookup of this constructor function:
Shape.prototype.toString= function() {
return 'Shape at '+this.x+', '+this.y;
};
Now to subclass it, in as much as you can call what JavaScript does subclassing. We do that by completely replacing that weird magic prototype
property:
function Circle(x, y, r) {
Shape.call(this, x, y); // invoke the base class's constructor function to take co-ords
this.r= r;
}
Circle.prototype= new Shape();
before adding methods to it:
Circle.prototype.toString= function() {
return 'Circular '+Shape.prototype.toString.call(this)+' with radius '+this.r;
}
This example will work and you will see code like it in many tutorials. But man, that new Shape()
is ugly: we're instantiating the base class even though no actual Shape is to be created. It happens to work in this simple case because JavaScript is so sloppy: it allows zero arguments to be passed in, in which case x
and y
become undefined
and are assigned to the prototype's this.x
and this.y
. If the constructor function were doing anything more complicated, it would fall flat on its face.
So what we need to do is find a way to create a prototype object which contains the methods and other members we want at a class level, without calling the base class's constructor function. To do this we are going to have to start writing helper code. This is the simplest approach I know of:
function subclassOf(base) {
_subclassOf.prototype= base.prototype;
return new _subclassOf();
}
function _subclassOf() {};
This transfers the base class's members in its prototype to a new constructor function which does nothing, then uses that constructor. Now we can write simply:
function Circle(x, y, r) {
Shape.call(this, x, y);
this.r= r;
}
Circle.prototype= subclassOf(Shape);
instead of the new Shape()
wrongness. We now have an acceptable set of primitives to built classes.
There are a few refinements and extensions we can consider under this model. For example here is a syntactical-sugar version:
Function.prototype.subclass= function(base) {
var c= Function.prototype.subclass.nonconstructor;
c.prototype= base.prototype;
this.prototype= new c();
};
Function.prototype.subclass.nonconstructor= function() {};
...
function Circle(x, y, r) {
Shape.call(this, x, y);
this.r= r;
}
Circle.subclass(Shape);
Either version has the drawback that the constructor function cannot be inherited, as it is in many languages. So even if your subclass adds nothing to the construction process, it must remember to call the base constructor with whatever arguments the base wanted. This can be slightly automated using apply
, but still you have to write out:
function Point() {
Shape.apply(this, arguments);
}
Point.subclass(Shape);
So a common extension is to break out the initialisation stuff into its own function rather than the constructor itself. This function can then inherit from the base just fine:
function Shape() { this._init.apply(this, arguments); }
Shape.prototype._init= function(x, y) {
this.x= x;
this.y= y;
};
function Point() { this._init.apply(this, arguments); }
Point.subclass(Shape);
// no need to write new initialiser for Point!
Now we've just got the same constructor function boilerplate for each class. Maybe we can move that out into its own helper function so we don't have to keep typing it, for example instead of Function.prototype.subclass
, turning it round and letting the base class's Function spit out subclasses:
Function.prototype.makeSubclass= function() {
function Class() {
if ('_init' in this)
this._init.apply(this, arguments);
}
Function.prototype.makeSubclass.nonconstructor.prototype= this.prototype;
Class.prototype= new Function.prototype.makeSubclass.nonconstructor();
return Class;
};
Function.prototype.makeSubclass.nonconstructor= function() {};
...
Shape= Object.makeSubclass();
Shape.prototype._init= function(x, y) {
this.x= x;
this.y= y;
};
Point= Shape.makeSubclass();
Circle= Shape.makeSubclass();
Circle.prototype._init= function(x, y, r) {
Shape.prototype._init.call(this, x, y);
this.r= r;
};
...which is starting to look a bit more like other languages, albeit with slightly clumsier syntax. You can sprinkle in a few extra features if you like. Maybe you want makeSubclass
to take and remember a class name and provide a default toString
using it. Maybe you want to make the constructor detect when it has accidentally been called without the new
operator (which would otherwise often result in very annoying debugging):
Function.prototype.makeSubclass= function() {
function Class() {
if (!(this instanceof Class))
throw('Constructor called without "new"');
...
Maybe you want to pass in all the new members and have makeSubclass
add them to the prototype, to save you having to write Class.prototype...
quite so much. A lot of class systems do that, eg:
Circle= Shape.makeSubclass({
_init: function(x, y, z) {
Shape.prototype._init.call(this, x, y);
this.r= r;
},
...
});
There are a lot of potential features you might consider desirable in an object system and no-one really agrees on one particular formula.
The closure way, then. This avoids the problems of JavaScript's prototype-based inheritance, by not using inheritance at all. Instead:
function Shape(x, y) {
var that= this;
this.x= x;
this.y= y;
this.toString= function() {
return 'Shape at '+that.x+', '+that.y;
};
}
function Circle(x, y, r) {
var that= this;
Shape.call(this, x, y);
this.r= r;
var _baseToString= this.toString;
this.toString= function() {
return 'Circular '+_baseToString(that)+' with radius '+that.r;
};
};
var mycircle= new Circle();
Now every single instance of Shape
will have its own copy of the toString
method (and any other methods or other class members we add).
The bad thing about every instance having its own copy of each class member is that it's less efficient. If you are dealing with large numbers of subclassed instances, prototypical inheritance may serve you better. Also calling a method of the base class is slightly annoying as you can see: we have to remember what the method was before the subclass constructor overwrote it, or it gets lost.
[Also because there is no inheritance here, the instanceof
operator won't work; you would have to provide your own mechanism for class-sniffing if you need it. Whilst you could fiddle the prototype objects in a similar way as with prototype inheritance, it's a bit tricky and not really worth it just to get instanceof
working.]
The good thing about every instance having its own method is that the method may then be bound to the specific instance that owns it. This is useful because of JavaScript's weird way of binding this
in method calls, which has the upshot that if you detach a method from its owner:
var ts= mycircle.toString;
alert(ts());
then this
inside the method won't be the Circle instance as expected (it'll actually be the global window
object, causing widespread debugging woe). In reality this typically happens when a method is taken and assigned to a setTimeout
, onclick
or EventListener
in general.
With the prototype way, you have to include a closure for every such assignment:
setTimeout(function() {
mycircle.move(1, 1);
}, 1000);
or, in the future (or now if you hack Function.prototype) you can also do it with function.bind()
:
setTimeout(mycircle.move.bind(mycircle, 1, 1), 1000);
if your instances are done the closure way, the binding is done for free by the closure over the instance variable (usually called that
or self
, though personally I would advise against the latter as self
already has another, different meaning in JavaScript). You don't get the arguments 1, 1
in the above snippet for free though, so you would still need another closure or a bind()
if you need to do that.
There are lots of variants on the closure method too. You may prefer to omit this
completely, creating a new that
and returning it instead of using the new
operator:
function Shape(x, y) {
var that= {};
that.x= x;
that.y= y;
that.toString= function() {
return 'Shape at '+that.x+', '+that.y;
};
return that;
}
function Circle(x, y, r) {
var that= Shape(x, y);
that.r= r;
var _baseToString= that.toString;
that.toString= function() {
return 'Circular '+_baseToString(that)+' with radius '+r;
};
return that;
};
var mycircle= Circle(); // you can include `new` if you want but it won't do anything
Which way is “proper”? Both. Which is “best”? That depends on your situation. FWIW I tend towards prototyping for real JavaScript inheritance when I'm doing strongly OO stuff, and closures for simple throwaway page effects.
But both ways are quite counter-intuitive to most programmers. Both have many potential messy variations. You will meet both (as well as many in-between and generally broken schemes) if you use other people's code/libraries. There is no one generally-accepted answer. Welcome to the wonderful world of JavaScript objects.
[This has been part 94 of Why JavaScript Is Not My Favourite Programming Language.]
I was getting a lot of empty text nodes with the accepted filter function. If you're only interested in selecting text nodes that contain non-whitespace, try adding a nodeValue
conditional to your filter
function, like a simple $.trim(this.nodevalue) !== ''
:
$('element')
.contents()
.filter(function(){
return this.nodeType === 3 && $.trim(this.nodeValue) !== '';
});
Or to avoid strange situations where the content looks like whitespace, but is not (e.g. the soft hyphen ­
character, newlines \n
, tabs, etc.), you can try using a Regular Expression. For example, \S
will match any non-whitespace characters:
$('element')
.contents()
.filter(function(){
return this.nodeType === 3 && /\S/.test(this.nodeValue);
});
For turning off line numbers, any of these commands will work:
What I need is to use Docker with MariaDb on different port /3301/ on my Ubuntu machine because I already had MySql installed and running on 3306.
To do this after half day searching did it using:
docker run -it -d -p 3301:3306 -v ~/mdbdata/mariaDb:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=root --name mariaDb mariadb
This pulls the image with latest MariaDb, creates container called mariaDb, and run mysql on port 3301. All data of which is located in home directory in /mdbdata/mariaDb.
To login in mysql after that can use:
mysql -u root -proot -h 127.0.0.1 -P3301
Used sources are:
The answer of Iarks in this article /using -it -d was the key :) /
how-to-install-and-use-docker-on-ubuntu-16-04
installing-and-using-mariadb-via-docker
mariadb-and-docker-use-cases-part-1
Good luck all!
Try this:
ISNULL(IIF (ColunmValue!='',ColunmValue, 'no units exists') , 'no units exists') AS 'ColunmValueName'
The Spring security filter chain is a very complex and flexible engine.
Key filters in the chain are (in the order)
- SecurityContextPersistenceFilter (restores Authentication from JSESSIONID)
- UsernamePasswordAuthenticationFilter (performs authentication)
- ExceptionTranslationFilter (catch security exceptions from FilterSecurityInterceptor)
- FilterSecurityInterceptor (may throw authentication and authorization exceptions)
Looking at the current stable release 4.2.1 documentation, section 13.3 Filter Ordering you could see the whole filter chain's filter organization:
13.3 Filter Ordering
The order that filters are defined in the chain is very important. Irrespective of which filters you are actually using, the order should be as follows:
ChannelProcessingFilter, because it might need to redirect to a different protocol
SecurityContextPersistenceFilter, so a SecurityContext can be set up in the SecurityContextHolder at the beginning of a web request, and any changes to the SecurityContext can be copied to the HttpSession when the web request ends (ready for use with the next web request)
ConcurrentSessionFilter, because it uses the SecurityContextHolder functionality and needs to update the SessionRegistry to reflect ongoing requests from the principal
Authentication processing mechanisms - UsernamePasswordAuthenticationFilter, CasAuthenticationFilter, BasicAuthenticationFilter etc - so that the SecurityContextHolder can be modified to contain a valid Authentication request token
The SecurityContextHolderAwareRequestFilter, if you are using it to install a Spring Security aware HttpServletRequestWrapper into your servlet container
The JaasApiIntegrationFilter, if a JaasAuthenticationToken is in the SecurityContextHolder this will process the FilterChain as the Subject in the JaasAuthenticationToken
RememberMeAuthenticationFilter, so that if no earlier authentication processing mechanism updated the SecurityContextHolder, and the request presents a cookie that enables remember-me services to take place, a suitable remembered Authentication object will be put there
AnonymousAuthenticationFilter, so that if no earlier authentication processing mechanism updated the SecurityContextHolder, an anonymous Authentication object will be put there
ExceptionTranslationFilter, to catch any Spring Security exceptions so that either an HTTP error response can be returned or an appropriate AuthenticationEntryPoint can be launched
FilterSecurityInterceptor, to protect web URIs and raise exceptions when access is denied
Now, I'll try to go on by your questions one by one:
I'm confused how these filters are used. Is it that for the spring provided form-login, UsernamePasswordAuthenticationFilter is only used for /login, and latter filters are not? Does the form-login namespace element auto-configure these filters? Does every request (authenticated or not) reach FilterSecurityInterceptor for non-login url?
Once you are configuring a <security-http>
section, for each one you must at least provide one authentication mechanism. This must be one of the filters which match group 4 in the 13.3 Filter Ordering section from the Spring Security documentation I've just referenced.
This is the minimum valid security:http element which can be configured:
<security:http authentication-manager-ref="mainAuthenticationManager"
entry-point-ref="serviceAccessDeniedHandler">
<security:intercept-url pattern="/sectest/zone1/**" access="hasRole('ROLE_ADMIN')"/>
</security:http>
Just doing it, these filters are configured in the filter chain proxy:
{
"1": "org.springframework.security.web.context.SecurityContextPersistenceFilter",
"2": "org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter",
"3": "org.springframework.security.web.header.HeaderWriterFilter",
"4": "org.springframework.security.web.csrf.CsrfFilter",
"5": "org.springframework.security.web.savedrequest.RequestCacheAwareFilter",
"6": "org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter",
"7": "org.springframework.security.web.authentication.AnonymousAuthenticationFilter",
"8": "org.springframework.security.web.session.SessionManagementFilter",
"9": "org.springframework.security.web.access.ExceptionTranslationFilter",
"10": "org.springframework.security.web.access.intercept.FilterSecurityInterceptor"
}
Note: I get them by creating a simple RestController which @Autowires the FilterChainProxy and returns it's contents:
@Autowired
private FilterChainProxy filterChainProxy;
@Override
@RequestMapping("/filterChain")
public @ResponseBody Map<Integer, Map<Integer, String>> getSecurityFilterChainProxy(){
return this.getSecurityFilterChainProxy();
}
public Map<Integer, Map<Integer, String>> getSecurityFilterChainProxy(){
Map<Integer, Map<Integer, String>> filterChains= new HashMap<Integer, Map<Integer, String>>();
int i = 1;
for(SecurityFilterChain secfc : this.filterChainProxy.getFilterChains()){
//filters.put(i++, secfc.getClass().getName());
Map<Integer, String> filters = new HashMap<Integer, String>();
int j = 1;
for(Filter filter : secfc.getFilters()){
filters.put(j++, filter.getClass().getName());
}
filterChains.put(i++, filters);
}
return filterChains;
}
Here we could see that just by declaring the <security:http>
element with one minimum configuration, all the default filters are included, but none of them is of a Authentication type (4th group in 13.3 Filter Ordering section). So it actually means that just by declaring the security:http
element, the SecurityContextPersistenceFilter, the ExceptionTranslationFilter and the FilterSecurityInterceptor are auto-configured.
In fact, one authentication processing mechanism should be configured, and even security namespace beans processing claims for that, throwing an error during startup, but it can be bypassed adding an entry-point-ref attribute in <http:security>
If I add a basic <form-login>
to the configuration, this way:
<security:http authentication-manager-ref="mainAuthenticationManager">
<security:intercept-url pattern="/sectest/zone1/**" access="hasRole('ROLE_ADMIN')"/>
<security:form-login />
</security:http>
Now, the filterChain will be like this:
{
"1": "org.springframework.security.web.context.SecurityContextPersistenceFilter",
"2": "org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter",
"3": "org.springframework.security.web.header.HeaderWriterFilter",
"4": "org.springframework.security.web.csrf.CsrfFilter",
"5": "org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter",
"6": "org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter",
"7": "org.springframework.security.web.savedrequest.RequestCacheAwareFilter",
"8": "org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter",
"9": "org.springframework.security.web.authentication.AnonymousAuthenticationFilter",
"10": "org.springframework.security.web.session.SessionManagementFilter",
"11": "org.springframework.security.web.access.ExceptionTranslationFilter",
"12": "org.springframework.security.web.access.intercept.FilterSecurityInterceptor"
}
Now, this two filters org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter and org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter are created and configured in the FilterChainProxy.
So, now, the questions:
Is it that for the spring provided form-login, UsernamePasswordAuthenticationFilter is only used for /login, and latter filters are not?
Yes, it is used to try to complete a login processing mechanism in case the request matches the UsernamePasswordAuthenticationFilter url. This url can be configured or even changed it's behaviour to match every request.
You could too have more than one Authentication processing mechanisms configured in the same FilterchainProxy (such as HttpBasic, CAS, etc).
Does the form-login namespace element auto-configure these filters?
No, the form-login element configures the UsernamePasswordAUthenticationFilter, and in case you don't provide a login-page url, it also configures the org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter, which ends in a simple autogenerated login page.
The other filters are auto-configured by default just by creating a <security:http>
element with no security:"none"
attribute.
Does every request (authenticated or not) reach FilterSecurityInterceptor for non-login url?
Every request should reach it, as it is the element which takes care of whether the request has the rights to reach the requested url. But some of the filters processed before might stop the filter chain processing just not calling FilterChain.doFilter(request, response);
. For example, a CSRF filter might stop the filter chain processing if the request has not the csrf parameter.
What if I want to secure my REST API with JWT-token, which is retrieved from login? I must configure two namespace configuration http tags, rights? Other one for /login with
UsernamePasswordAuthenticationFilter
, and another one for REST url's, with customJwtAuthenticationFilter
.
No, you are not forced to do this way. You could declare both UsernamePasswordAuthenticationFilter
and the JwtAuthenticationFilter
in the same http element, but it depends on the concrete behaviour of each of this filters. Both approaches are possible, and which one to choose finnally depends on own preferences.
Does configuring two http elements create two springSecurityFitlerChains?
Yes, that's true
Is UsernamePasswordAuthenticationFilter turned off by default, until I declare form-login?
Yes, you could see it in the filters raised in each one of the configs I posted
How do I replace SecurityContextPersistenceFilter with one, which will obtain Authentication from existing JWT-token rather than JSESSIONID?
You could avoid SecurityContextPersistenceFilter, just configuring session strategy in <http:element>
. Just configure like this:
<security:http create-session="stateless" >
Or, In this case you could overwrite it with another filter, this way inside the <security:http>
element:
<security:http ...>
<security:custom-filter ref="myCustomFilter" position="SECURITY_CONTEXT_FILTER"/>
</security:http>
<beans:bean id="myCustomFilter" class="com.xyz.myFilter" />
EDIT:
One question about "You could too have more than one Authentication processing mechanisms configured in the same FilterchainProxy". Will the latter overwrite the authentication performed by first one, if declaring multiple (Spring implementation) authentication filters? How this relates to having multiple authentication providers?
This finally depends on the implementation of each filter itself, but it's true the fact that the latter authentication filters at least are able to overwrite any prior authentication eventually made by preceding filters.
But this won't necesarily happen. I have some production cases in secured REST services where I use a kind of authorization token which can be provided both as a Http header or inside the request body. So I configure two filters which recover that token, in one case from the Http Header and the other from the request body of the own rest request. It's true the fact that if one http request provides that authentication token both as Http header and inside the request body, both filters will try to execute the authentication mechanism delegating it to the manager, but it could be easily avoided simply checking if the request is already authenticated just at the begining of the doFilter()
method of each filter.
Having more than one authentication filter is related to having more than one authentication providers, but don't force it. In the case I exposed before, I have two authentication filter but I only have one authentication provider, as both of the filters create the same type of Authentication object so in both cases the authentication manager delegates it to the same provider.
And opposite to this, I too have a scenario where I publish just one UsernamePasswordAuthenticationFilter but the user credentials both can be contained in DB or LDAP, so I have two UsernamePasswordAuthenticationToken supporting providers, and the AuthenticationManager delegates any authentication attempt from the filter to the providers secuentially to validate the credentials.
So, I think it's clear that neither the amount of authentication filters determine the amount of authentication providers nor the amount of provider determine the amount of filters.
Also, documentation states SecurityContextPersistenceFilter is responsible of cleaning the SecurityContext, which is important due thread pooling. If I omit it or provide custom implementation, I have to implement the cleaning manually, right? Are there more similar gotcha's when customizing the chain?
I did not look carefully into this filter before, but after your last question I've been checking it's implementation, and as usually in Spring, nearly everything could be configured, extended or overwrited.
The SecurityContextPersistenceFilter delegates in a SecurityContextRepository implementation the search for the SecurityContext. By default, a HttpSessionSecurityContextRepository is used, but this could be changed using one of the constructors of the filter. So it may be better to write an SecurityContextRepository which fits your needs and just configure it in the SecurityContextPersistenceFilter, trusting in it's proved behaviour rather than start making all from scratch.
This works for me.
$("#file").replaceWith($("#file").clone());
http://forum.jquery.com/topic/how-to-clear-a-file-input-in-ie
Hope it helps.
You can code like this:
$query_select = "SELECT * FROM shouts ORDER BY id DESC LIMIT 8;";
$result_select = mysql_query($query_select) or die(mysql_error());
$rows = array();
while($row = mysql_fetch_array($result_select))
$rows[] = $row;
foreach($rows as $row){
$ename = stripslashes($row['name']);
$eemail = stripcslashes($row['email']);
$epost = stripslashes($row['post']);
$eid = $row['id'];
$grav_url = "http://www.gravatar.com/avatar.php?gravatar_id=".md5(strtolower($eemail))."&size=70";
echo ('<img src = "' . $grav_url . '" alt="Gravatar">'.'<br/>');
echo $eid . '<br/>';
echo $ename . '<br/>';
echo $eemail . '<br/>';
echo $epost . '<br/><br/><br/><br/>';
}
As you can see, it's still need a loop while to get data from mysql_fetch_array
A very simple Solution that i just Tried is:
1) Delete your Instalation Folder at ~/Genymobile
2) Delete the Virtual Device Folder at C:\Users\ your_name\AppData\Local/Genymobile
3) Reinstall
4) Done.
If you have multiple tables in the same worksheet you can give each table an object name and read the table using the OleDb method as shown here: http://vbktech.wordpress.com/2011/05/10/c-net-reading-and-writing-to-multiple-tables-in-the-same-microsoft-excel-worksheet/
Use the CSS z-index property. Elements with a greater z-index value are positioned in front of elements with smaller z-index values.
Note that for this to work, you also need to set a position
style (position:absolute
, position:relative
, or position:fixed
) on both/all of the elements you want to order.
You can use this full code for your problem. For more details you can check it on appucoder.com
class FileDemoTwo{
public static void main(String args[])throws Exception{
FileDemoTwo ob = new FileDemoTwo();
BufferedReader in = new BufferedReader(new FileReader("read.txt"));
String str;
List<String> list = new ArrayList<String>();
while((str =in.readLine()) != null ){
list.add(str);
}
String[] stringArr = list.toArray(new String[0]);
System.out.println(" "+Arrays.toString(stringArr));
}
}
scp as mentioned above is usually a best way, but don't forget colon in the remote directory spec otherwise you'll get copy of source directory on local machine.
txtPath.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)+"\\\Tasks";
Put a double backslash instead of a single backslash...
You should do something like this:
1) create directory object what would point to server-side accessible folder
CREATE DIRECTORY image_files AS '/data/images'
/
2) Place your file into OS folder directory object points to
3) Give required access privileges to Oracle schema what will load data from file into table:
GRANT READ ON DIRECTORY image_files TO scott
/
4) Use BFILENAME, EMPTY_BLOB functions and DBMS_LOB package (example NOT tested - be care) like in below:
DECLARE
l_blob BLOB;
v_src_loc BFILE := BFILENAME('IMAGE_FILES', 'myimage.png');
v_amount INTEGER;
BEGIN
INSERT INTO esignatures
VALUES (100, 'BOB', empty_blob()) RETURN iblob INTO l_blob;
DBMS_LOB.OPEN(v_src_loc, DBMS_LOB.LOB_READONLY);
v_amount := DBMS_LOB.GETLENGTH(v_src_loc);
DBMS_LOB.LOADFROMFILE(l_blob, v_src_loc, v_amount);
DBMS_LOB.CLOSE(v_src_loc);
COMMIT;
END;
/
After this you get the content of your file in BLOB column and can get it back using Java for example.
edit: One letter left missing: it should be LOADFROMFILE.
According to this Video if you use the ProGuard you don't need even think about Enums performance issues!!
Proguard can in many situations optimize Enums to INT values on your behalf so really don't need to think about it or do any work.
In React-Native we have an Option called Dimensions
Include Dimensions at the top var where you have include the Image,and Text and other components.
Then in your Stylesheets you can use as below,
ex: {
width: Dimensions.get('window').width,
height: Dimensions.get('window').height
}
In this way you can get the device window and height.
for MS excel 2000 office version, click on the pivot table you will find a tab above the ribon, called Pivottable tool - click on that You can change data source from Data tab
If you want to update react use npx update react
on the terminal.
Create new array:
var my_array = new Array();
Add elements to this array:
my_array.push("element1");
The function indexOf (returns index or -1 when not found):
var indexOf = function(needle)
{
if (typeof Array.prototype.indexOf === 'function') // Newer browsers
{
indexOf = Array.prototype.indexOf;
}
else // Older browsers
{
indexOf = function(needle)
{
var index = -1;
for (var i = 0; i < this.length; i++)
{
if (this[i] === needle)
{
index = i;
break;
}
}
return index;
};
}
return indexOf.call(this, needle);
};
Check index of this element (tested with Firefox and Internet Explorer 8 (and later)):
var index = indexOf.call(my_array, "element1");
Remove 1 element located at index from the array
my_array.splice(index, 1);
If you are using ES6 Classes and ControllerAs
syntax, you need to do something slightly different.
See the snippet below and note that vm
is the ControllerAs
value of the parent Controller as used in the parent HTML
myApp.directive('name', function() {
return {
// no scope definition
link : function(scope, element, attrs, ngModel) {
scope.vm.func(...)
I got same issue while using cygwin to install nvm
In fact, the target directory where empty but the git
binary used was the one from windows (and not git
from cygwin git package
).
After installing cygwin git package
, the git clone
from nvm
install was ok!
explode
does the job:
$parts = explode('.', $string);
You can also directly fetch parts of the result into variables:
list($part1, $part2) = explode('.', $string);
IE10 does not support DX filters as IE9 and earlier have done, nor does it support a prefixed version of the greyscale filter.
However, you can use an SVG overlay in IE10 to accomplish the greyscaling. Example:
img.grayscale:hover {
filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'1 0 0 0 0, 0 1 0 0 0, 0 0 1 0 0, 0 0 0 1 0\'/></filter></svg>#grayscale");
}
svg {
background:url(http://4.bp.blogspot.com/-IzPWLqY4gJ0/T01CPzNb1KI/AAAAAAAACgA/_8uyj68QhFE/s400/a2cf7051-5952-4b39-aca3-4481976cb242.jpg);
}
(from: http://www.karlhorky.com/2012/06/cross-browser-image-grayscale-with-css.html)
Simplified JSFiddle: http://jsfiddle.net/KatieK/qhU7d/2/
More about the IE10 SVG filter effects: http://blogs.msdn.com/b/ie/archive/2011/10/14/svg-filter-effects-in-ie10.aspx
@papigee should work on Windows 10 just fine. I'm using the integrated VSCode terminal with git bash and this always works for me.
winpty docker exec -it <container-id> //bin//sh
Here is a version that uses dataType html, but this is far less explicit, because i am returning an empty string to indicate an error.
Ajax call:
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'html',
data: {
email : $('#email').val()
},
success : function(data){
$('#waiting').hide(500);
$('#message').removeClass().addClass((data == '') ? 'error' : 'success')
.html(data).show(500);
if (data == '') {
$('#message').html("Format your email correcly");
$('#demoForm').show(500);
}
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#demoForm').show(500);
}
});
post.php
<?php
sleep(1);
function processEmail($email) {
if (preg_match("#^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$#", $email)) {
// your logic here (ex: add into database)
return true;
}
return false;
}
if (processEmail($_POST['email'])) {
echo "<span>Your email is <strong>{$_POST['email']}</strong></span>";
}
You can use sys.platform
:
from sys import platform
if platform == "linux" or platform == "linux2":
# linux
elif platform == "darwin":
# OS X
elif platform == "win32":
# Windows...
sys.platform
has finer granularity than sys.name
.
For the valid values, consult the documentation.
See also the answer to “What OS am I running on?”
Here's a simple snippet working in Java 8 and using the "new" date and time API LocalDateTime:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss.SS");
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now));
Pointer adaptation to the rescue!
Since this hasn't been touched in awhile, you can use:
a:link, a:visited {
color: red;
}
a:hover {
color:blue;
}
@media (hover: none) {
a:link, a:visited {
color: red;
}
}
See this demo in both your desktop browser and your phone browser. Supported by modern touch devices.
Note: Keep in mind that since a Surface PC's primary input (capability) is a mouse, it will end up being a blue link, even if it's a detached (tablet) screen. Browsers will (should) always default to the most precise input's capability.
You can do this also:
$("a.markAsDone").click(function (event) {
event.preventDefault();
$.ajax({
type: "post",
dataType: "html",
url: $(this).attr("rel"),
data: $('<form>@Html.AntiForgeryToken()</form>').serialize(),
success: function (response) {
// ....
}
});
});
This is using Razor
, but if you're using WebForms
syntax you can just as well use <%= %>
tags
You are debugging two or more times. so the application may run more at a time. Then only this issue will occur. You should close all debugging applications using task-manager, Then debug again.
<?php
if(empty($myarray))
echo"true";
else
echo "false";
?>
you are missing the "btn btn-navbar" section. For example:
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
Take a look to navbar documentation in:
The problem is that your PATH does not include the location of the node executable.
You can likely run node as "/usr/local/bin/node
".
You can add that location to your path by running the following command to add a single line to your bashrc file:
echo 'export PATH=$PATH:/usr/local/bin' >> $HOME/.bashrc
No, I think you are thinking of stack space. Heap space is occupied by objects. The way to increase it is -Xmx256m, replacing the 256 with the amount you need on the command line.
To truly force maven to only use your local repo, you can run with mvn <goals> -o
. The -o
tells maven to let you work "offline", and it will stay off the network.
It's similar to above but you can try like
public Integer count(String tableName) throws CrateException {
String query = String.format("Select count(*) as size from %s", tableName);
try (Statement s = connection.createStatement()) {
try (ResultSet resultSet = queryExecutor.executeQuery(s, query)) {
Preconditions.checkArgument(resultSet.next(), "Result set is empty");
return resultSet.getInt("size");
}
} catch (SQLException e) {
throw new CrateException(e);
}
}
}
<div id="elem" class="className"></div>
With Javascript
document.getElementById('elem').className;
With jQuery
$('#elem').attr('class');
OR
$('#elem').get(0).className;
You have a couple of choices. For one, you can use the os.path.getmtime
and os.path.getctime
functions:
import os.path, time
print("last modified: %s" % time.ctime(os.path.getmtime(file)))
print("created: %s" % time.ctime(os.path.getctime(file)))
Your other option is to use os.stat
:
import os, time
(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(file)
print("last modified: %s" % time.ctime(mtime))
Note: ctime()
does not refer to creation time on *nix systems, but rather the last time the inode data changed. (thanks to kojiro for making that fact more clear in the comments by providing a link to an interesting blog post)
This works:
$("#myselect").find('option').removeAttr("selected");
or
$("#myselect").find('option:selected').removeAttr("selected");
try this
<c:forEach items="${list}" var="map">
<tr>
<c:forEach items="${map}" var="entry">
<td>${entry.value}</td>
</c:forEach>
</tr>
</c:forEach>
Latest revision based on comment from BinaryZebra's comment
and tested here. The addition of command eval
allows for the expression to be kept in the present execution environment while the expressions before are only held for the duration of the eval.
Use $IFS that has no spaces\tabs, just newlines/CR
$ IFS=$'\r\n' GLOBIGNORE='*' command eval 'XYZ=($(cat /etc/passwd))'
$ echo "${XYZ[5]}"
sync:x:5:0:sync:/sbin:/bin/sync
Also note that you may be setting the array just fine but reading it wrong - be sure to use both double-quotes ""
and braces {}
as in the example above
Edit:
Please note the many warnings about my answer in comments about possible glob expansion, specifically gniourf-gniourf's comments about my prior attempts to work around
With all those warnings in mind I'm still leaving this answer here (yes, bash 4 has been out for many years but I recall that some macs only 2/3 years old have pre-4 as default shell)
Other notes:
Can also follow drizzt's suggestion below and replace a forked subshell+cat with
$(</etc/passwd)
The other option I sometimes use is just set IFS into XIFS, then restore after. See also Sorpigal's answer which does not need to bother with this
In some extent, You CAN trigger
HTML5 form validation and show hints to user without submitting the form!
Two button, one for validate, one for submit
Set a onclick
listener on the validate button to set a global flag(say justValidate
) to indicate this click is intended to check the validation of the form.
And set a onclick
listener on the submit button to set the justValidate
flag to false.
Then in the onsubmit
handler of the form, you check the flag justValidate
to decide the returning value and invoke the preventDefault()
to stop the form to submit. As you know, the HTML5 form validation(and the GUI hint to user) is preformed before the onsubmit
event, and even if the form is VALID you can stop the form submit by returning false or invoke preventDefault()
.
And, in HTML5 you have a method to check the form's validation: the form.checkValidity()
, then in you can know if the form is validate or not in your code.
OK, here is the demo: http://jsbin.com/buvuku/2/edit
First you need to input the two numbers say num_rows and num_columns perhaps using argc and argv then do a for loop to print the dots.
int j=0;
int k=0;
for (k=0;k<num_columns;k++){
for (j=0;j<num_rows;j++){
printf(".");
}
printf("\n");
}
you'd have to replace the dot with something else later.
You are iterating through an undefined
value, ie, com
property of the Array's object, you should iterate through the array itself:
$.each(obj, function(key,value) {
// here `value` refers to the objects
});
Also note that jQuery intelligently tries to parse the sent JSON, probably you don't need to parse the response. If you are using $.ajax()
, you can set the dataType
to json
which tells jQuery parse the JSON for you.
If it still doesn't work, check the browser's console for troubleshooting.
And you can use %stylesheets% (assetic feature) tag:
{% stylesheets
"@MainBundle/Resources/public/colorbox/colorbox.css"
"%kerner.root_dir%/Resources/css/main.css"
%}
<link type="text/css" rel="stylesheet" media="all" href="{{ asset_url }}" />
{% endstylesheets %}
You can write path to css as parameter (%parameter_name%).
More about this variant: http://symfony.com/doc/current/cookbook/assetic/asset_management.html
The code below will check whether the stored procedure already exists or not.
If it exists it will alter, if it doesn't exist it will create a new stored procedure for you:
//syntax for Create and Alter Proc
DECLARE @Create NVARCHAR(200) = 'Create PROCEDURE sp_cp_test';
DECLARE @Alter NVARCHAR(200) ='Alter PROCEDURE sp_cp_test';
//Actual Procedure
DECLARE @Proc NVARCHAR(200)= ' AS BEGIN select ''sh'' END';
//Checking For Sp
IF EXISTS (SELECT *
FROM sysobjects
WHERE id = Object_id('[dbo].[sp_cp_test]')
AND Objectproperty(id, 'IsProcedure') = 1
AND xtype = 'p'
AND NAME = 'sp_cp_test')
BEGIN
SET @Proc=@Alter + @Proc
EXEC (@proc)
END
ELSE
BEGIN
SET @Proc=@Create + @Proc
EXEC (@proc)
END
go
Convert comma separated String to List
List<String> items = Arrays.asList(str.split("\\s*,\\s*"));
The above code splits the string on a delimiter defined as: zero or more whitespace, a literal comma, zero or more whitespace
which will place the words into the list and collapse any whitespace between the words and commas.
Please note that this returns simply a wrapper on an array: you CANNOT for example .remove()
from the resulting List
. For an actual ArrayList
you must further use new ArrayList<String>
.
Thanks to unutbu for the explanation. By default numpy.cov calculates the sample covariance. To obtain the population covariance you can specify normalisation by the total N samples like this:
Covariance = numpy.cov(a, b, bias=True)[0][1]
print(Covariance)
or like this:
Covariance = numpy.cov(a, b, ddof=0)[0][1]
print(Covariance)
If your div looks like this:
<div id="MyDiv">content in here</div>
Then this Javascript:
document.getElementById("MyDiv").innerHTML = "";
will make it look like this:
<div id="MyDiv"></div>
If adding your routes
inside the web middleware
doesn't work for any reason then try adding this to $middleware
into Kernel.php
protected $middleware = [
//...
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
];
I've been doing it this way:
class Event(list):
"""Event subscription.
A list of callable objects. Calling an instance of this will cause a
call to each item in the list in ascending order by index.
Example Usage:
>>> def f(x):
... print 'f(%s)' % x
>>> def g(x):
... print 'g(%s)' % x
>>> e = Event()
>>> e()
>>> e.append(f)
>>> e(123)
f(123)
>>> e.remove(f)
>>> e()
>>> e += (f, g)
>>> e(10)
f(10)
g(10)
>>> del e[0]
>>> e(2)
g(2)
"""
def __call__(self, *args, **kwargs):
for f in self:
f(*args, **kwargs)
def __repr__(self):
return "Event(%s)" % list.__repr__(self)
However, like with everything else I've seen, there is no auto generated pydoc for this, and no signatures, which really sucks.
You can add parameter columns or use dict
with key which is converted to column name:
np.random.seed(123)
e = np.random.normal(size=10)
dataframe=pd.DataFrame(e, columns=['a'])
print (dataframe)
a
0 -1.085631
1 0.997345
2 0.282978
3 -1.506295
4 -0.578600
5 1.651437
6 -2.426679
7 -0.428913
8 1.265936
9 -0.866740
e_dataframe=pd.DataFrame({'a':e})
print (e_dataframe)
a
0 -1.085631
1 0.997345
2 0.282978
3 -1.506295
4 -0.578600
5 1.651437
6 -2.426679
7 -0.428913
8 1.265936
9 -0.866740
Another option I like, which can be generalized once I start seeing the code not conform to DRY, is to use one controller that redirects to another controller.
public ActionResult ClientIdSearch(int cid)
{
var action = String.Format("Details/{0}", cid);
return RedirectToAction(action, "Accounts");
}
I find this allows me to apply my logic in one location and re-use it without have to sprinkle JavaScript in the views to handle this. And, as I mentioned I can then refactor for re-use as I see this getting abused.
No, you can unpublish but once your application has been live
on the market you cannot delete it. (Each package name is unique and Google remembers all package names anyway so you could use this a reminder)
The "Delete" button only works for unpublished version of your app. Once you published your app or a particular version of it, you cannot delete it from the Market. However, you can still "unpublish" it. The "Delete" button is only handy when you uploaded a new version, then you realized you goofed and want to remove that new version before publishing it.
Update, 2016
you can now filter out unpublished or draft apps from your listing.
Unpublish option can be found in the header area, beside PUBLISHED text.
UPDATE 2020
Due to changes in the new play console, the unpublish option was moved to a different location as follows.
Click All Apps
in the left pane. Then click the app you want to remove.
Then under the Setup
option in the left pane, Click Advanced Settings
.
Then under App Availablity
on the right, change the status to UnPublished
and click Save Changes
at the bottom.
Take a look at the image below:
jQuery.post(post_url,{ content: "John" } )_x000D_
.done(function( data ) {_x000D_
_x000D_
_x000D_
});_x000D_
_x000D_
I used the technique what u have replied above, it works fine but my problem is i need to generate a pdf conent using john as text . I have been able to echo the passed data. but getting empty in when generating pdf uisng below content ples check
ob_start();_x000D_
_x000D_
include_once(JPATH_SITE .'/components/com_gaevents/pdfgenerator.php');_x000D_
$content = ob_get_clean();_x000D_
_x000D_
_x000D_
_x000D_
$test = $_SESSION['content'] ;_x000D_
_x000D_
require_once(JPATH_SITE.'/html2pdf/html2pdf.class.php');_x000D_
$html2pdf = new HTML2PDF('P', 'A4', 'en', true, 'UTF-8',0 ); _x000D_
$html2pdf->setDefaultFont('Arial');_x000D_
$html2pdf->WriteHTML($test);
_x000D_
It's pretty simple. Pay attention and you'll get it right away! :)
You will create a html array, which will be then sent to php array. Your html code will look like this:
<input type="checkbox" name="check_list[1]" alt="Checkbox" value="checked">
<input type="checkbox" name="check_list[2]" alt="Checkbox" value="checked">
<input type="checkbox" name="check_list[3]" alt="Checkbox" value="checked">
Where [1] [2] [3]
are the ID
s of your messages, meaning that you will echo
your $row['Report ID']
in their place.
Then, when you submit the form, your PHP array will look like this:
print_r($check_list)
[1] => checked
[3] => checked
Depending on which were checked and which were not.
I'm sure you can continue from this point forward.
None of the above solution worked for me completely on my mac.
The best solution I found this is to use the utility created here.
https://github.com/michalbe/md-file-tree
Once you have installed the utility npm install md-file-tree -g
then you can simply run to get all files tree
md-file-tree . > README.md
Simple: [boolean](get-variable "Varname" -ErrorAction SilentlyContinue)
like Paul said, use
conda create --prefix=/users/.../yourEnvName python=x.x
if you are located in the folder in which you want to create your virtual environment, just omit the path and use
conda create --prefix=yourEnvName python=x.x
conda only keep track of the environments included in the folder envs inside the anaconda folder. The next time you will need to activate your new env, move to the folder where you created it and activate it with
source activate yourEnvName
SELECT substring(commaSeparatedTags,0,charindex(',',commaSeparatedTags))
will give you the first tag. You can proceed similarly to get the second one and so on by combining substring and charindex one layer deeper each time. That's an immediate solution but it works only with very few tags as the query grows very quickly in size and becomes unreadable. Move on to functions then, as outlined in other, more sophisticated answers to this post.
I like both of the 2 main solutions:
NSArray *array = [NSArray arrayWithArray:mutableArray];
Or
NSArray *array = [mutableArray copy];
The primary difference I see in them is how they behave when mutableArray is nil:
NSMutableArray *mutableArray = nil;
NSArray *array = [NSArray arrayWithArray:mutableArray];
// array == @[] (empty array)
NSMutableArray *mutableArray = nil;
NSArray *array = [mutableArray copy];
// array == nil
TL;DR
mysql_real_escape_string()
will provide no protection whatsoever (and could furthermore munge your data) if:
MySQL's
NO_BACKSLASH_ESCAPES
SQL mode is enabled (which it might be, unless you explicitly select another SQL mode every time you connect); andyour SQL string literals are quoted using double-quote
"
characters.This was filed as bug #72458 and has been fixed in MySQL v5.7.6 (see the section headed "The Saving Grace", below).
In homage to @ircmaxell's excellent answer (really, this is supposed to be flattery and not plagiarism!), I will adopt his format:
Starting off with a demonstration...
mysql_query('SET SQL_MODE="NO_BACKSLASH_ESCAPES"'); // could already be set
$var = mysql_real_escape_string('" OR 1=1 -- ');
mysql_query('SELECT * FROM test WHERE name = "'.$var.'" LIMIT 1');
This will return all records from the test
table. A dissection:
Selecting an SQL Mode
mysql_query('SET SQL_MODE="NO_BACKSLASH_ESCAPES"');
As documented under String Literals:
There are several ways to include quote characters within a string:
A “
'
” inside a string quoted with “'
” may be written as “''
”.A “
"
” inside a string quoted with “"
” may be written as “""
”.Precede the quote character by an escape character (“
\
”).A “
'
” inside a string quoted with “"
” needs no special treatment and need not be doubled or escaped. In the same way, “"
” inside a string quoted with “'
” needs no special treatment.
If the server's SQL mode includes NO_BACKSLASH_ESCAPES
, then the third of these options—which is the usual approach adopted by mysql_real_escape_string()
—is not available: one of the first two options must be used instead. Note that the effect of the fourth bullet is that one must necessarily know the character that will be used to quote the literal in order to avoid munging one's data.
The Payload
" OR 1=1 --
The payload initiates this injection quite literally with the "
character. No particular encoding. No special characters. No weird bytes.
mysql_real_escape_string()
$var = mysql_real_escape_string('" OR 1=1 -- ');
Fortunately, mysql_real_escape_string()
does check the SQL mode and adjust its behaviour accordingly. See libmysql.c
:
ulong STDCALL
mysql_real_escape_string(MYSQL *mysql, char *to,const char *from,
ulong length)
{
if (mysql->server_status & SERVER_STATUS_NO_BACKSLASH_ESCAPES)
return escape_quotes_for_mysql(mysql->charset, to, 0, from, length);
return escape_string_for_mysql(mysql->charset, to, 0, from, length);
}
Thus a different underlying function, escape_quotes_for_mysql()
, is invoked if the NO_BACKSLASH_ESCAPES
SQL mode is in use. As mentioned above, such a function needs to know which character will be used to quote the literal in order to repeat it without causing the other quotation character from being repeated literally.
However, this function arbitrarily assumes that the string will be quoted using the single-quote '
character. See charset.c
:
/*
Escape apostrophes by doubling them up
// [ deletia 839-845 ]
DESCRIPTION
This escapes the contents of a string by doubling up any apostrophes that
it contains. This is used when the NO_BACKSLASH_ESCAPES SQL_MODE is in
effect on the server.
// [ deletia 852-858 ]
*/
size_t escape_quotes_for_mysql(CHARSET_INFO *charset_info,
char *to, size_t to_length,
const char *from, size_t length)
{
// [ deletia 865-892 ]
if (*from == '\'')
{
if (to + 2 > to_end)
{
overflow= TRUE;
break;
}
*to++= '\'';
*to++= '\'';
}
So, it leaves double-quote "
characters untouched (and doubles all single-quote '
characters) irrespective of the actual character that is used to quote the literal! In our case $var
remains exactly the same as the argument that was provided to mysql_real_escape_string()
—it's as though no escaping has taken place at all.
The Query
mysql_query('SELECT * FROM test WHERE name = "'.$var.'" LIMIT 1');
Something of a formality, the rendered query is:
SELECT * FROM test WHERE name = "" OR 1=1 -- " LIMIT 1
As my learned friend put it: congratulations, you just successfully attacked a program using mysql_real_escape_string()
...
mysql_set_charset()
cannot help, as this has nothing to do with character sets; nor can mysqli::real_escape_string()
, since that's just a different wrapper around this same function.
The problem, if not already obvious, is that the call to mysql_real_escape_string()
cannot know with which character the literal will be quoted, as that's left to the developer to decide at a later time. So, in NO_BACKSLASH_ESCAPES
mode, there is literally no way that this function can safely escape every input for use with arbitrary quoting (at least, not without doubling characters that do not require doubling and thus munging your data).
It gets worse. NO_BACKSLASH_ESCAPES
may not be all that uncommon in the wild owing to the necessity of its use for compatibility with standard SQL (e.g. see section 5.3 of the SQL-92 specification, namely the <quote symbol> ::= <quote><quote>
grammar production and lack of any special meaning given to backslash). Furthermore, its use was explicitly recommended as a workaround to the (long since fixed) bug that ircmaxell's post describes. Who knows, some DBAs might even configure it to be on by default as means of discouraging use of incorrect escaping methods like addslashes()
.
Also, the SQL mode of a new connection is set by the server according to its configuration (which a SUPER
user can change at any time); thus, to be certain of the server's behaviour, you must always explicitly specify your desired mode after connecting.
So long as you always explicitly set the SQL mode not to include NO_BACKSLASH_ESCAPES
, or quote MySQL string literals using the single-quote character, this bug cannot rear its ugly head: respectively escape_quotes_for_mysql()
will not be used, or its assumption about which quote characters require repeating will be correct.
For this reason, I recommend that anyone using NO_BACKSLASH_ESCAPES
also enables ANSI_QUOTES
mode, as it will force habitual use of single-quoted string literals. Note that this does not prevent SQL injection in the event that double-quoted literals happen to be used—it merely reduces the likelihood of that happening (because normal, non-malicious queries would fail).
In PDO, both its equivalent function PDO::quote()
and its prepared statement emulator call upon mysql_handle_quoter()
—which does exactly this: it ensures that the escaped literal is quoted in single-quotes, so you can be certain that PDO is always immune from this bug.
As of MySQL v5.7.6, this bug has been fixed. See change log:
Functionality Added or Changed
Incompatible Change: A new C API function,
mysql_real_escape_string_quote()
, has been implemented as a replacement formysql_real_escape_string()
because the latter function can fail to properly encode characters when theNO_BACKSLASH_ESCAPES
SQL mode is enabled. In this case,mysql_real_escape_string()
cannot escape quote characters except by doubling them, and to do this properly, it must know more information about the quoting context than is available.mysql_real_escape_string_quote()
takes an extra argument for specifying the quoting context. For usage details, see mysql_real_escape_string_quote().Note
Applications should be modified to use
mysql_real_escape_string_quote()
, instead ofmysql_real_escape_string()
, which now fails and produces anCR_INSECURE_API_ERR
error ifNO_BACKSLASH_ESCAPES
is enabled.References: See also Bug #19211994.
Taken together with the bug explained by ircmaxell, the following examples are entirely safe (assuming that one is either using MySQL later than 4.1.20, 5.0.22, 5.1.11; or that one is not using a GBK/Big5 connection encoding):
mysql_set_charset($charset);
mysql_query("SET SQL_MODE=''");
$var = mysql_real_escape_string('" OR 1=1 /*');
mysql_query('SELECT * FROM test WHERE name = "'.$var.'" LIMIT 1');
...because we've explicitly selected an SQL mode that doesn't include NO_BACKSLASH_ESCAPES
.
mysql_set_charset($charset);
$var = mysql_real_escape_string("' OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");
...because we're quoting our string literal with single-quotes.
$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(["' OR 1=1 /*"]);
...because PDO prepared statements are immune from this vulnerability (and ircmaxell's too, provided either that you're using PHP=5.3.6 and the character set has been correctly set in the DSN; or that prepared statement emulation has been disabled).
$var = $pdo->quote("' OR 1=1 /*");
$stmt = $pdo->query("SELECT * FROM test WHERE name = $var LIMIT 1");
...because PDO's quote()
function not only escapes the literal, but also quotes it (in single-quote '
characters); note that to avoid ircmaxell's bug in this case, you must be using PHP=5.3.6 and have correctly set the character set in the DSN.
$stmt = $mysqli->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$param = "' OR 1=1 /*";
$stmt->bind_param('s', $param);
$stmt->execute();
...because MySQLi prepared statements are safe.
Thus, if you:
OR
OR
in addition to employing one of the solutions in ircmaxell's summary, use at least one of:
NO_BACKSLASH_ESCAPES
...then you should be completely safe (vulnerabilities outside the scope of string escaping aside).
You can use DDC (Domain Directory Controller). It is a new, easy to use, Java SDK. You don't even need to know LDAP to use it. It exposes an object-oriented API instead.
You can find it here.
I think this is closer to the answer you're looking for:
<input type="file">
$file = $(file);
var filename = fileElement[0].files[0].name;
This code block is enough. Please don't forget to set delegate in viewDidLoad or by storyboard just before to use the following extension:
extension YOUR_VIEW_CONTROLLER: UITextViewDelegate {
func textViewDidBeginEditing (_ textView: UITextView) {
if YOUR_TEXT_VIEW.text.isEmpty || YOUR_TEXT_VIEW.text == "YOUR DEFAULT PLACEHOLDER TEXT HERE" {
YOUR_TEXT_VIEW.text = nil
YOUR_TEXT_VIEW.textColor = .red // YOUR PREFERED COLOR HERE
}
}
func textViewDidEndEditing (_ textView: UITextView) {
if YOUR_TEXT_VIEW.text.isEmpty {
YOUR_TEXT_VIEW.textColor = UIColor.gray // YOUR PREFERED PLACEHOLDER COLOR HERE
YOUR_TEXT_VIEW.text = "YOUR DEFAULT PLACEHOLDER TEXT HERE"
}
}
}
I was using Terminator before, so I found it convenient to re-map Alt + arrow-key to switch between the panes. This can be done in Preferences -> Keys -> Key Mappings - press the '+' button to add a mapping. Also, in my case such a mapping was already defined in Profiles, I simply removed it.
Google Play does not allow you to publish an app signed with your debug keystore. If you try to upload such an APK, Google Play will fail with the message "You uploaded an APK that was signed in debug mode. You need to sign your APK in release mode."
However, if you try to upload an update which is signed with the debug keystore, you will not see this message; Google Play will display the message shown in the question, referring to SHA1 fingerprints.
So firstly, check whether you signed the app with your debug key by mistake.
You can check which certificates the original APK and update APK were signed with by using these commands, using the Java keytool
:
keytool -list -printcert -jarfile original.apk
keytool -list -printcert -jarfile update.apk
This shows you detailed information about the how an APK was signed, for example:
Owner: CN=My App, O=My Company, L=Somewhere, C=DE
Issuer: CN=My App, O=My Company, L=Somewhere, C=DE
Serial number: 4790b086
Valid from: Mon Nov 11 15:01:28 GMT 2013 until: Fri Mar 29 16:01:28 BST 2041
Certificate fingerprints:
MD5: A3:2E:67:AF:74:3A:BD:DD:A2:A9:0D:CA:6C:D4:AF:20
SHA1: A6:E7:CE:64:17:45:0F:B4:C7:FC:76:43:90:04:DC:A7:84:EF:33:E9
SHA256: FB:6C:59:9E:B4:58:E3:62:AD:81:42:...:09:FC:BC:FE:E7:40:53:C3:D8:14:4F
Signature algorithm name: SHA256withRSA
Version: 3
The important parts to note here — for each APK — are the SHA1 fingerprint value, the Owner identity value, and the Valid from/until dates.
If that keytool
command doesn't work (the -jarfile
option requires Java 7), you can get more basic information via the jarsigner
command:
jarsigner -verify -verbose:summary -certs original.apk
jarsigner -verify -verbose:summary -certs update.apk
This unfortunately does not show the SHA1 fingerprint, but does show the X.509 owner identity, along with the certificate expiry dates. For example:
sm 4642892 Thu Apr 17 10:57:44 CEST 2014 classes.dex (and 412 more)
X.509, CN=My App, O=My Company, L=Somewhere, C=DE
[certificate is valid from 11/11/13 12:12 to 29/03/41 12:12]
[CertPath not validated: Path does not chain with any of the trust anchors]
You can ignore any "CertPath not validated" message, along with warnings about certificate chains or timestamps; they're not relevant in this case.
If the Owner/X.509 identity value is CN=Android Debug, O=Android, C=US
, then you have signed the APK with your debug key, not the original release key
If the SHA1 fingerprint value is different between the original and update APKs, then you did not use the same signing key for both APKs
If the Owner/X.509 identity values are different, or the certificate expiry dates differ between the two APKs, then you did not use the same signing key for both APKs
Note that even if the Owner/X.509 values are identical between the two certificates, this doesn't mean that the certificates are identical — if anything else does not match — such as the fingerprint values — then the certificates are different.
If the two APKs have different certificate information, then you must find the original keystore, i.e. the file with the first SHA1 fingerprint value that Google Play (or keytool
) told you.
Search through all the keystore files you can find on your computer, and in any backups you have, until you have the one with the correct SHA1 fingerprint:
keytool -list -keystore my-release.keystore
Just press Enter if prompted for the password — you don't necessarily have to enter it if you just want to quickly check the SHA1 value.
If you cannot find the original keystore, you will never be able to publish any updates to this particular app.
Android mentions this explicitly on the Signing Your Application page:
Warning: Keep your keystore and private key in a safe and secure place, and ensure that you have secure backups of them. If you publish an app to Google Play and then lose the key with which you signed your app, you will not be able to publish any updates to your app, since you must always sign all versions of your app with the same key.
After the first release of an APK, all subsequent releases must be signed with the exact same key.
No. This is not possible. The APK only contains public information, and not your private key information.
No. Even if you do find the original, you can't sign an APK with key A, then sign the next update with both keys A and B, then sign the next update after that with only key B.
Signing an APK (or any JAR file) with multiple keys is technically possible, but Google Play no longer accepts APKs with multiple signatures.
Attempting to do so will result in the message "Your APK has been signed with multiple certificates. Please only sign it with one certificate and upload it again."
You will have to build your app with a new application ID (e.g. change from "com.example.myapp" to "com.example.myapp2") and create a brand new listing on Google Play.
Possibly you will also have to change your code so that people can install the new app even if they have the old app installed, e.g. you need to make sure that you don't have conflicting content providers.
You will lose your existing install base, reviews etc., and will have to find a way to get your existing customers to uninstall the old app and install the new version.
Again, ensure you have secure backups of the keystore and password(s) you use for this version.
Late to the party, but I think it is a useful answer.
flatMap
would be the shortest way to do it.
Stream.of(objects).flatMap(o->(o instanceof Client)?Stream.of((Client)o):Stream.empty())
If o
is a Client
then create a Stream with a single element, otherwise use the empty stream. These streams will then be flattened into a Stream<Client>
.
Try the following:
Unplug the usb and plug it back again.
Go to the Settings -> Applications -> Development of your device and uncheck the USB debugging mode and then check it back again.
Restart the adb on your PC. adb kill-server and then adb start-server
Restart your device and try again.
In addition to the ways already mentioned (dropping the war-file directly into the webapps-directory), if you have the Tomcat Manager -application installed, you can deploy war-files via browser too. To get to the manager, browse to the root of the server (in your case, localhost:8080), select "Tomcat Manager" (at this point, you need to know username and password for a Tomcat-user with "manager"-role, the users are defined in tomcat-users.xml in the conf-directory of the tomcat-installation). From the opening page, scroll downwards until you see the "Deploy"-part of the page, where you can click "browse" to select a WAR file to deploy from your local machine. After you've selected the file, click deploy. After a while the manager should inform you that the application has been deployed (and if everything went well, started).
Here's a longer how-to and other instructions from the Tomcat 7 documentation pages.
I generally prefer, where possible, to use the default value of value types to determine whether they've been set. This obviously isn't possible all the time, especially with ints - but for DateTimes, I think reserving the MinValue to signify that it hasn't been changed is fair enough. The benefit of this over nullables is that there's one less place where you'll get a null reference exception (and probably lots of places where you don't have to check for null before accessing it!)
it should. Typically that's how you do multiple selectors. Otherwise it may not like you trying to assign the return values of three uploads to the same var.
I would suggest using .each
or maybe push the returns to an array rather than assigning them to that value.
You error clearly says, you are trying to use locale something was not there.
>>> locale.setlocale(locale.LC_ALL, 'de_DE')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/locale.py", line 581, in setlocale
return _setlocale(category, locale)
locale.Error: unsupported locale setting
locale.Error: unsupported locale setting
To check available setting, use locale -a
deb@deb-Latitude-E7470:/ambot$ locale -a
C
C.UTF-8
en_AG
en_AG.utf8
en_AU.utf8
en_BW.utf8
en_CA.utf8
en_DK.utf8
en_GB.utf8
en_HK.utf8
en_IE.utf8
en_IN
en_IN.utf8
en_NG
en_NG.utf8
en_NZ.utf8
en_PH.utf8
en_SG.utf8
en_US.utf8
en_ZA.utf8
en_ZM
en_ZM.utf8
en_ZW.utf8
POSIX
so you can use one among,
>>> locale.setlocale(locale.LC_ALL, 'en_AG.utf8')
'en_AG.utf8'
>>>
for de_DE
This file can either be adjusted manually or updated using the tool, update-locale.
update-locale LANG=de_DE.UTF-8
There is no such feature in markdown, however you can always use HTML inside markdown:
<a href="http://example.com/" target="_blank">example</a>
I uninstalled all parts of SQL Server 2012 using Control Panel in Windows and then reinstalled (choosing "All Features"). Now it works!
This is documented in section 3.9.3 of the Spring 3.0 manual:
For a fallback match, the bean name is considered a default qualifier value.
In other words, the default behaviour is as though you'd added @Qualifier("country")
to the setter method.
Add target="_blank"
to the <form>
tag.
$client = new \GuzzleHttp\Client();
$request = $client->post('http://demo.website.com/api', [
'body' => json_encode($dataArray)
]);
$response = $request->getBody();
Add
openssl.cafile
in php.ini
file
A simple function drawing a circle on the middle of your window frame, using a multiplicator percentage
/// CGFloat is a multiplicator from self.view.frame.width
func drawCircle(withMultiplicator coefficient: CGFloat) {
let radius = self.view.frame.width / 2 * coefficient
let circlePath = UIBezierPath(arcCenter: self.view.center, radius: radius, startAngle: CGFloat(0), endAngle:CGFloat(Double.pi * 2), clockwise: true)
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath
//change the fill color
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = UIColor.darkGray.cgColor
shapeLayer.lineWidth = 2.0
view.layer.addSublayer(shapeLayer)
}
This question is a bit old, but here's another way in C++11 of "doing more work" in the constructor before initialising your member variables:
BigMommaClass::BigMommaClass(int numba1, int numba2)
: thingOne([](int n1, int n2){return n1+n2;}(numba1,numba2)),
thingTwo(numba1, numba2) {}
The lambda function above will be invoked and the result passed to thingOnes constructor. You can of course make the lambda as complex as you like.
Javascript tilde (~) coerces a given value to the one's complement--all bits are inverted. That's all tilde does. It's not sign opinionated. It neither adds nor subtracts any quantity.
0 -> 1
1 -> 0
...in every bit position [0...integer nbr of bits - 1]
On standard desktop processors using high-level languages like JavaScript, BASE10 signed arithmetic is the most common, but keep in mind, it's not the only kind. Bits at the CPU level are subject to interpretation based on a number of factors. At the 'code' level, in this case JavaScript, they are interpreted as a 32-bit signed integer by definition (let's leave floats out of this). Think of it as quantum, those 32-bits represent many possible values all at once. It depends entirely on the converting lens you view them through.
JavaScript Tilde operation (1's complement)
BASE2 lens
~0001 -> 1110 - end result of ~ bitwise operation
BASE10 Signed lens (typical JS implementation)
~1 -> -2
BASE10 Unsigned lens
~1 -> 14
All of the above are true at the same time.
I have recently started working on a project using Vue JS, JSON Schema. I am trying to access nested JSON Objects from a JSON Schema file in the Vue app. I tried the below code and now I can load different JSON objects inside different Vue template tags. In the script tag add the below code
import {JsonObject1name, JsonObject2name} from 'your Json file path';
Now you can access JsonObject1,2 names in data section of export default part as below:
data: () => ({
schema: JsonObject1name,
schema1: JsonObject2name,
model: {}
}),
Now you can load the schema, schema1 data inside Vue template according to your requirement. See below code for example :
<SchemaForm id="unique name representing your Json object1" class="form" v-model="model" :schema="schema" :components="components">
</SchemaForm>
<SchemaForm id="unique name representing your Json object2" class="form" v-model="model" :schema="schema1" :components="components">
</SchemaForm>
SchemaForm is the local variable name for @formSchema/native library. I have implemented the data of different JSON objects through forms in different CSS tabs.
I hope this answer helps someone. I can help if there are any questions.
both <button>
tag and <input type="button">
accept a title attribute..
If your branch is local only and hasn't been pushed to the server, use
git rebase master
Otherwise, use
git merge master
A solution using list.index
:
def indices(lst, element):
result = []
offset = -1
while True:
try:
offset = lst.index(element, offset+1)
except ValueError:
return result
result.append(offset)
It's much faster than the list comprehension with enumerate
, for large lists. It is also much slower than the numpy
solution if you already have the array, otherwise the cost of converting outweighs the speed gain (tested on integer lists with 100, 1000 and 10000 elements).
NOTE: A note of caution based on Chris_Rands' comment: this solution is faster than the list comprehension if the results are sufficiently sparse, but if the list has many instances of the element that is being searched (more than ~15% of the list, on a test with a list of 1000 integers), the list comprehension is faster.
It can happen because of native method calling in your application. For example, in Qtjambi if you use QApplication.quit()
instead of QApplication.closeAllWindows()
for closing a Java application it generates an error log.
In this case, you can get a stack trace right to your method that called the native code and caused the crash. Just look in the log file it tells you about:
# An error report file with more information is saved as hs_err_pid24139.log.
The stack trace looks quite unusual, since it has native code mixed with VM code and your code, but each line is prefixed so you can tell which lines are your own code. There's a key at the top of the stack trace to explain the prefixes:
Native frames: (J=compiled Java code, A=aot compiled Java code, j=interpreted, Vv=VM code, C=native code)
have you tried something like this:
if [ $# -eq 0 ] || [ $# -gt 1 ]
then
echo "$#"
fi
.p12
and .pfx
are both PKCS #12 files. Am I missing something?
Have you tried renaming the exported .pfx
file to have a .p12
extension?
For a package manager that can install and manage multiple versions of python, these are good choices:
The advantages to these package managers is that it may be easier to set them up and install multiple versions of python with them than it is to install python from source. They also provide commands for easily changing the available python version(s) using shims and setting the python version per-directory.
This disadvantage is that, by default, they are installed at the user-level (inside your home directory) and require a little bit of user-level configuration - you'll need to edit your ~/.profile
and ~/.bashrc
or similar files. This means that it is not easy to use them to install multiple python versions globally for all users. In order to do this, you can install from source alongside the OS's existing python version.
You'll need root privileges for this method.
See the official python documentation for building from source for additional considerations and options.
/usr/local
is the designated location for a system administrator to install shared (system-wide) software, so it's subdirectories are a good place to download the python source and install. See section 4.9 of the Linux Foundation's File Hierarchy Standard.
Install any build dependencies. On Debian-based systems, use:
apt update
apt install build-essential zlib1g-dev libncurses5-dev libgdbm-dev libnss3-dev libssl-dev libsqlite3-dev libreadline-dev libffi-dev libbz2-dev
Choose which python version you want to install. See the Python Source Releases page for a listing.
Download and unzip file in /usr/local/src
, replacing X.X.X
below with the python version (i.e. 3.8.2
).
cd /usr/local/src
wget https://www.python.org/ftp/python/X.X.X/Python-X.X.X.tgz
tar vzxf Python-X.X.X.tgz
Before building and installing, set the CFLAGS
environment variable with C compiler flags necessary (see GNU's make
documentation). This is usually not necessary for general use, but if, for example, you were going to create a uWSGI plugin with this python version, you might want to set the flags, -fPIC
, with the following:
export CFLAGS='-fPIC'
Change the working directory to the unzipped python source directory, and configure the build. You'll probably want to use the --enable-optimizations
option on the ./configure
command for profile guided optimization. Use --prefix=/usr/local
to install to the proper subdirectories (/usr/local/bin
, /usr/local/lib
, etc.).
cd Python-X.X.X
./configure --enable-optimizations --prefix=/usr/local
Build the project with make
and install with make altinstall
to avoid overriding any files when installing multiple versions. See the warning on this page of the python build documentation.
make -j 4
make altinstall
Then you should be able to run your new python and pip versions with pythonX.X
and pipX.X
(i.e python3.8
and pip3.8
). Note that if the minor version of your new installation is the same as the OS's version (for example if you were installing python3.8.4 and the OS used python3.8.2), then you would need to specify the entire path (/usr/local/bin/pythonX.X
) or set an alias to use this version.
Run:
ls -l /usr/local/bin/python*
The first row in this example shows the python3 symlink. To set it as the default python symlink run the following:
ln -s -f /usr/local/bin/python3 /usr/local/bin/python
then reload your shell.
If this is your app, if you connect the device to your computer, you can use the "Devices" option on Xcode's "Window" menu and then download the app's data container to your computer. Just select your app from the list of installed apps, and click on the "gear" icon and choose "Download Container".
Once you've downloaded it, right click on the file in the Finder and choose "Show Package Contents".
Using Following Code You Solve thisQuestion.... If you run a file using localhost server than this problem solve by following Jsp Page Code.This Code put Between Head Tag in jsp file
<style type="text/css">
<%@include file="css/style.css" %>
</style>
<script type="text/javascript">
<%@include file="js/script.js" %>
</script>
I do not have experience with version 7 of JBoss but with 5 I often had issues when redeploying apps which went away when I cleaned the work and tmp folder. I wrote a script for that which was executed everytime the server shut down. Maybe executing it before startup is better considering abnormal shutdowns (which weren't uncommon with Jboss 5 :))
String time = "12:32:22";
String[] values = time.split(":");
This will take your time and split it where it sees a colon and put the value in an array, so you should have 3 values after this.
Then loop through string array and convert each one. (with Integer.parseInt
)
For JDBC based project (directly or indirectly, e.g. JPA, EJB, ...) you can mockup not the entire database (in such case it would be better to use a test db on a real RDBMS), but only mockup at JDBC level.
Advantage is abstraction which comes with that way, as JDBC data (result set, update count, warning, ...) are the same whatever is the backend: your prod db, a test db, or just some mockup data provided for each test case.
With JDBC connection mocked up for each case there is no need to manage test db (cleanup, only one test at time, reload fixtures, ...). Every mockup connection is isolated and there is no need to clean up. Only minimal required fixtures are provided in each test case to mock up JDBC exchange, which help to avoid complexity of managing a whole test db.
Acolyte is my framework which includes a JDBC driver and utility for this kind of mockup: http://acolyte.eu.org .
I've come across this "deep object copy" function that I've found handy for duplicating objects by value. It doesn't use jQuery, but it certainly is deep.
http://www.overset.com/2007/07/11/javascript-recursive-object-copy-deep-object-copy-pass-by-value/
new
operator (thus invoking a constructor)clazz.newInstance()
(which again invokes the constructor). Or by clazz.getConstructor(..).newInstance(..)
(again using a constructor, but you can thus choose which one)To summarize the answer - one main way - by invoking the constructor of the object's class.
Update: Another answer listed two ways that do not involve using a constructor - deseralization and cloning.
I know this is an old thread, however I noticed that no one mentioned the underline option, which can remove the underlines under the column headings.
set pagesize 50000--50k is the max as of 12c
set linesize 10000
set trimspool on --remove trailing blankspaces
set underline off --remove the dashes/underlines under the col headers
set colsep ~
select * from DW_TMC_PROJECT_VW;
Most likely both tables have a column with the same name. Alias each table, and call each column with the table alias.
Working on a project I was stuck for some time on this concept - I ended up with a similar answer to Method 1 by @GSerg that worked great. Essentially I defined two formula ranges (using a few variables) and then used the Union concept. My example is from a larger project that I'm working on but hopefully the portion of code below can help some other people who might not know how to use the Union concept in conjunction with defined ranges and variables. I didn't include the entire code because at this point it's fairly long - if anyone wants more insight feel free to let me know.
First I declared all my variables as Public
Then I defined/set each variable
Lastly I set a new variable "SelectRanges" as the Union between the two other FormulaRanges
Public r As Long
Public c As Long
Public d As Long
Public FormulaRange3 As Range
Public FormulaRange4 As Range
Public SelectRanges As Range
With Sheet8
c = pvt.DataBodyRange.Columns.Count + 1
d = 3
r = .Cells(.Rows.Count, 1).End(xlUp).Row
Set FormulaRange3 = .Range(.Cells(d, c + 2), .Cells(r - 1, c + 2))
FormulaRange3.NumberFormat = "0"
Set FormulaRange4 = .Range(.Cells(d, c + c + 2), .Cells(r - 1, c + c + 2))
FormulaRange4.NumberFormat = "0"
Set SelectRanges = Union(FormulaRange3, FormulaRange4)
File \conf\tomcat-users.xml
, before this line
</tomcat-users>
add these lines
<role rolename="manager-gui"/>
<role rolename="manager-script"/>
<role rolename="manager-jmx"/>
<role rolename="manager-status"/>
<user username="admin" password="admin" roles="manager-gui,manager-script,manager-jmx,manager-status"/>
var singleText = "single";
var s = window.location.search;
if (s.indexOf(singleText) == -1) {
window.location.href += (s.substring(0,1) == "?") ? "&" : "?" + singleText;
}
You can use apache commons IO..
FileInputStream fisTargetFile = new FileInputStream(new File("test.txt"));
String targetFileStr = IOUtils.toString(fisTargetFile, "UTF-8");
Prior to bash 4 there is no good way to use associative arrays in bash. Your best bet is to use an interpreted language that actually has support for such things, like awk. On the other hand, bash 4 does support them.
As for less good ways in bash 3, here is a reference than might help: http://mywiki.wooledge.org/BashFAQ/006
I'd suggest pulling from the remote branch as often as possible in order to minimise large merges and possible conflicts.
Having said that, I would go with the first option:
git add foo.js
git commit foo.js -m "commit"
git pull
git push
Commit your changes before pulling so that your commits are merged with the remote changes during the pull. This may result in conflicts which you can begin to deal with knowing that your code is already committed should anything go wrong and you have to abort the merge for whatever reason.
I'm sure someone will disagree with me though, I don't think there's any correct way to do this merge flow, only what works best for people.
I confirm that git and msysgit can coexist on the same computer, as mentioned in "Which GIT version to use cygwin or msysGit or both?".
Git for Windows (msysgit) will run in its own shell (dos with git-cmd.bat
or bash with Git Bash.vbs
)
Update 2016: msysgit is obsolete, and the new Git for Windows now uses msys2
Git on Cygwin, after installing its package, will run in its own cygwin bash shell.
In there, you can do a sudo apt-get install git-core
and start using git on project-sources present either on the WSL container's "native" file-system (see below), or in the hosting Windows's file-system through the /mnt/c/...
, /mnt/d/...
directory hierarchies.
Specifically for the Bash on Windows or WSL (Windows Subsystem for Linux):
DrvFs
emulated file-system may not behave the same as files on the native VolFs
file-system).
- Unfortunately, it cannot invoke back into Windows executables, or
- interact with any native drivers (i.e. so no Graphic card, no USB drives yet).
There is a setting in the IE options that controls whether it should open new links in an existing window or in a new window. I'm not sure if you can control it from the command line but maybe changing this option would be enough for you.
In IE7 it looks like the option is "Reuse windows for launching shortcuts (when tabbed browsing is disabled)".
If your XSLT processor supports EXSLT, you can use str:tokenize, otherwise, the link contains an implementation using functions like substring-before.
Both yes and no:
Yes, you can use the same old KVO APIs in Swift to observe Objective-C objects.
You can also observe dynamic
properties of Swift objects inheriting from NSObject
.
But... No it's not strongly typed as you could expect Swift native observation system to be.
Using Swift with Cocoa and Objective-C | Key Value Observing
No, currently there is no builtin value observation system for arbitrary Swift objects.
Yes, there are builtin Property Observers, which are strongly typed.
But... No they are not KVO, since they allow only for observing of objects own properties, don't support nested observations ("key paths"), and you have to explicitly implement them.
The Swift Programming Language | Property Observers
Yes, you can implement explicit value observing, which will be strongly typed, and allow for adding multiple handlers from other objects, and even support nesting / "key paths".
But... No it will not be KVO since it will only work for properties which you implement as observable.
You can find a library for implementing such value observing here:
Observable-Swift - KVO for Swift - Value Observing and Events
I don't see any margin
or margin-left
declarations for #footer-wrap li
.
This ought to do the trick:
#footer-wrap ul,
#footer-wrap li {
margin-left: 0;
list-style-type: none;
}
Try this setup:
a = [["a","b","c",],["d","e"],["f","g","h"]]
To print the 2nd element in the 1st list ("b"), use print a[0][1]
- For the 2nd element in 3rd list ("g"): print a[2][1]
The first brackets reference which nested list you're accessing, the second pair references the item in that list.
Let assume you have have a file filedata.txt
with content:
d:\stuff\morestuff\furtherdown\THEFILE.txt
d:\otherstuff\something\otherfile.txt
You can read and split the file paths:
>>> for i in open("filedata.txt").readlines():
... print i.strip().split("\\")
...
['d:', 'stuff', 'morestuff', 'furtherdown', 'THEFILE.txt']
['d:', 'otherstuff', 'something', 'otherfile.txt']
I had the same issue after upgrading from Fedora Server 24 (PHP 5) to 25 (PHP 7). After investigation, I found that /etc/php.d/
had two different .ini
files loading extension=geoip.so
.
Previous version of distros had this file named 50-geoip.ini
but the recent was changed to 40-geoip.ini
, and I suspect that in the version-upgrade process the old hasn't been removed, while the new one has been created.
That was the actual case of the issue. After removing stray 50-geoip.ini
from /etc/php.d/
and restarting httpd
it just worked flawlessly.
From Increase MySQL connection limit:-
MySQL’s default configuration sets the maximum simultaneous connections to 100. If you need to increase it, you can do it fairly easily:
For MySQL 3.x:
# vi /etc/my.cnf
set-variable = max_connections = 250
For MySQL 4.x and 5.x:
# vi /etc/my.cnf
max_connections = 250
Restart MySQL once you’ve made the changes and verify with:
echo "show variables like 'max_connections';" | mysql
EDIT:-(From comments)
The maximum concurrent connection can be maximum range: 4,294,967,295. Check MYSQL docs
For me, this error was because I had some of my data titles were two names, I merged them in one name and all went well.
I get consistent behaviour for both instances:
>>> ls[0:10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ls[10:-1]
[10, 11, 12, 13, 14, 15, 16, 17, 18]
Note, though, that tenth element of the list is at index 9, since the list is 0-indexed. That might be where your hang-up is.
In other words, [0:10]
doesn't go from index 0-10, it effectively goes from 0 to the tenth element (which gets you indexes 0-9, since the 10 is not inclusive at the end of the slice).
Environment variables (that you modify using the System Properties) are only propagated to subshells when you create a new subshell.
If you had a command line prompt (DOS or cygwin) open when you changed the User env vars, then they won't show up.
You need to open a new command line prompt after you change the user settings.
The equivalent in Unix/Linux is adding a line to your .bash_rc: you need to start a new shell to get the values.
Here is a good article from Microsoft http://www.iis.net/learn/troubleshoot/security-issues/troubleshooting-forms-authentication that covers various cases and scenarios.
I used this solution to get realtime output on a subprocess. This loop will stop as soon as the process completes leaving out a need for a break statement or possible infinite loop.
sub_process = subprocess.Popen(my_command, close_fds=True, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while sub_process.poll() is None:
out = sub_process.stdout.read(1)
sys.stdout.write(out)
sys.stdout.flush()
It seems to be a browser bug.
10690: Reported a bug in Firefox for responsive images (those with max-width: 100%) in table cells. No other browsers are affected. See
.img-responsive
in <fieldset>
have the same behaviour.
Raw t-sql is limited to CHARINDEX(), PATINDEX(), REPLACE(), and SUBSTRING() for string manipulation. But with sql server 2005 and later you can set up user defined functions that run in .Net, which means setting up a string.format() UDF shouldn't be too tough.
If your looking how to copy an Amazon AWS .pem
keypair into a different
region do the following:
openssl rsa -in .ssh/amazon-aws.pem -pubout > .ssh/amazon-aws.pub
Then
aws ec2 import-key-pair --key-name amazon-aws --public-key-material '$(cat .ssh/amazon-aws.pub)' --region us-west-2
You can use
new File("relative/path").getAbsoluteFile()
after
System.setProperty("user.dir", "/some/directory")
System.setProperty("user.dir", "C:/OtherProject");
File file = new File("data/data.csv").getAbsoluteFile();
System.out.println(file.getPath());
Will print
C:\OtherProject\data\data.csv
Although, some users already answered this question already, I am giving an example of application settings to solve this problem.
I had the same issue. I am using https://github.com/grevory/angular-local-storage module in my angularjs application. If you configure your app as follows, it will save variable in session storage instead of local storage. Therefore, if you close the browser or close the tab, session storage will be removed automatically. You do not need to do anything.
app.config(function (localStorageServiceProvider) {
localStorageServiceProvider
.setPrefix('myApp')
.setStorageType('sessionStorage')
});
Hope it will help.
After following the steps from @Johnride, I still got the same error.
This fixed the problem:
Tools-> Options-> Select no proxy
The default value for a GUID is empty. (eg: 00000000-0000-0000-0000-000000000000)
This can be invoked using Guid.Empty
or new Guid()
If you want a new GUID, you use Guid.NewGuid()
[ngStyle] with condition based if and else case.
<label for="file" [ngStyle]="isPreview ? {'cursor': 'default'} : {'cursor': 'pointer'}">Attachment
Unfortunately, this is not a trivial thing to solve for the general case. The easiest thing would be to add a css-style property "float: right;" to your 200px div, however, this would also cause your "main"-div to actually be full width and any text in there would float around the edge of the 200px-div, which often looks weird, depending on the content (pretty much in all cases except if it's a floating image).
EDIT: As suggested by Dom, the wrapping problem could of course be solved with a margin. Silly me.
Take a look on life cycle of Activity
Where
***onCreate()***
Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one. Always followed by onStart().
***onStart()***
Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.
And you can write your simple class to take a look when these methods call
public class TestActivity extends Activity {
/** Called when the activity is first created. */
private final static String TAG = "TestActivity";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i(TAG, "On Create .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onDestroy()
*/
@Override
protected void onDestroy() {
super.onDestroy();
Log.i(TAG, "On Destroy .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onPause()
*/
@Override
protected void onPause() {
super.onPause();
Log.i(TAG, "On Pause .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onRestart()
*/
@Override
protected void onRestart() {
super.onRestart();
Log.i(TAG, "On Restart .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onResume()
*/
@Override
protected void onResume() {
super.onResume();
Log.i(TAG, "On Resume .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onStart()
*/
@Override
protected void onStart() {
super.onStart();
Log.i(TAG, "On Start .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onStop()
*/
@Override
protected void onStop() {
super.onStop();
Log.i(TAG, "On Stop .....");
}
}
Hope this will clear your confusion.
And take a look here for details.
Lifecycle Methods in Details is a very good example and demo application, which is a very good article to understand the life cycle.
Is there any way you could programatically apply a class to the object?
<object class="hasparams">
then do
object.hasparams
string[] result = new string[table.Columns.Count];
DataRow dr = table.Rows[0];
for (int i = 0; i < dr.ItemArray.Length; i++)
{
result[i] = dr[i].ToString();
}
foreach (string str in result)
Console.WriteLine(str);
you can install it dirctly via
$ npm install --save react react-dom
$ npm install --save react-bootstrap
then import what you really need from the bootstrap like :
import Button from 'react-bootstrap/lib/Button';
// or
import Button from 'react-bootstrap';
and also you can install :
npm install --save reactstrap@next react react-dom
check this out click here .
and for the CSS you can read this link also carfuly
Recently, I have faced this issue. And fixed it by changing CPU/ABI from Intel Atom (x86) to ARM(armeabi-v7a).
Job done.
Minted, whether from GitHub or CTAN, the Comprehensive TeX Archive Network, works in Overleaf, TeX Live and MiKTeX.
It requires the installation of the Python package Pygments; this is explained in the documentation in either source above. Although Pygments brands itself as a Python syntax highlighter, Minted guarantees the coverage of hundreds of other languages.
Example:
\documentclass{article}
\usepackage{minted}
\begin{document}
\begin{minted}[mathescape, linenos]{python}
# Note: $\pi=\lim_{n\to\infty}\frac{P_n}{d}$
title = "Hello World"
sum = 0
for i in range(10):
sum += i
\end{minted}
\end{document}
Output:
l = [1, 2, 3, 4, 5]
del l[0:3] # Here 3 specifies the number of items to be deleted.
This is the code if you want to delete a number of items from the list. You might as well skip the zero before the colon. It does not have that importance. This might do as well.
l = [1, 2, 3, 4, 5]
del l[:3] # Here 3 specifies the number of items to be deleted.
Using an enhanced for would be even nicer:
int sum = 0;
for (int d : data) sum += d;
Another thing that will probably give you a big surprise is the wrong result that you will obtain from
double average = sum / data.length;
Reason: on the right-hand side you have integer division and Java will not automatically promote it to floating-point division. It will calculate the integer quotient of sum/data.length
and only then promote that integer to a double
. A solution would be
double average = 1.0d * sum / data.length;
This will force the dividend into a double
, which will automatically propagate to the divisor.
I think this syntax has not been mentionned yet (in the case you want a method without arguments) :
class Clazz {
static <T> T doIt() {
// shake that booty
}
}
And the call :
String str = Clazz.<String>doIt();
Hope this help someone.
Looks like phpmyadmin's username and password are stored elsewhere ( probably in a custom-defined config file ) in WAMP or there is some additional hashing or ... involved in the process.
So to change currently used default 'config'-file-based password you can browse "<host>/phpmyadmin/user_password.php
" using your browser. You'll be prompted to enter your mysql credentials and then you can use the displayed form to change the stored password for the user you logged into previously.
with leading zero for day and month
var pattern =/^(0[1-9]|1[0-9]|2[0-9]|3[0-1])\/(0[1-9]|1[0-2])\/([0-9]{4})$/;
and with both leading zero/without leading zero for day and month
var pattern =/^(0?[1-9]|1[0-9]|2[0-9]|3[0-1])\/(0?[1-9]|1[0-2])\/([0-9]{4})$/;
Linux Android Studio 0.8.6:
rm -R ~/.AndroidStudioBeta/config/
Linux Android Studio 1.0.0:
rm -R ~/.AndroidStudio/config/
awk '!seen[$0]++' file.txt
seen
is an associative-array that Awk will pass every line of the file to. If a line isn't in the array then seen[$0]
will evaluate to false. The !
is the logical NOT operator and will invert the false to true. Awk will print the lines where the expression evaluates to true. The ++
increments seen
so that seen[$0] == 1
after the first time a line is found and then seen[$0] == 2
, and so on.
Awk evaluates everything but 0
and ""
(empty string) to true. If a duplicate line is placed in seen
then !seen[$0]
will evaluate to false and the line will not be written to the output.
I assume this is *nix?
Use "here document":
sqlplus -s user/pass <<+EOF
select 1 from dual;
+EOF
EDIT: I should have tried your second example. It works, too (even in Windows, sans ticks):
$ echo 'select 1 from dual;'|sqlplus -s user/pw
1
----------
1
$
Using pip2 worked for me:
!pip2 install geocoder
...
import geocoder
g = geocoder.google('Mountain View, CA')
g.latlng
[37.3860517, -122.0838511]
In the PHP file first you need to register the session
<? session_start();
$_SESSION['id'] = $userData['user_id'];?>
And in each page of your php application you can retrive the session id
<? session_start()
id = $_SESSION['id'];
?>
I will soon released a new version of my app to support to galaxy ace.
You can download here: https://play.google.com/store/apps/details?id=droid.pr.coolflashlightfree
In order to solve your problem you should do this:
this._camera = Camera.open();
this._camera.startPreview();
this._camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});
Parameters params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
this._camera.setParameters(params);
params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
this._camera.setParameters(params);
don't worry about FLASH_MODE_OFF because this will keep the light on, strange but it's true
to turn off the led just release the camera
Here is example with only CSS for that. In example I'm using SASS and SLIM.
https://codepen.io/Darex1991/pen/zBxPxe
Slim:
a.btn.btn--joined-state
span joined
span leave
SASS:
=animate($property...)
@each $vendor in ('-webkit-', '')
#{$vendor}transition-property: $property
#{$vendor}transition-duration: .3s
#{$vendor}transition-timing-function: ease-in
=visible
+animate(opacity, max-height, visibility)
max-height: 150px
opacity: 1
visibility: visible
=invisible
+animate(opacity, max-height, visibility)
max-height: 0
opacity: 0
visibility: hidden
=transform($var)
@each $vendor in ('-webkit-', '-ms-', '')
#{$vendor}transform: $var
.btn
border: 1px solid blue
&--joined-state
position: relative
span
+animate(opacity)
span:last-of-type
+invisible
+transform(translateX(-50%))
position: absolute
left: 50%
&:hover
span:first-of-type
+invisible
span:last-of-type
+visible
border-color: blue
For disabling all the database related autoconfiguration and exit from:
Cannot determine embedded database driver class for database type NONE
1. Using annotation:
@SpringBootApplication
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class Application {
public static void main(String[] args) {
SpringApplication.run(PayPalApplication.class, args);
}
}
2. Using Application.properties:
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration
For several cases, or even just a few cases involving a lot of criteria, consider using a switch.
switch( true ){
case ( !empty($youtube) && !empty($link) ):{
// Nothing is empty...
break;
}
case ( !empty($youtube) && empty($link) ):{
// One is empty...
break;
}
case ( empty($youtube) && !empty($link) ):{
// The other is empty...
break;
}
case ( empty($youtube) && empty($link) ):{
// Everything is empty
break;
}
default:{
// Even if you don't expect ever to use it, it's a good idea to ALWAYS have a default.
// That way if you change it, or miss a case, you have some default handler.
break;
}
}
If you have multiple cases that require the same action, you can stack them and omit the break; to flowthrough. Just maybe put a comment like /*Flowing through*/ so you're explicit about doing it on purpose.
Note that the { } around the cases aren't required, but they are nice for readability and code folding.
More about switch: http://php.net/manual/en/control-structures.switch.php
if you are using the fedora distro, you can change the file
/etc/containers/registries.conf
Adding domain docker.io
The WebRequest object seems like too much work for me. I prefer to use the WebClient control.
To use this function you just need to create two NameValueCollections holding your parameters and request headers.
Consider the following function:
private static string DoGET(string URL,NameValueCollection QueryStringParameters = null, NameValueCollection RequestHeaders = null)
{
string ResponseText = null;
using (WebClient client = new WebClient())
{
try
{
if (RequestHeaders != null)
{
if (RequestHeaders.Count > 0)
{
foreach (string header in RequestHeaders.AllKeys)
client.Headers.Add(header, RequestHeaders[header]);
}
}
if (QueryStringParameters != null)
{
if (QueryStringParameters.Count > 0)
{
foreach (string parm in QueryStringParameters.AllKeys)
client.QueryString.Add(parm, QueryStringParameters[parm]);
}
}
byte[] ResponseBytes = client.DownloadData(URL);
ResponseText = Encoding.UTF8.GetString(ResponseBytes);
}
catch (WebException exception)
{
if (exception.Response != null)
{
var responseStream = exception.Response.GetResponseStream();
if (responseStream != null)
{
using (var reader = new StreamReader(responseStream))
{
Response.Write(reader.ReadToEnd());
}
}
}
}
}
return ResponseText;
}
Add your querystring parameters (if required) as a NameValueCollection like so.
NameValueCollection QueryStringParameters = new NameValueCollection();
QueryStringParameters.Add("id", "123");
QueryStringParameters.Add("category", "A");
Add your http headers (if required) as a NameValueCollection like so.
NameValueCollection RequestHttpHeaders = new NameValueCollection();
RequestHttpHeaders.Add("Authorization", "Basic bGF3c2912XBANzg5ITppc2ltCzEF");
Basically you can create a regex to fulfil your needs and then assign that pattern to your input field.
Or for a more direct approach:
<input type="number" require ng-pattern="<your regex here>">
More info @ angular docs here and here (built-in validators)
You can't. CSS does not support "events". Dare I ask what you need it for? Check out this post here on SO. I can't think of a reason why you would want to hook up an event to a style change. I'm assuming here that the style change is triggered somwhere else by a piece of javascript. Why not add extra logic there?
As mentioned above if you wish to as a new element your queried collection you can use:
$items = DB::select(DB::raw('SELECT * FROM items WHERE items.id = '.$id.' ;'));
foreach($items as $item){
$product = DB::select(DB::raw(' select * from product
where product_id = '. $id.';' ));
$items->push($product);
// or
// $items->put('products', $product);
}
but if you wish to add new element to each queried element you need to do like:
$items = DB::select(DB::raw('SELECT * FROM items WHERE items.id = '.$id.' ;'));
foreach($items as $item){
$product = DB::select(DB::raw(' select * from product
where product_id = '. $id.';' ));
$item->add_whatever_element_you_want = $product;
}
add_whatever_element_you_want
can be whatever you wish that your element is named (like product for example).
I have a generous amount of data that's stored in my repo as individual JSON fragments. There's about 75,000 files sitting under a few directories and it's not really detrimental to performance.
Checking them in the first time was, obviously, a little slow.
I am just wondering why to use some libraries for JWT token decoding and verification at all.
Encoded JWT token can be created using following pseudocode
var headers = base64URLencode(myHeaders);
var claims = base64URLencode(myClaims);
var payload = header + "." + claims;
var signature = base64URLencode(HMACSHA256(payload, secret));
var encodedJWT = payload + "." + signature;
It is very easy to do without any specific library. Using following code:
using System;
using System.Text;
using System.Security.Cryptography;
public class Program
{
// More info: https://stormpath.com/blog/jwt-the-right-way/
public static void Main()
{
var header = "{\"typ\":\"JWT\",\"alg\":\"HS256\"}";
var claims = "{\"sub\":\"1047986\",\"email\":\"[email protected]\",\"given_name\":\"John\",\"family_name\":\"Doe\",\"primarysid\":\"b521a2af99bfdc65e04010ac1d046ff5\",\"iss\":\"http://example.com\",\"aud\":\"myapp\",\"exp\":1460555281,\"nbf\":1457963281}";
var b64header = Convert.ToBase64String(Encoding.UTF8.GetBytes(header))
.Replace('+', '-')
.Replace('/', '_')
.Replace("=", "");
var b64claims = Convert.ToBase64String(Encoding.UTF8.GetBytes(claims))
.Replace('+', '-')
.Replace('/', '_')
.Replace("=", "");
var payload = b64header + "." + b64claims;
Console.WriteLine("JWT without sig: " + payload);
byte[] key = Convert.FromBase64String("mPorwQB8kMDNQeeYO35KOrMMFn6rFVmbIohBphJPnp4=");
byte[] message = Encoding.UTF8.GetBytes(payload);
string sig = Convert.ToBase64String(HashHMAC(key, message))
.Replace('+', '-')
.Replace('/', '_')
.Replace("=", "");
Console.WriteLine("JWT with signature: " + payload + "." + sig);
}
private static byte[] HashHMAC(byte[] key, byte[] message)
{
var hash = new HMACSHA256(key);
return hash.ComputeHash(message);
}
}
The token decoding is reversed version of the code above.To verify the signature you will need to the same and compare signature part with calculated signature.
UPDATE: For those how are struggling how to do base64 urlsafe encoding/decoding please see another SO question, and also wiki and RFCs
Another solution is by using .animate() and appropriate CSS.
e.g.
$('#mydiv').animate({ marginLeft: "100%"} , 4000);
You can make a category of UIView and add this in .h file of category
@property (nonatomic) IBInspectable UIColor *borderColor;
@property (nonatomic) IBInspectable CGFloat borderWidth;
@property (nonatomic) IBInspectable CGFloat cornerRadius;
Now add this in .m file
@dynamic borderColor,borderWidth,cornerRadius;
and this as well in . m file
-(void)setBorderColor:(UIColor *)borderColor{
[self.layer setBorderColor:borderColor.CGColor];
}
-(void)setBorderWidth:(CGFloat)borderWidth{
[self.layer setBorderWidth:borderWidth];
}
-(void)setCornerRadius:(CGFloat)cornerRadius{
[self.layer setCornerRadius:cornerRadius];
}
now you will see this in your storyboard for all UIView subclasses (UILabel, UITextField, UIImageView etc)
Thats it.. No Need to import category anywhere, just add the category's files in the project and see these properties in the storyboard.
Better solution is to introduce another interface for async operations. New interface must inherit from original interface.
Example:
interface IIO
{
void DoOperation();
}
interface IIOAsync : IIO
{
Task DoOperationAsync();
}
class ClsAsync : IIOAsync
{
public void DoOperation()
{
DoOperationAsync().GetAwaiter().GetResult();
}
public async Task DoOperationAsync()
{
//just an async code demo
await Task.Delay(1000);
}
}
class Program
{
static void Main(string[] args)
{
IIOAsync asAsync = new ClsAsync();
IIO asSync = asAsync;
Console.WriteLine(DateTime.Now.Second);
asAsync.DoOperation();
Console.WriteLine("After call to sync func using Async iface: {0}",
DateTime.Now.Second);
asAsync.DoOperationAsync().GetAwaiter().GetResult();
Console.WriteLine("After call to async func using Async iface: {0}",
DateTime.Now.Second);
asSync.DoOperation();
Console.WriteLine("After call to sync func using Sync iface: {0}",
DateTime.Now.Second);
Console.ReadKey(true);
}
}
P.S. Redesign your async operations so they return Task instead of void, unless you really must return void.
Style the td
and th
instead
td, th {
border: 1px solid black;
}
And also to make it so there is no spacing between cells use:
table {
border-collapse: collapse;
}
(also note, you have border-style: none;
which should be border-style: solid;
)
See an example here: http://jsfiddle.net/KbjNr/
When you export your project as a 'Runnable jar' (Right mouse on project -> Export -> Runnable jar) you have the option to package all dependencies into the generated jar. It also has two other ways (see screenshot) to export your libraries, be aware of the licences when deciding which packaging method you will use.
The 'launch configuration' dropdown is populated with classes containing a main(String[])
method. The selected class is started when you 'run' the jar.
Exporting as a runnable jar uses the dependencies on your build path (Right mouse on project -> Build Path -> Configure Build Path...). When you export as a 'regular' (non-runnable) jar you can select any file in your project(s). If you have the libraries in your project folder you can include them but external dependencies, for example maven, cannot be included (for maven projects, search here).
Just use the -H
parameter several times:
curl -H "Accept-Charset: utf-8" -H "Content-Type: application/x-www-form-urlencoded" http://www.some-domain.com
Check the type
property. Would that suffice?
Once had this issue, thought it reasonable to share how I resolved it;
I think the way to do that in php is to use the header function as:
header ("Location: exampleFile.php");
You could just enclose that header file in an if statement so that it redirects only when a certain condition is met, as in:
if (isset($_POST['submit'])){ header("Location: exampleFile.php") }
Hope that helps.
My problem was kind of the same at first and then a little different in the sense that when /java
folder showed up, it was deep down in a nested folder somewhere in src/main/resources/java
.
Initallially the problem was being in the Package Explorer
and not in the Project Explorer
as many people have talked about. So,
Project Explorer
However, the main problem was I missed to notice a checkbox at the second step of Maven Project Creation
from the wizard. That got me created a complicated structure and not a clean direct one.
Once I marked it checked
I got a clean project structure as what asked.
<application
android:icon="@drawable/YOUR_ICON" <!-- THIS ICON(IMAGE) WILL BE SHOWN IN YOUR APPS -->
android:label="MY APP NAME " > <!-- HERE LABEL(APP NAME) -->
<activity
android:name=".application's starting activity" <!-- (.)dot means current dir, if your activity is in another package then give full package name ex: com.xxx.Activity -->
android:label="LABEL FOR ACTIVITY "
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Assign the enddate to some date variable because AddDays
method returns new Datetime as the result..
Datetime somedate=endDate.AddDays(2);
It is absolutely possible to install side-by-side several JRE/JDK versions. Moreover, you don't have to do anything special for that to happen, as Sun is creating a different folder for each (under Program Files).
There is no control panel to check which JRE works for each application. Basically, the JRE that will work would be the first in your PATH environment variable. You can change that, or the JAVA_HOME variable, or create specific cmd/bat files to launch the applications you desire, each with a different JRE in path.
You could try:
List<string> a = new List<string>();
List<string> b = new List<string>();
a.AddRange(b);
This preserves the order of the lists, but it doesn't remove any duplicates which Union
would do.
This does change list a
. If you wanted to preserve the original lists then you should use Concat
(as pointed out in the other answers):
var newList = a.Concat(b);
This returns an IEnumerable
as long as a
is not null.
There is Q
objects that allow to complex lookups. Example:
from django.db.models import Q
Item.objects.filter(Q(creator=owner) | Q(moderated=False))
the best way to give a hint is placeholder like this:
<input.... placeholder="hint".../>
SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
// or SimpleDateFormat sdf = new SimpleDateFormat( "MM/dd/yyyy KK:mm:ss a Z" );
sdf.setTimeZone( TimeZone.getTimeZone( "UTC" ) );
System.out.println( sdf.format( new Date() ) );
I'm not very advanced in AngularJS, but my solution would be to use a simple JS class for you cart (in the sense of coffee script) that extend Array.
The beauty of AngularJS is that you can pass you "model" object with ng-click like shown below.
I don't understand the advantage of using a factory, as I find it less pretty that a CoffeeScript class.
My solution could be transformed in a Service, for reusable purpose. But otherwise I don't see any advantage of using tools like factory or service.
class Basket extends Array
constructor: ->
add: (item) ->
@push(item)
remove: (item) ->
index = @indexOf(item)
@.splice(index, 1)
contains: (item) ->
@indexOf(item) isnt -1
indexOf: (item) ->
indexOf = -1
@.forEach (stored_item, index) ->
if (item.id is stored_item.id)
indexOf = index
return indexOf
Then you initialize this in your controller and create a function for that action:
$scope.basket = new Basket()
$scope.addItemToBasket = (item) ->
$scope.basket.add(item)
Finally you set up a ng-click to an anchor, here you pass your object (retreived from the database as JSON object) to the function:
li ng-repeat="item in items"
a href="#" ng-click="addItemToBasket(item)"
Give an id for the select object like this:
<select id="mySelect" name="val" size="1" >
<option value="A">Apple</option>
<option value="C">Cars</option>
<option value="H">Honda</option>
<option value="F">Fiat</option>
<option value="I">Indigo</option>
</select>
You can do it in pure JavaScript:
var selectobject = document.getElementById("mySelect");
for (var i=0; i<selectobject.length; i++) {
if (selectobject.options[i].value == 'A')
selectobject.remove(i);
}
But - as the other answers suggest - it's a lot easier to use jQuery or some other JS library.
<object width="100" height="100">
<param name="movie" value="file.swf">
<embed src="file.swf" width="100" height="100">
</embed>
</object>
All the answer above are good.... except they DOES NOT support all the unicode characters! at ECMA Script (Javascript)
If you are a Node users, you might want the the modified version of accepted answer that support all unicode characters :
/(?<=((?<=[\s,.:;"']|^)["']))(?:(?=(\\?))\2.)*?(?=\1)/gmu
Try here.
Caller-Saved (AKA volatile or call-clobbered) Registers
Callee-Saved (AKA non-volatile or call-preserved) Registers
A compiler specific difference between anonymous namespaces and static functions can be seen compiling the following code.
#include <iostream>
namespace
{
void unreferenced()
{
std::cout << "Unreferenced";
}
void referenced()
{
std::cout << "Referenced";
}
}
static void static_unreferenced()
{
std::cout << "Unreferenced";
}
static void static_referenced()
{
std::cout << "Referenced";
}
int main()
{
referenced();
static_referenced();
return 0;
}
Compiling this code with VS 2017 (specifying the level 4 warning flag /W4 to enable warning C4505: unreferenced local function has been removed) and gcc 4.9 with the -Wunused-function or -Wall flag shows that VS 2017 will only produce a warning for the unused static function. gcc 4.9 and higher, as well as clang 3.3 and higher, will produce warnings for the unreferenced function in the namespace and also a warning for the unused static function.
Try this
<input id ="btn" type="button" value="click" onclick="pay();cls()"/>
If you happen to use Poco libraries you can do:
#include <Poco/Path.h>
...
std::string fileExt = Poco::Path("/home/user/myFile.abc").getExtension(); // == "abc"
$res = mysql_query("SELECT table_name FROM information_schema.tables WHERE table_schema = '$databasename' AND table_name = '$tablename';");
If no records are returned then it doesn't exist.