According to the flask.Request.args documents.
flask.Request.args
A MultiDict with the parsed contents of the query string. (The part in the URL after the question mark).
So the args.get()
is method get()
for MultiDict, whose prototype is as follows:
get(key, default=None, type=None)
Update:
In newer version of flask (v1.0.x and v1.1.x), flask.Request.args
is an ImmutableMultiDict
(an immutable MultiDict
), so the prototype and specific method above is still valid.
5 years later on and .NET Core 3.1 allows you to do specify the media type like this:
[HttpPost]
[Consumes("multipart/form-data")]
public IActionResult UploadLogo()
{
return Ok();
}
I've just faced the same issue and I came to believe that the other answers are a bit more complicated than they need to be, so here's my approach for those who don't want to rely on more libraries or decorators:
A CORS request actually consists of two HTTP requests. A preflight request and then an actual request that is only made if the preflight passes successfully.
Before the actual cross domain POST
request, the browser will issue an OPTIONS
request. This response should not return any body, but only some reassuring headers telling the browser that it's alright to do this cross-domain request and it's not part of some cross site scripting attack.
I wrote a Python function to build this response using the make_response
function from the flask
module.
def _build_cors_prelight_response():
response = make_response()
response.headers.add("Access-Control-Allow-Origin", "*")
response.headers.add("Access-Control-Allow-Headers", "*")
response.headers.add("Access-Control-Allow-Methods", "*")
return response
This response is a wildcard one that works for all requests. If you want the additional security gained by CORS, you have to provide a whitelist of origins, headers and methods.
This response will convince your (Chrome) browser to go ahead and do the actual request.
When serving the actual request you have to add one CORS header - otherwise the browser won't return the response to the invoking JavaScript code. Instead the request will fail on the client-side. Example with jsonify
response = jsonify({"order_id": 123, "status": "shipped"}
response.headers.add("Access-Control-Allow-Origin", "*")
return response
I also wrote a function for that.
def _corsify_actual_response(response):
response.headers.add("Access-Control-Allow-Origin", "*")
return response
allowing you to return a one-liner.
from flask import Flask, request, jsonify, make_response
from models import OrderModel
flask_app = Flask(__name__)
@flask_app.route("/api/orders", methods=["POST", "OPTIONS"])
def api_create_order():
if request.method == "OPTIONS": # CORS preflight
return _build_cors_prelight_response()
elif request.method == "POST": # The actual request following the preflight
order = OrderModel.create(...) # Whatever.
return _corsify_actual_response(jsonify(order.to_dict()))
else
raise RuntimeError("Weird - don't know how to handle method {}".format(request.method))
def _build_cors_prelight_response():
response = make_response()
response.headers.add("Access-Control-Allow-Origin", "*")
response.headers.add('Access-Control-Allow-Headers', "*")
response.headers.add('Access-Control-Allow-Methods', "*")
return response
def _corsify_actual_response(response):
response.headers.add("Access-Control-Allow-Origin", "*")
return response
The following does not return a response:
You must return anything like return afunction()
or return 'a string'
.
This can solve the issue
It's really simple. Let me divide this process into two simple steps.
<form method="POST">
<input type="text" name="user_name"></input>
<input type="text" name="password"></input>
</form>
from flask import request
@app.route('/my-route', methods=['POST'])
# you should always parse username and
# password in a POST method not GET
def my_route():
username = request.form.get("user_name")
print(username)
password = request.form.get("password")
print(password)
#now manipulate the username and password variables as you wish
#Tip: define another method instead of methods=['GET','POST'], if you want to
# render the same template with a GET request too
To download file on flask call. File name is Examples.pdf When I am hitting 127.0.0.1:5000/download it should get download.
Example:
from flask import Flask
from flask import send_file
app = Flask(__name__)
@app.route('/download')
def downloadFile ():
#For windows you need to use drive name [ex: F:/Example.pdf]
path = "/Examples.pdf"
return send_file(path, as_attachment=True)
if __name__ == '__main__':
app.run(port=5000,debug=True)
I also had similar problem where redirects were giving 404 or 405 randomly on my development server. It was an issue with gunicorn instances.
Turns out that I had not properly shut down the gunicorn instance before starting a new one for testing.
Somehow both of the processes were running simultaneously, listening to the same port 8080 and interfering with each other.
Strangely enough they continued running in background after I had killed all my terminals.
Had to kill them manually using fuser -k 8080/tcp
This code will list out all the form variables that are being sent in a POST. This way you can see if you have the proper names of the post values.
string[] keys = Request.Form.AllKeys;
for (int i= 0; i < keys.Length; i++)
{
Response.Write(keys[i] + ": " + Request.Form[keys[i]] + "<br>");
}
The value is null, you have to check why... (in addition to the implementation of the solutions proposed here)
Check the hardware Connections.
Try with
Server.Encode
and
Server.HtmlDecode
while sending and receiving.
Request.Form is a NameValueCollection. In NameValueCollection you can find the GetAllValues() method.
By the way the LINQ method also works.
I've used this in the past, since we typically use razor syntax for coding
@using (Html.BeginForm("actionName", "controllerName", FormMethod.Post, new { target = "_blank" }))
{
// add hidden and form filed here
}
You sure can.
The easiest way to see how you might do this is to browse to the aspx page you want to post to. Then save the source of that page as HTML. Change the action of the form on your new html page to point back to the aspx page you originally copied it from.
Add value tags to your form fields and put the data you want in there, then open the page and hit the submit button.
Here is my complete solution for dynamic String values with case check.
/**
* Makes a portion of String formatted in BOLD.
*
* @param completeString String from which a portion needs to be extracted and formatted.<br> eg. I am BOLD.
* @param targetStringToFormat Target String value to format. <br>eg. BOLD
* @param matchCase Match by target character case or not. If true, BOLD != bold
* @return A string with a portion formatted in BOLD. <br> I am <b>BOLD</b>.
*/
public static SpannableStringBuilder formatAStringPortionInBold(String completeString, String targetStringToFormat, boolean matchCase) {
//Null complete string return empty
if (TextUtils.isEmpty(completeString)) {
return new SpannableStringBuilder("");
}
SpannableStringBuilder str = new SpannableStringBuilder(completeString);
int start_index = 0;
//if matchCase is true, match exact string
if (matchCase) {
if (TextUtils.isEmpty(targetStringToFormat) || !completeString.contains(targetStringToFormat)) {
return str;
}
start_index = str.toString().indexOf(targetStringToFormat);
} else {
//else find in lower cases
if (TextUtils.isEmpty(targetStringToFormat) || !completeString.toLowerCase().contains(targetStringToFormat.toLowerCase())) {
return str;
}
start_index = str.toString().toLowerCase().indexOf(targetStringToFormat.toLowerCase());
}
int end_index = start_index + targetStringToFormat.length();
str.setSpan(new StyleSpan(BOLD), start_index, end_index, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return str;
}
Eg. completeString = "I am BOLD"
CASE I
if *targetStringToFormat* = "bold"
and *matchCase* = true
returns "I am BOLD" (since bold != BOLD)
CASE II
if *targetStringToFormat* = "bold"
and *matchCase* = false
returns "I am BOLD"
To Apply:
myTextView.setText(formatAStringPortionInBold("I am BOLD", "bold", false))
Hope that helps!
I use pip freeze
to get the packages I need into a requirements.txt
file and add that to my repository. I tried to think of a way of why you would want to store the entire virtualenv, but I could not.
Also you can try this, if you want to focus on same text after error.
If you wants to show this error message in a paragraph then you can use this one:
$(document).ready(function () {
$("#submit").click(function () {
if($('#selBooks').val() === '') {
$("#Paragraph_id").text("Please select a book and then proceed.").show();
$('#selBooks').focus();
return false;
}
});
});
Your code looks fine, but there are a couple of things to be aware of:
Post::find($id);
acts upon the primary key, if you have set your primary key in your model to something other than id
by doing:
protected $primaryKey = 'slug';
then find
will search by that key instead.
Laravel also expects the id
to be an integer, if you are using something other than an integer (such as a string) you need to set the incrementing property on your model to false:
public $incrementing = false;
You should avoid setting LD_LIBRARY_PATH
in your .bashrc
. See "Why LD_LIBRARY_PATH is bad
" for more information.
Use the linker option -rpath while linking so that the dynamic linker knows where to find libsync.so
during runtime.
gcc ... -Wl,-rpath /path/to/library -L/path/to/library -lsync -o sync_test
Another way would be to use a wrapper like this
#!/bin/bash
LD_LIBRARY_PATH=/path/to/library sync_test "$@"
If sync_test
starts any other programs, they might end up using the libs in /path/to/library
which may or may not be intended.
I couldn't get this answer to work with unbinding (despite the update see here), but was able to figure out a way around it. The answer was to create a 'destroy_proxy' special event that triggered a 'destroyed' event. You put the event listener on both 'destroyed_proxy' and 'destroyed', then when you want to unbind, you just unbind the 'destroyed' event:
var count = 1;
(function ($) {
$.event.special.destroyed_proxy = {
remove: function (o) {
$(this).trigger('destroyed');
}
}
})(jQuery)
$('.remove').on('click', function () {
$(this).parent().remove();
});
$('li').on('destroyed_proxy destroyed', function () {
console.log('Element removed');
if (count > 2) {
$('li').off('destroyed');
console.log('unbinded');
}
count++;
});
Here is a fiddle
Although this question is already answered (tl;dr: yes, an empty href
value is valid), none of the existing answers references the relevant specifications.
An empty string can’t be a URI. However, the href
attribute doesn’t only take URIs as value, but also URI references. An empty string may be a URI reference.
HTML 4.01 uses RFC 2396, where it says in section 4.2. Same-document References (bold emphasis mine):
A URI reference that does not contain a URI is a reference to the current document. In other words, an empty URI reference within a document is interpreted as a reference to the start of that document, and a reference containing only a fragment identifier is a reference to the identified fragment of that document.
RFC 2396 is obsoleted by RFC 3986 (which is currently IETF’s URI standard), which essentially says the same.
HTML5 uses (valid URL potentially surrounded by spaces ? valid URL) W3C’s URL spec, which has been discontinued. WHATWG’s URL Standard should be used instead (see the last section).
HTML 5.1 uses (valid URL potentially surrounded by spaces ? valid URL) WHATWG’s URL Standard (see the next section).
WHATWG’s HTML uses (valid URL potentially surrounded by spaces) the definition of valid URL string from WHATWG’s URL Standard, where it says that it can be a relative-URL-with-fragment string, which must at least be a relative-URL string, which can be a path-relative-scheme-less-URL string, which is a path-relative-URL string that doesn’t start with a scheme string followed by :
, and its definition says (bold emphasis mine):
A path-relative-URL string must be zero or more URL-path-segment strings, separated from each other by U+002F (/), and not start with U+002F (/).
select *
from
(
( select * from TableInSchema1
minus
select * from TableInSchema2)
union all
( select * from TableInSchema2
minus
select * from TableInSchema1)
)
should do the trick if you want to solve this with a query
You just have to reset the values you don't want to their defaults. No need to get into a mess by using !important
.
#zoomTarget .slikezamenjanje img {
max-height: auto;
padding-right: 0px;
}
I think the key datum you are missing is that CSS comes with default values. If you want to override a value, set it back to its default, which you can look up.
For example, all CSS height
and width
attributes default to auto
.
Yes the culprit is definitely word-wrapping. When I tested your two programs, NetBeans IDE 8.2 gave me the following result.
Looking at your code closely you have used a line break at the end of first loop. But you didn't use any line break in second loop. So you are going to print a word with 1000 characters in the second loop. That causes a word-wrapping problem. If we use a non-word character " " after B, it takes only 5.35 seconds to compile the program. And If we use a line break in the second loop after passing 100 values or 50 values, it takes only 8.56 seconds and 7.05 seconds respectively.
Random r = new Random();
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 1000; j++) {
if(r.nextInt(4) == 0) {
System.out.print("O");
} else {
System.out.print("B");
}
if(j%100==0){ //Adding a line break in second loop
System.out.println();
}
}
System.out.println("");
}
Another advice is that to change settings of NetBeans IDE. First of all, go to NetBeans Tools and click Options. After that click Editor and go to Formatting tab. Then select Anywhere in Line Wrap Option. It will take almost 6.24% less time to compile the program.
In your MySQL workbench, you can go to the left sidebar, under Management select "Users and Privileges", click root under User Accounts, the in the right section click tab "Account Limits" to increase the max queries, updates, etc, and then click tab "Administrative Roles" and check the boxes to give the account access. Hope that helps!
For the datatype Double
to int
, you can use the following:
Double double = 5.00;
int integer = double.intValue();
Use the constructor of string which accepts a char[]
char[] c = ...;
string s = new string(c);
Try to do something like this:
<!--Include jQuery-->
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function doSomething() {
$.get("somepage.php");
return false;
}
</script>
<a href="#" onclick="doSomething();">Click Me!</a>
Note: Not supported in all browsers.
I was looking for a way to download a file using jquery without having to set the file url in the href attribute from the beginning.
jQuery('<a/>', {_x000D_
id: 'downloadFile',_x000D_
href: 'http://cdn.sstatic.net/Sites/stackoverflow/img/[email protected]',_x000D_
style: 'display:hidden;',_x000D_
download: ''_x000D_
}).appendTo('body');_x000D_
_x000D_
$("#downloadFile")[0].click();
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
These are mine, based on pure SVG and CSS animations. Don't pay attention to JS code in the snippet bellow, it's just for demoing purposes. Feel free to make your custom ones basing on mine, it's super easy.
var svg = d3.select("svg"),_x000D_
columnsCount = 3;_x000D_
_x000D_
['basic', 'basic2', 'basic3', 'basic4', 'loading', 'loading2', 'spin', 'chrome', 'chrome2', 'flower', 'flower2', 'backstreet_boys'].forEach(function(animation, i){_x000D_
var x = (i%columnsCount+1) * 200-100,_x000D_
y = 20 + (Math.floor(i/columnsCount) * 200);_x000D_
_x000D_
_x000D_
svg.append("text")_x000D_
.attr('text-anchor', 'middle')_x000D_
.attr("x", x)_x000D_
.attr("y", y)_x000D_
.text((i+1)+". "+animation);_x000D_
_x000D_
svg.append("circle")_x000D_
.attr("class", animation)_x000D_
.attr("cx", x)_x000D_
.attr("cy", y+40)_x000D_
.attr("r", 16)_x000D_
});
_x000D_
circle {_x000D_
fill: none;_x000D_
stroke: #bbb;_x000D_
stroke-width: 4_x000D_
}_x000D_
_x000D_
.basic {_x000D_
animation: basic 0.5s linear infinite;_x000D_
stroke-dasharray: 20 80;_x000D_
}_x000D_
_x000D_
@keyframes basic {_x000D_
0% {stroke-dashoffset: 100;}_x000D_
100% {stroke-dashoffset: 0;}_x000D_
}_x000D_
_x000D_
.basic2 {_x000D_
animation: basic2 0.5s linear infinite;_x000D_
stroke-dasharray: 80 20;_x000D_
}_x000D_
_x000D_
@keyframes basic2 {_x000D_
0% {stroke-dashoffset: 100;}_x000D_
100% {stroke-dashoffset: 0;}_x000D_
}_x000D_
_x000D_
.basic3 {_x000D_
animation: basic3 0.5s linear infinite;_x000D_
stroke-dasharray: 20 30;_x000D_
}_x000D_
_x000D_
@keyframes basic3 {_x000D_
0% {stroke-dashoffset: 100;}_x000D_
100% {stroke-dashoffset: 0;}_x000D_
}_x000D_
_x000D_
.basic4 {_x000D_
animation: basic4 0.5s linear infinite;_x000D_
stroke-dasharray: 10 23.3;_x000D_
}_x000D_
_x000D_
@keyframes basic4 {_x000D_
0% {stroke-dashoffset: 100;}_x000D_
100% {stroke-dashoffset: 0;}_x000D_
}_x000D_
_x000D_
.loading {_x000D_
animation: loading 1s linear infinite;_x000D_
stroke-dashoffset: 25;_x000D_
}_x000D_
_x000D_
@keyframes loading {_x000D_
0% {stroke-dashoffset: 0; stroke-dasharray: 50 0; }_x000D_
50% {stroke-dashoffset: -100; stroke-dasharray: 0 50;}_x000D_
100% { stroke-dashoffset: -200;stroke-dasharray: 50 0;}_x000D_
}_x000D_
_x000D_
.loading2 {_x000D_
animation: loading2 1s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes loading2 {_x000D_
0% {stroke-dasharray: 5 28.3; stroke-dashoffset: 75;}_x000D_
50% {stroke-dasharray: 45 5; stroke-dashoffset: -50;}_x000D_
100% {stroke-dasharray: 5 28.3; stroke-dashoffset: -125; }_x000D_
}_x000D_
_x000D_
.spin {_x000D_
animation: spin 1s linear infinite;_x000D_
stroke-dashoffset: 25;_x000D_
}_x000D_
_x000D_
@keyframes spin {_x000D_
0% {stroke-dashoffset: 0; stroke-dasharray: 33.3 0; }_x000D_
50% {stroke-dashoffset: -100; stroke-dasharray: 0 33.3;}_x000D_
100% { stroke-dashoffset: -200;stroke-dasharray: 33.3 0;}_x000D_
}_x000D_
_x000D_
.chrome {_x000D_
animation: chrome 2s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes chrome {_x000D_
0% {stroke-dasharray: 0 100; stroke-dashoffset: 25;}_x000D_
25% {stroke-dasharray: 75 25; stroke-dashoffset: 0;}_x000D_
50% {stroke-dasharray: 0 100; stroke-dashoffset: -125;}_x000D_
75% {stroke-dasharray: 75 25; stroke-dashoffset: -150;}_x000D_
100% {stroke-dasharray: 0 100; stroke-dashoffset: -275;}_x000D_
}_x000D_
_x000D_
.chrome2 {_x000D_
animation: chrome2 1s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes chrome2 {_x000D_
0% {stroke-dasharray: 0 100; stroke-dashoffset: 25;}_x000D_
25% {stroke-dasharray: 50 50; stroke-dashoffset: 0;}_x000D_
50% {stroke-dasharray: 0 100; stroke-dashoffset: -50;}_x000D_
75% {stroke-dasharray: 50 50; stroke-dashoffset: -125;}_x000D_
100% {stroke-dasharray: 0 100; stroke-dashoffset: -175;}_x000D_
}_x000D_
_x000D_
.flower {_x000D_
animation: flower 1s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes flower {_x000D_
0% {stroke-dasharray: 0 20; stroke-dashoffset: 25;}_x000D_
50% {stroke-dasharray: 20 0; stroke-dashoffset: -50;}_x000D_
100% {stroke-dasharray: 0 20; stroke-dashoffset: -125;}_x000D_
}_x000D_
_x000D_
.flower2 {_x000D_
animation: flower2 1s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes flower2 {_x000D_
0% {stroke-dasharray: 5 20; stroke-dashoffset: 25;}_x000D_
50% {stroke-dasharray: 20 5; stroke-dashoffset: -50;}_x000D_
100% {stroke-dasharray: 5 20; stroke-dashoffset: -125;}_x000D_
}_x000D_
_x000D_
.backstreet_boys {_x000D_
animation: backstreet_boys 3s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes backstreet_boys {_x000D_
0% {stroke-dasharray: 5 28.3; stroke-dashoffset: -225;}_x000D_
15% {stroke-dasharray: 5 28.3; stroke-dashoffset: -300;}_x000D_
30% {stroke-dasharray: 5 20; stroke-dashoffset: -300;}_x000D_
45% {stroke-dasharray: 5 20; stroke-dashoffset: -375;}_x000D_
60% {stroke-dasharray: 5 15; stroke-dashoffset: -375;}_x000D_
75% {stroke-dasharray: 5 15; stroke-dashoffset: -450;}_x000D_
90% {stroke-dasharray: 5 15; stroke-dashoffset: -525;}_x000D_
100% {stroke-dasharray: 5 28.3; stroke-dashoffset: -925;}_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>_x000D_
<svg width="600px" height="700px"></svg>
_x000D_
Also available on CodePen: https://codepen.io/anon/pen/PeRazr
Not sure the key combination that gets you there to the > prompt but it is not a bash prompt that I know. I usually get it by accident. Ctrl+C (or D) gets me back to the $ prompt.
Actually the minimum amount of Angular to be used (as requested in the original question) is just adding a class to the DOM element when show
variable is true, and perform the animation/transition via CSS.
So your minimum Angular code is this:
<div class="box-opener" (click)="show = !show">
Open/close the box
</div>
<div class="box" [class.opened]="show">
<!-- Content -->
</div>
With this solution, you need to create CSS rules for the transition, something like this:
.box {
background-color: #FFCC55;
max-height: 0px;
overflow-y: hidden;
transition: ease-in-out 400ms max-height;
}
.box.opened {
max-height: 500px;
transition: ease-in-out 600ms max-height;
}
If you have retro-browser-compatibility issues, just remember to add the vendor prefixes in the transition
s.
See the example here
When you pass a pointer by a non-const
reference, you are telling the compiler that you are going to modify that pointer's value. Your code does not do that, but the compiler thinks that it does, or plans to do it in the future.
To fix this error, either declare x
constant
// This tells the compiler that you are not planning to modify the pointer
// passed by reference
void test(float * const &x){
*x = 1000;
}
or make a variable to which you assign a pointer to nKByte
before calling test
:
float nKByte = 100.0;
// If "test()" decides to modify `x`, the modification will be reflected in nKBytePtr
float *nKBytePtr = &nKByte;
test(nKBytePtr);
My case is the page is sending multiple requests with different parameters when it was open. So most are being "stalled". Following requests immediately sent gets "stalled". Avoiding unnecessary requests would be better (to be lazy...).
I got the same error, This is what i did to solve the issue.
Before Indentation:
Indentation Error: expected an indented block.
After Indentation:
Working fine. After TAB space.
That is exactly what you do with an advanced filter. If it's a one shot, you don't even need a macro, it is available in the Data menu.
Sheets("Sheet1").Range("A1:D17").AdvancedFilter Action:=xlFilterCopy, _
CriteriaRange:=Sheets("Sheet1").Range("G1:G2"), CopyToRange:=Range("A1:D1") _
, Unique:=False
The following solution worked well for me in various environments:
sourceDir="some/directory"
targetDir="any/other/directory"
find "$sourceDir" -type d | sed -e "s?$sourceDir?$targetDir?" | xargs mkdir -p
This will give you the count per month for 2012;
SELECT MONTH(ARR_DATE) MONTH, COUNT(*) COUNT
FROM table_emp
WHERE YEAR(arr_date)=2012
GROUP BY MONTH(ARR_DATE);
Demo here.
Another solution is you could use a background image to mimic the look of a left border
You might need to tweak for IE (as per usual) but it's worth a shot if that's the design you are going for.
import sys
print(sys.argv[0])
This will print foo.py
for python foo.py
, dir/foo.py
for python dir/foo.py
, etc. It's the first argument to python
. (Note that after py2exe it would be foo.exe
.)
Although this is almost certainly not the OPs issue, you can also get Unable to establish SSL connection
from wget
if you're behind a proxy and don't have HTTP_PROXY
and HTTPS_PROXY
environment variables set correctly. Make sure to set HTTP_PROXY
and HTTPS_PROXY
to point to your proxy.
This is a common situation if you work for a large corporation.
Stephen Darlington makes a very good point, and you can see that if you change my benchmark to use a more realistically sized table if I fill the table out to 10000 rows using the following:
begin
for i in 2 .. 10000 loop
insert into t (NEEDED_FIELD, cond) values (i, 10);
end loop;
end;
Then re-run the benchmarks. (I had to reduce the loop counts to 5000 to get reasonable times).
declare
otherVar number;
cnt number;
begin
for i in 1 .. 5000 loop
select count(*) into cnt from t where cond = 0;
if (cnt = 1) then
select NEEDED_FIELD INTO otherVar from t where cond = 0;
else
otherVar := 0;
end if;
end loop;
end;
/
PL/SQL procedure successfully completed.
Elapsed: 00:00:04.34
declare
otherVar number;
begin
for i in 1 .. 5000 loop
begin
select NEEDED_FIELD INTO otherVar from t where cond = 0;
exception
when no_data_found then
otherVar := 0;
end;
end loop;
end;
/
PL/SQL procedure successfully completed.
Elapsed: 00:00:02.10
The method with the exception is now more than twice as fast. So, for almost all cases,the method:
SELECT NEEDED_FIELD INTO var WHERE condition;
EXCEPTION
WHEN NO_DATA_FOUND....
is the way to go. It will give correct results and is generally the fastest.
this seems to work on our site, using your ideas and a little math based upon the left edge of wrapper div. It seems redundant to go left 50% then take out 50% extra margin, but it seems to work.
div.ImgWrapper {
width: 160px;
height: 160px
overflow: hidden;
text-align: center;
}
img.CropCenter {
left: 50%;
margin-left: -100%;
position: relative;
width: auto !important;
height: 160px !important;
}
<div class="ImgWrapper">
<a href="#"><img class="CropCenter" src="img.png"></a>
</div>
Scenario 1: Occurrence of a word in a sentence.
eg: str1 = "This is an example and is easy"
. The occurrence of the word "is". lets str2 = "is"
count = str1.count(str2)
Scenario 2 : Occurrence of pattern in a sentence.
string = "ABCDCDC"
substring = "CDC"
def count_substring(string,sub_string):
len1 = len(string)
len2 = len(sub_string)
j =0
counter = 0
while(j < len1):
if(string[j] == sub_string[0]):
if(string[j:j+len2] == sub_string):
counter += 1
j += 1
return counter
Thanks!
dd
in command mode (after pressing escape) will cut the line, p
in command mode will paste.
Update:
For a bonus, d
and then a movement will cut the equivalent of that movement, so dw
will cut a word, d<down-arrow>
will cut this line and the line below, d50w
will cut 50 words.
yy
is copy line, and works like dd
.
D
cuts from cursor to end of line.
If you've used v
(visual mode), you should try V
(visual line mode) and <ctrl>v
(visual block mode).
It works for me:
<script type="text/javascript">
$(function () {
var dateNow = new Date();
$('#calendario').datetimepicker({
locale: 'es',
format: 'DD/MM/YYYY',
defaultDate:moment(dateNow).hours(0).minutes(0).seconds(0).milliseconds(0)
});
});
</script>
You can loop through the Selection object to see what was selected. Here is a code snippet from Microsoft (http://msdn.microsoft.com/en-us/library/aa203726(office.11).aspx):
Sub Count_Selection()
Dim cell As Object
Dim count As Integer
count = 0
For Each cell In Selection
count = count + 1
Next cell
MsgBox count & " item(s) selected"
End Sub
The accepted answer offers a solution which requires changing of the underlying data frame. This is not necessary. One can also simply factorise within the aes()
call directly or create a vector for that instead.
This is certainly not much different than user Drew Steen's answer, but with the important difference of not changing the original data frame.
level_order <- c('virginica', 'versicolor', 'setosa') #this vector might be useful for other plots/analyses
ggplot(iris, aes(x = factor(Species, level = level_order), y = Petal.Width)) + geom_col()
or
level_order <- factor(iris$Species, level = c('virginica', 'versicolor', 'setosa'))
ggplot(iris, aes(x = level_order, y = Petal.Width)) + geom_col()
or
directly in the aes()
call without a pre-created vector:
ggplot(iris, aes(x = factor(Species, level = c('virginica', 'versicolor', 'setosa')), y = Petal.Width)) + geom_col()
In the future one would use left: unset;
for unsetting the value of left.
As of today 4 nov 2014 unset
is only supported in Firefox.
My guess is we'll be able to use it around year 2022 when IE 11 is properly phased out.
Try to use:
onClick="$('.error').remove();"
on Clear button.
Use
border-collapse:collapse
as Nathan wrote and you need to set
td { border-bottom: 1px solid #000; }
At first, you must specify your path, the path that your *.csv
files are in there
path = 'f:\project\dataset'
You can change it based on your system.
then,
use dir
function :
files = dir (strcat(path,'\*.csv'))
L = length (files);
for i=1:L
image{i}=csvread(strcat(path,'\',file(i).name));
% process the image in here
end
pwd
also can be used.
Use the below code. For me it is working
jQuery("[id$='hfSpecialty_ids']").focus()
To do this, you can loop through one and append to the other:
<?php
$test1 = array(
'11' => '11',
'22' => '22',
'33' => '33',
'44' => '44'
);
$test2 = array(
'44' => '44',
'55' => '55',
'66' => '66',
'77' => '77'
);
function combineWithKeys($array1, $array2)
{
foreach($array1 as $key=>$value) $array2[$key] = $value;
asort($array2);
return $array2;
}
print_r(combineWithKeys($test1, $test2));
?>
UPDATE: KingCrunch came up with the best solution: print_r($array1+$array2);
I did create a symbol link (c:\android-sdk) in windows 10 and resolved:
mklink /D "c:\android-sdk" "C:\Users\Clézio\android-sdk"
A simple and very usefull example, is....
Imagine:
you have a uint32_t array[2]
and want to access the 3rd and 4th Byte of the Byte chain.
you could do *((uint16_t*) &array[1])
.
But this sadly breaks the strict aliasing rules!
But known compilers allow you to do the following :
union un
{
uint16_t array16[4];
uint32_t array32[2];
}
technically this is still a violation of the rules. but all known standards support this usage.
Here's the accepted answer implementation ported to Java in case anyone needs it.
package com.project529.garage.util;
/**
* Mean radius.
*/
private static double EARTH_RADIUS = 6371;
/**
* Returns the distance between two sets of latitudes and longitudes in meters.
* <p/>
* Based from the following JavaScript SO answer:
* http://stackoverflow.com/questions/27928/calculate-distance-between-two-latitude-longitude-points-haversine-formula,
* which is based on https://en.wikipedia.org/wiki/Haversine_formula (error rate: ~0.55%).
*/
public double getDistanceBetween(double lat1, double lon1, double lat2, double lon2) {
double dLat = toRadians(lat2 - lat1);
double dLon = toRadians(lon2 - lon1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(toRadians(lat1)) * Math.cos(toRadians(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double d = EARTH_RADIUS * c;
return d;
}
public double toRadians(double degrees) {
return degrees * (Math.PI / 180);
}
Building on and and enhancing the answer by @piro , you can build a contextmanager. This allows for very readable code which will disable the alaram signal after a successful run (sets signal.alarm(0))
@contextmanager
def timeout(duration):
def timeout_handler(signum, frame):
raise Exception(f'block timedout after {duration} seconds')
signal.signal(signal.SIGALRM, timeout_handler)
signal.alarm(duration)
yield
signal.alarm(0)
def sleeper(duration):
time.sleep(duration)
print('finished')
Example usage:
In [19]: with timeout(2):
...: sleeper(1)
...:
finished
In [20]: with timeout(2):
...: sleeper(3)
...:
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
<ipython-input-20-66c78858116f> in <module>()
1 with timeout(2):
----> 2 sleeper(3)
3
<ipython-input-7-a75b966bf7ac> in sleeper(t)
1 def sleeper(t):
----> 2 time.sleep(t)
3 print('finished')
4
<ipython-input-18-533b9e684466> in timeout_handler(signum, frame)
2 def timeout(duration):
3 def timeout_handler(signum, frame):
----> 4 raise Exception(f'block timedout after {duration} seconds')
5 signal.signal(signal.SIGALRM, timeout_handler)
6 signal.alarm(duration)
Exception: block timedout after 2 seconds
to get localize your input use:
char sep = DecimalFormatSymbols.getInstance().getDecimalSeparator();
and then add:
textEdit.setKeyListener(DigitsKeyListener.getInstance("0123456789" + sep));
than don't forget to replace "," with "." so Float or Double can parse it without errors.
You need to clear the old array out before you push the new data in. There are many ways to accomplish this but I used this one:
options.series[0].data.length = 0;
So your code should look like this:
options.series[0].data.length = 0;
$.each(lines, function(lineNo, line) {
var items = line.split(',');
var data = {};
$.each(items, function(itemNo, item) {
if (itemNo === 0) {
data.name = item;
} else {
data.y = parseFloat(item);
}
});
options.series[0].data.push(data);
});
Now when the button is clicked the old data is purged and only the new data should show up. Hope that helps.
Create an SSLSocket
factory yourself, and set it on the HttpsURLConnection
before connecting.
...
HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
conn.setSSLSocketFactory(sslFactory);
conn.setMethod("POST");
...
You'll want to create one SSLSocketFactory
and keep it around. Here's a sketch of how to initialize it:
/* Load the keyStore that includes self-signed cert as a "trusted" entry. */
KeyStore keyStore = ...
TrustManagerFactory tmf =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keyStore);
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, tmf.getTrustManagers(), null);
sslFactory = ctx.getSocketFactory();
If you need help creating the key store, please comment.
Here's an example of loading the key store:
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(trustStore, trustStorePassword);
trustStore.close();
To create the key store with a PEM format certificate, you can write your own code using CertificateFactory
, or just import it with keytool
from the JDK (keytool won't work for a "key entry", but is just fine for a "trusted entry").
keytool -import -file selfsigned.pem -alias server -keystore server.jks
You can do it like this:
postData[postData.length] = { name: "variable_name", value: variable_value };
I managed to do this with a pretty simple bit of CSS. This does require that the error messages be siblings of the input they relate to, and that they have a class of error
.
:focus ~ .error {
display:none;
}
After meeting those two requirements, this will hide any error message related to a focused input field, something that I think angularjs should be doing anyway. Seems like an oversight.
If you only want to change the font in the TEXTAREA then you only need to change the changeFont() function in the original code to:
function changeFont(_name) {
document.getElementById("mytextarea").style.fontFamily = _name;
}
Then selecting a font will change on the font only in the TEXTAREA.
Your DOS command 2> nul
Read page Using command redirection operators. Besides the "2>" construct mentioned by Tanuki Software, it lists some other useful combinations.
phpMyAdmin includes a neat find-and-replace tool.
Select the table, then hit Search > Find and replace
This query took about a minute and successfully replaced several thousand instances of oldurl.ext
with the newurl.ext
within Column post_content
Best thing about this method : You get to check every match before committing.
N.B. I am using phpMyAdmin 4.9.0.1
ListenForClients
is getting invoked twice (on two different threads) - once from the constructor, once from the explicit method call in Main
. When two instances of the TcpListener
try to listen on the same port, you get that error.
On Windows you must edit the file daemon.json or windows-daemon-options.json, the default location of the configuration file on Windows is %programdata%\docker\config\daemon.json or %programdata%\docker\resources\windows-daemon-options.json
The optional field features on the json file, allows users to enable or disable specific daemon features. Example: {"features":{"buildkit": true}} enables buildkit as the default docker image builder.
SELECT prosrc FROM pg_proc WHERE proname = 'function_name';
This tells the function handler how to invoke the function. It might be the actual source code of the function for interpreted languages, a link symbol, a file name, or just about anything else, depending on the implementation language/call convention
If you installed it on port 8080, you need to access it on port 8080:
What you have from the server is a string like below:
var data = '[{"id":"197","category":"Damskie"},{"id":"198","category":"M\u0119skie"}]';
Then you can use JSON.parse
function to change it to an object. Then you access the category like below:
var dataObj = JSON.parse(data);
console.log(dataObj[0].category); //will return Damskie
console.log(dataObj[1].category); //will return Meskie
If you want to style the subtitle also then simply add this in your custom style.
<item name="android:subtitleTextStyle">@style/MyTheme.ActionBar.TitleTextStyle</item>
People who are looking to get the same result for AppCompat
library then this is what I used:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="CustomActivityTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">
<item name="android:actionBarStyle">@style/MyActionBar</item>
<item name="actionBarStyle">@style/MyActionBar</item>
<!-- other activity and action bar styles here -->
</style>
<!-- style for the action bar backgrounds -->
<style name="MyActionBar" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="android:background">@drawable/actionbar_background</item>
<item name="background">@drawable/actionbar_background</item>
<item name="android:titleTextStyle">@style/MyTheme.ActionBar.TitleTextStyle</item>
<item name="android:subtitleTextStyle">@style/MyTheme.ActionBar.TitleTextStyle</item>
<item name="titleTextStyle">@style/MyTheme.ActionBar.TitleTextStyle</item>
<item name="subtitleTextStyle">@style/MyTheme.ActionBar.TitleTextStyle</item>
</style>
<style name="MyTheme.ActionBar.TitleTextStyle" parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Title">
<item name="android:textColor">@color/color_title</item>
</style>
</resources>
String interpolation to the rescue.
let imageUrl = 'imageurl.png';
$('myOjbect').css('background-image', `url(${imageUrl})`);
./main.go (in package main)
./a/a.go (in package a)
./a/b.go (in package a)
in this case:
main.go import "./a"
It can call the function in the a.go and b.go,that with first letter caps on.
Definitely not the ideal solution, but it's easier for me to understand if I convert the list into tuples and then sort it.
mylist = [[1,2,3,4],[4,5,6,7]]
mylist2 = []
for thing in mylist:
thing = tuple(thing)
mylist2.append(thing)
set(mylist2)
Relative Paths
A relative path assumes that the file is on the current server. Using relative paths allows you to construct your site offline and fully test it before uploading it.
For example:
php/webct/itr/index.php
.
Absolute Paths
An absolute path refers to a file on the Internet using its full URL. Absolute paths tell the browser precisely where to go.
For example:
http://www.uvsc.edu/disted/php/webct/itr/index.php
Absolute paths are easier to use and understand. However, it is not good practice on your own website. For one thing, using relative paths allows you to construct your site offline and fully test it before uploading it. If you were to use absolute paths you would have to change your code before uploading it in order to get it to work. This would also be the case if you ever had to move your site or if you changed domain names.
Reference: http://openhighschoolcourses.org/mod/book/tool/print/index.php?id=12503
You should put javascript tag in your html file.
because browser load your webpage according to html flow, you should put your javascript file<script src="javascript/game.js">
after the <canvas>
element tag. otherwise,if you put your javascript in the header of html.Browser load script first but it doesn't find the canvas. So your canvas doesn't work.
You could use a simple regular expression to assert that the id only contains allowed characters, like so:
if(id.match(/^[0-9a-zA-Z]{1,16}$/)){
//The id is fine
}
else{
//The id is illegal
}
My example allows only alphanumerical characters, and strings of length 1 to 16, you should change it to match the type of ids that you use.
By the way, at line 6, the value property is missing a pair of quotes, an easy mistake to make when you quote on two levels.
I can't see your actual data flow, depending on context this check may not at all be needed, or it may not be enough. In order to make a proper security review we would need more information.
In general, about built in escape or sanitize functions, don't trust them blindly. You need to know exactly what they do, and you need to establish that that is actually what you need. If it is not what you need, the code your own, most of the time a simple whitelisting regex like the one I gave you works just fine.
sudo bash -c "nohup /opt/viptel/viptel_bin/log.sh $* &> /dev/null" &
Redirecting the output of sudo causes sudo to reask for the password, thus an awkward mechanism is needed to do this variant.
Here is a supplemental answer that shows some fuller code:
Container(
decoration: BoxDecoration(
color: Colors.tealAccent,
borderRadius: BorderRadius.circular(32),
),
child: TextField(
decoration: InputDecoration(
hintStyle: TextStyle(fontSize: 17),
hintText: 'Search your trips',
suffixIcon: Icon(Icons.search),
border: InputBorder.none,
contentPadding: EdgeInsets.all(20),
),
),
),
Notes:
Colors.teal
.InputDecoration
also has a filled
and fillColor
property, but I couldn't get them to have a corner radius, so I used a container instead.Also if you want to do something like ClassB.Run("thing");
, make sure the Method Run();
is static
or you could call it like this: thing.Run("thing");
.
I needed to do something like this (for unit testing purposes), and I came across this - the EnumBuster: http://www.javaspecialists.eu/archive/Issue161.html
It allows enum values to be added, removed and restored.
Edit: I've only just started using this, and found that there's some slight changes needed for java 1.5, which I'm currently stuck with:
<Memento>
use the full-featured .ajax
jQuery function.
compare with https://stackoverflow.com/a/3543713/1689451 for an example.
without testing, just merging your code with the referenced SO question:
target = $(this).attr('data-target');
$.ajax({
url: $(this).attr('href'),
type: "GET",
timeout: 2000,
success: function(response) { $(target).modal({
show: true
}); },
error: function(x, t, m) {
if(t==="timeout") {
alert("got timeout");
} else {
alert(t);
}
}
});?
To clear Application Data Please Try this way.
public void clearApplicationData() {
File cache = getCacheDir();
File appDir = new File(cache.getParent());
if (appDir.exists()) {
String[] children = appDir.list();
for (String s : children) {
if (!s.equals("lib")) {
deleteDir(new File(appDir, s));Log.i("TAG", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
}
}
}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
}
Try this simple class for customizing a dialog to your liking:
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
public class CustomDialog
{
private List<JComponent> components;
private String title;
private int messageType;
private JRootPane rootPane;
private String[] options;
private int optionIndex;
public CustomDialog()
{
components = new ArrayList<>();
setTitle("Custom dialog");
setMessageType(JOptionPane.PLAIN_MESSAGE);
setRootPane(null);
setOptions(new String[] { "OK", "Cancel" });
setOptionSelection(0);
}
public void setTitle(String title)
{
this.title = title;
}
public void setMessageType(int messageType)
{
this.messageType = messageType;
}
public void addComponent(JComponent component)
{
components.add(component);
}
public void addMessageText(String messageText)
{
JLabel label = new JLabel("<html>" + messageText + "</html>");
components.add(label);
}
public void setRootPane(JRootPane rootPane)
{
this.rootPane = rootPane;
}
public void setOptions(String[] options)
{
this.options = options;
}
public void setOptionSelection(int optionIndex)
{
this.optionIndex = optionIndex;
}
public int show()
{
int optionType = JOptionPane.OK_CANCEL_OPTION;
Object optionSelection = null;
if(options.length != 0)
{
optionSelection = options[optionIndex];
}
int selection = JOptionPane.showOptionDialog(rootPane,
components.toArray(), title, optionType, messageType, null,
options, optionSelection);
return selection;
}
public static String getLineBreak()
{
return "<br>";
}
}
Perhaps it's meaningful to also add that
$('#fieldName').prop('readonly',false);
can be used as a toggle option..
$('form#register input[required]')
It will only return inputs which have required attribute.
Is the opaque overlay for aesthetic purposes?
If so, you can use:
#overlay {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 50;
background: #000;
pointer-events: none;
opacity: 0.8;
color: #fff;
}
'pointer-events: none' will change the overlay behavior so that it can be physically opaque. Of course, this will only work in good browsers.
setLoanItem()
isn't a static method, it's an instance method, which means it belongs to a particular instance of that class rather than that class itself.
Essentially, you haven't specified what media object you want to call the method on, you've only specified the class name. There could be thousands of media objects and the compiler has no way of knowing what one you meant, so it generates an error accordingly.
You probably want to pass in a media object on which to call the method:
public void loanItem(Media m) {
m.setLoanItem("Yes");
}
The usual way to do this is something like the following.
test1.py
def some_func():
print 'in test 1, unproductive'
if __name__ == '__main__':
# test1.py executed as script
# do something
some_func()
service.py
import test1
def service_func():
print 'service func'
if __name__ == '__main__':
# service.py executed as script
# do something
service_func()
test1.some_func()
1.Just Disable signing from the properties of your project it will solve issue :)
2.The other method is to purchase the certificate for your product from Digicert or Comodo or any other you want. You can get some free certificates for One pc use.
I sorted this problem by verifying the json on JSONLint.com and then using Jackson. Below is the code for the same.
Main Class:-
String jsonStr = "[{\r\n" + " \"name\": \"John\",\r\n" + " \"city\": \"Berlin\",\r\n"
+ " \"cars\": [\r\n" + " \"FIAT\",\r\n" + " \"Toyata\"\r\n"
+ " ],\r\n" + " \"job\": \"Teacher\"\r\n" + " },\r\n" + " {\r\n"
+ " \"name\": \"Mark\",\r\n" + " \"city\": \"Oslo\",\r\n" + " \"cars\": [\r\n"
+ " \"VW\",\r\n" + " \"Toyata\"\r\n" + " ],\r\n"
+ " \"job\": \"Doctor\"\r\n" + " }\r\n" + "]";
ObjectMapper mapper = new ObjectMapper();
MyPojo jsonObj[] = mapper.readValue(jsonStr, MyPojo[].class);
for (MyPojo itr : jsonObj) {
System.out.println("Val of getName is: " + itr.getName());
System.out.println("Val of getCity is: " + itr.getCity());
System.out.println("Val of getJob is: " + itr.getJob());
System.out.println("Val of getCars is: " + itr.getCars() + "\n");
}
POJO:
public class MyPojo {
private List<String> cars = new ArrayList<String>();
private String name;
private String job;
private String city;
public List<String> getCars() {
return cars;
}
public void setCars(List<String> cars) {
this.cars = cars;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
} }
RESULT:-
Val of getName is: John
Val of getCity is: Berlin
Val of getJob is: Teacher
Val of getCars is: [FIAT, Toyata]
Val of getName is: Mark
Val of getCity is: Oslo
Val of getJob is: Doctor
Val of getCars is: [VW, Toyata]
I just wanted to post a demo using calc() for setting rows/height, since no one did.
body {_x000D_
/* page default */_x000D_
font-size: 15px;_x000D_
line-height: 1.5;_x000D_
}_x000D_
_x000D_
textarea {_x000D_
/* demo related */_x000D_
width: 300px;_x000D_
margin-bottom: 1em;_x000D_
display: block;_x000D_
_x000D_
/* rows related */_x000D_
font-size: inherit;_x000D_
line-height: inherit;_x000D_
padding: 3px;_x000D_
}_x000D_
_x000D_
textarea.border-box {_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
textarea.rows-5 {_x000D_
/* height: calc(font-size * line-height * rows); */_x000D_
height: calc(1em * 1.5 * 5);_x000D_
}_x000D_
_x000D_
textarea.border-box.rows-5 {_x000D_
/* height: calc(font-size * line-height * rows + padding-top + padding-bottom + border-top-width + border-bottom-width); */_x000D_
height: calc(1em * 1.5 * 5 + 3px + 3px + 1px + 1px);_x000D_
}
_x000D_
<p>height is 2 rows by default</p>_x000D_
_x000D_
<textarea>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>_x000D_
_x000D_
<p>height is 5 now</p>_x000D_
_x000D_
<textarea class="rows-5">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>_x000D_
_x000D_
<p>border-box height is 5 now</p>_x000D_
_x000D_
<textarea class="border-box rows-5">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>
_x000D_
If you use large values for the paddings (e.g. greater than 0.5em), you'll start to see the text that overflows the content(-box) area, and that might lead you to think that the height is not exactly x rows (that you set), but it is. To understand what's going on, you might want to check out The box model and box-sizing pages.
Abstract Data type is a mathematical module that includes data with various operations. Implementation details are hidden and that's why it is called abstract. Abstraction allowed you to organise the complexity of the task by focusing on logical properties of data and actions.
you can use asctime() function of time.h to get a string simply .
time_t _tm =time(NULL );
struct tm * curtime = localtime ( &_tm );
cout<<"The current date/time is:"<<asctime(curtime);
Sample output:
The current date/time is:Fri Oct 16 13:37:30 2015
You don't even need to cast, it is implicit.
int i = 3;
float f = i;
A full list/table of implicit numeric conversions can be seen here http://msdn.microsoft.com/en-us/library/y5b434w4.aspx
Is canny
your own function? Do you use Canny from OpenCV inside it? If yes check if you feed suitable argument for Canny
- first Canny
argument should meet following criteria:
<type 'numpy.ndarray'>
dtype('uint8')
shape
should be 2-tuple
of int
s (tuple
containing exactly 2 integers)You can check it by printing respectively
type(variable_name)
variable_name.dtype
variable_name.shape
Replace variable_name
with name of variable you feed as first argument to Canny
.
Have a look at the jQuery.scrollTo plugin. Here's a demo.
This plugin has a lot of options that go beyond what native scrollIntoView offers you. For instance, you can set the scrolling to be smooth, and then set a callback for when the scrolling finishes.
You can also have a look at all the JQuery plugins tagged with "scroll".
I think u want to change the default settings of android studio. Whenever a layout or Activity in created u want to create "RelativeLayout" by default. In that case, flow the step below
you are done
Use GREATEST()
E.g.:
SELECT GREATEST(2,1);
Note: Whenever if any single value contains null at that time this function always returns null (Thanks to user @sanghavi7)
public static void main (String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Please enter size of an array");
int n=s.nextInt();
double arr[] = new double[n];
System.out.println("Please enter elements of array:");
for (int i=0; i<n; i++)
{
arr[i] = s.nextDouble();
}
}
Its simple only one line code is needed for this.
if String A = scanner.nextLine();
then you need to write this to display the string with this first letter capitalized.
System.out.println(A.substring(0, 1).toUpperCase() + A.substring(1));
And its done now.
vMYQUERY := 'SELECT COUNT(*) FROM ALL_OBJECTS WHERE OWNER = UPPER(''MFI_IDBI2LIVE'') AND OBJECT_TYPE = ''TABLE''
AND OBJECT_NAME =''' || vTBL_CLIENT_MASTER || '''';
PRINT_STRING(VMYQUERY);
EXECUTE IMMEDIATE vMYQUERY INTO VCOUNTTEMP ;
You could use SQL.js which is the SQLlite lib compiled to JavaScript and store the database in the local storage introduced in HTML5.
Another thing you can try (based on tvanfosson's answer) is this:
<div class="renderaction fade-in"
data-actionurl="@Url.Action("details","user", new { id = Model.ID } )"></div>
And then in the scripts section of your page:
<script type="text/javascript">
$(function () {
$(".renderaction").each(function (i, n) {
var $n = $(n),
url = $n.attr('data-actionurl'),
$this = $(this);
$.get(url, function (data) {
$this.html(data);
});
});
});
</script>
This renders your @Html.RenderAction using ajax.
And to make it all fansy sjmansy you can add a fade-in effect using this css:
/* make keyframes that tell the start state and the end state of our object */
@-webkit-keyframes fadeIn { from { opacity:0; } to { opacity:1; } }
@-moz-keyframes fadeIn { from { opacity:0; } to { opacity:1; } }
@keyframes fadeIn { from { opacity:0; } to { opacity:1; } }
.fade-in {
opacity: 0; /* make things invisible upon start */
-webkit-animation: fadeIn ease-in 1; /* call our keyframe named fadeIn, use animattion ease-in and repeat it only 1 time */
-moz-animation: fadeIn ease-in 1;
-o-animation: fadeIn ease-in 1;
animation: fadeIn ease-in 1;
-webkit-animation-fill-mode: forwards; /* this makes sure that after animation is done we remain at the last keyframe value (opacity: 1)*/
-o-animation-fill-mode: forwards;
animation-fill-mode: forwards;
-webkit-animation-duration: 1s;
-moz-animation-duration: 1s;
-o-animation-duration: 1s;
animation-duration: 1s;
}
Man I love mvc :-)
Here is the solution with a for
loop. Importantly, it takes the one call to readLines
out of the for loop so that it is not improperly called again and again. Here it is:
fileName <- "up_down.txt"
conn <- file(fileName,open="r")
linn <-readLines(conn)
for (i in 1:length(linn)){
print(linn[i])
}
close(conn)
If you're using C# 3.0 you can use linq, way better and way more elegant:
List<int> myList = GetListOfIntsFromSomewhere();
// This will filter out the list of ints that are > than 7, Where returns an
// IEnumerable<T> so a call to ToList is required to convert back to a List<T>.
List<int> filteredList = myList.Where( x => x > 7).ToList();
If you can't find the .Where
, that means you need to import using System.Linq;
at the top of your file.
Try this:
window.open(url, '_blank');
This will open in new tab (if your code is synchronous and in this case it is. in other case it would open a window)
I prefer manipulating the length of the stringbuilder:
data.Length = data.Length - 1;
USE This Assembly Referance in your Project
Add a reference to System.Net.Http.Formatting.dll
For Bootstrap 4
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="input-group">_x000D_
<input type="text" class="form-control" placeholder="Start"/>_x000D_
<div class="input-group-prepend">_x000D_
<span class="input-group-text" id="">-</span>_x000D_
</div>_x000D_
<input type="text" class="form-control" placeholder="End"/>_x000D_
</div>
_x000D_
import java.util.*;
public class Main {
public static void main(String[] args) {
TreeMap<String, Integer> initTree = new TreeMap();
initTree.put("D", 0);
initTree.put("C", -3);
initTree.put("A", 43);
initTree.put("B", 32);
System.out.println("Sorted by keys:");
System.out.println(initTree);
List list = new ArrayList(initTree.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> e1, Map.Entry<String, Integer> e2) {
return e1.getValue().compareTo(e2.getValue());
}
});
System.out.println("Sorted by values:");
System.out.println(list);
}
}
You might want to use the timeit module instead.
If you want to use the autobuilder at hub.docker.com, it has to be Dockerfile
. So there :)
Only suggestion is to access your resp_dict
via .get()
for a more graceful approach that will degrade well if the data isn't as expected.
resp_dict = json.loads(resp_str)
resp_dict.get('name') # will return None if 'name' doesn't exist
You could also add some logic to test for the key if you want as well.
if 'name' in resp_dict:
resp_dict['name']
else:
# do something else here.
SELECT json_agg(t) FROM t
for a JSON array of objects, and
SELECT
json_build_object(
'a', json_agg(t.a),
'b', json_agg(t.b)
)
FROM t
for a JSON object of arrays.
This section describes how to generate a JSON array of objects, with each row being converted to a single object. The result looks like this:
[{"a":1,"b":"value1"},{"a":2,"b":"value2"},{"a":3,"b":"value3"}]
The json_agg
function produces this result out of the box. It automatically figures out how to convert its input into JSON and aggregates it into an array.
SELECT json_agg(t) FROM t
There is no jsonb
(introduced in 9.4) version of json_agg
. You can either aggregate the rows into an array and then convert them:
SELECT to_jsonb(array_agg(t)) FROM t
or combine json_agg
with a cast:
SELECT json_agg(t)::jsonb FROM t
My testing suggests that aggregating them into an array first is a little faster. I suspect that this is because the cast has to parse the entire JSON result.
9.2 does not have the json_agg
or to_json
functions, so you need to use the older array_to_json
:
SELECT array_to_json(array_agg(t)) FROM t
You can optionally include a row_to_json
call in the query:
SELECT array_to_json(array_agg(row_to_json(t))) FROM t
This converts each row to a JSON object, aggregates the JSON objects as an array, and then converts the array to a JSON array.
I wasn't able to discern any significant performance difference between the two.
This section describes how to generate a JSON object, with each key being a column in the table and each value being an array of the values of the column. It's the result that looks like this:
{"a":[1,2,3], "b":["value1","value2","value3"]}
We can leverage the json_build_object
function:
SELECT
json_build_object(
'a', json_agg(t.a),
'b', json_agg(t.b)
)
FROM t
You can also aggregate the columns, creating a single row, and then convert that into an object:
SELECT to_json(r)
FROM (
SELECT
json_agg(t.a) AS a,
json_agg(t.b) AS b
FROM t
) r
Note that aliasing the arrays is absolutely required to ensure that the object has the desired names.
Which one is clearer is a matter of opinion. If using the json_build_object
function, I highly recommend putting one key/value pair on a line to improve readability.
You could also use array_agg
in place of json_agg
, but my testing indicates that json_agg
is slightly faster.
There is no jsonb
version of the json_build_object
function. You can aggregate into a single row and convert:
SELECT to_jsonb(r)
FROM (
SELECT
array_agg(t.a) AS a,
array_agg(t.b) AS b
FROM t
) r
Unlike the other queries for this kind of result, array_agg
seems to be a little faster when using to_jsonb
. I suspect this is due to overhead parsing and validating the JSON result of json_agg
.
Or you can use an explicit cast:
SELECT
json_build_object(
'a', json_agg(t.a),
'b', json_agg(t.b)
)::jsonb
FROM t
The to_jsonb
version allows you to avoid the cast and is faster, according to my testing; again, I suspect this is due to overhead of parsing and validating the result.
The json_build_object
function was new to 9.5, so you have to aggregate and convert to an object in previous versions:
SELECT to_json(r)
FROM (
SELECT
json_agg(t.a) AS a,
json_agg(t.b) AS b
FROM t
) r
or
SELECT to_jsonb(r)
FROM (
SELECT
array_agg(t.a) AS a,
array_agg(t.b) AS b
FROM t
) r
depending on whether you want json
or jsonb
.
(9.3 does not have jsonb
.)
In 9.2, not even to_json
exists. You must use row_to_json
:
SELECT row_to_json(r)
FROM (
SELECT
array_agg(t.a) AS a,
array_agg(t.b) AS b
FROM t
) r
Find the documentation for the JSON functions in JSON functions.
json_agg
is on the aggregate functions page.
If performance is important, ensure you benchmark your queries against your own schema and data, rather than trust my testing.
Whether it's a good design or not really depends on your specific application. In terms of maintainability, I don't see any particular problem. It simplifies your app code and means there's less to maintain in that portion of the app. If PG can give you exactly the result you need out of the box, the only reason I can think of to not use it would be performance considerations. Don't reinvent the wheel and all.
Aggregate functions typically give back NULL
when they operate over zero rows. If this is a possibility, you might want to use COALESCE
to avoid them. A couple of examples:
SELECT COALESCE(json_agg(t), '[]'::json) FROM t
Or
SELECT to_jsonb(COALESCE(array_agg(t), ARRAY[]::t[])) FROM t
Credit to Hannes Landeholm for pointing this out
As martijn-courteaux said, create a custom component it's the better option. In C# exists a component called PictureBox and I tried to create this component for Java, here is the code:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
public class JPictureBox extends JComponent {
private Icon icon = null;
private final Dimension dimension = new Dimension(100, 100);
private Image image = null;
private ImageIcon ii = null;
private SizeMode sizeMode = SizeMode.STRETCH;
private int newHeight, newWidth, originalHeight, originalWidth;
public JPictureBox() {
JPictureBox.this.setPreferredSize(dimension);
JPictureBox.this.setOpaque(false);
JPictureBox.this.setSizeMode(SizeMode.STRETCH);
}
@Override
public void paintComponent(Graphics g) {
if (ii != null) {
switch (getSizeMode()) {
case NORMAL:
g.drawImage(image, 0, 0, ii.getIconWidth(), ii.getIconHeight(), null);
break;
case ZOOM:
aspectRatio();
g.drawImage(image, 0, 0, newWidth, newHeight, null);
break;
case STRETCH:
g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), null);
break;
case CENTER:
g.drawImage(image, (int) (this.getWidth() / 2) - (int) (ii.getIconWidth() / 2), (int) (this.getHeight() / 2) - (int) (ii.getIconHeight() / 2), ii.getIconWidth(), ii.getIconHeight(), null);
break;
default:
g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), null);
}
}
}
public Icon getIcon() {
return icon;
}
public void setIcon(Icon icon) {
this.icon = icon;
ii = (ImageIcon) icon;
image = ii.getImage();
originalHeight = ii.getIconHeight();
originalWidth = ii.getIconWidth();
}
public SizeMode getSizeMode() {
return sizeMode;
}
public void setSizeMode(SizeMode sizeMode) {
this.sizeMode = sizeMode;
}
public enum SizeMode {
NORMAL,
STRETCH,
CENTER,
ZOOM
}
private void aspectRatio() {
if (ii != null) {
newHeight = this.getHeight();
newWidth = (originalWidth * newHeight) / originalHeight;
}
}
}
If you want to add an image, choose the JPictureBox, after that go to Properties and find "icon" property and select an image. If you want to change the sizeMode property then choose the JPictureBox, after that go to Properties and find "sizeMode" property, you can choose some values:
If you want to learn more about this topic, you can check this video.
The rules for turning on the carry flag in binary/integer math are two:
The carry flag is set if the addition of two numbers causes a carry out of the most significant (leftmost) bits added. 1111 + 0001 = 0000 (carry flag is turned on)
The carry (borrow) flag is also set if the subtraction of two numbers requires a borrow into the most significant (leftmost) bits subtracted. 0000 - 0001 = 1111 (carry flag is turned on) Otherwise, the carry flag is turned off (zero).
In unsigned arithmetic, watch the carry flag to detect errors.
In signed arithmetic, the carry flag tells you nothing interesting.
The rules for turning on the overflow flag in binary/integer math are two:
If the sum of two numbers with the sign bits off yields a result number with the sign bit on, the "overflow" flag is turned on. 0100 + 0100 = 1000 (overflow flag is turned on)
If the sum of two numbers with the sign bits on yields a result number with the sign bit off, the "overflow" flag is turned on. 1000 + 1000 = 0000 (overflow flag is turned on)
Otherwise the "overflow" flag is turned off
Note that you only need to look at the sign bits (leftmost) of the three numbers to decide if the overflow flag is turned on or off.
If you are doing two's complement (signed) arithmetic, overflow flag on means the answer is wrong - you added two positive numbers and got a negative, or you added two negative numbers and got a positive.
If you are doing unsigned arithmetic, the overflow flag means nothing and should be ignored.
For more clarification please refer: http://teaching.idallen.com/dat2343/10f/notes/040_overflow.txt
The :last-child
selector should do it, but it's not supported in any version of IE.
I'm afraid you have no choice but to use a class.
The obvious question being "why do you want to read in the entire file?" This is obviously not a scalable solution if your files get very large. The scala.io.Source
gives you back an Iterator[String]
from the getLines
method, which is very useful and concise.
It's not much of a job to come up with an implicit conversion using the underlying java IO utilities to convert a File
, a Reader
or an InputStream
to a String
. I think that the lack of scalability means that they are correct not to add this to the standard API.
This works on Windows with Cygwin installed:
System.getenv("NUMBER_OF_PROCESSORS")
I tested and used this command in kafka confluent V4.0.0
and apache kafka V 1.0.0 and 1.0.1
/opt/kafka/confluent-4.0.0/bin/kafka-configs --zookeeper XX.XX.XX.XX:2181 --entity-type topics --entity-name test --alter --add-config retention.ms=55000
test
is the topic name.
I think it works well in other versions too
glob2rx()
converts a pattern including a wildcard into the equivalent regular expression. You then need to pass this regular expression onto one of R's pattern matching tools.
If you want to match "blue*"
where *
has the usual wildcard, not regular expression, meaning we use glob2rx()
to convert the wildcard pattern into a useful regular expression:
> glob2rx("blue*")
[1] "^blue"
The returned object is a regular expression.
Given your data:
x <- c('red','blue1','blue2', 'red2')
we can pattern match using grep()
or similar tools:
> grx <- glob2rx("blue*")
> grep(grx, x)
[1] 2 3
> grep(grx, x, value = TRUE)
[1] "blue1" "blue2"
> grepl(grx, x)
[1] FALSE TRUE TRUE FALSE
As for the selecting rows problem you posted
> a <- data.frame(x = c('red','blue1','blue2', 'red2'))
> with(a, a[grepl(grx, x), ])
[1] blue1 blue2
Levels: blue1 blue2 red red2
> with(a, a[grep(grx, x), ])
[1] blue1 blue2
Levels: blue1 blue2 red red2
or via subset()
:
> with(a, subset(a, subset = grepl(grx, x)))
x
2 blue1
3 blue2
Hope that explains what grob2rx()
does and how to use it?
Install sshpass, then launch the command:
sshpass -p "yourpassword" ssh -o StrictHostKeyChecking=no yourusername@hostname
If you are sure there are no leading spaces, you can use bash parameter substitution:
$ string="word1 word2"
$ echo ${string/%\ */}
word1
Watch out for escaping the single space. See here for more examples of substitution patterns. If you have bash > 3.0, you could also use regular expression matching to cope with leading spaces - see here:
$ string=" word1 word2"
$ [[ ${string} =~ \ *([^\ ]*) ]]
$ echo ${BASH_REMATCH[1]}
word1
Maybe your file contains CRLF terminator. Every lines followed by \r\n.
awk
recognizes the $2
actually $2\r
. The \r
means goto the start of the line.
{print $2\r$1}
will print $2
first, then return to the head, then print $1
. So the field 2 is overlaid by the field 1.
Assuming that you meant to write
char *functionname(char *string[256])
Here you are declaring a function that takes an array of 256 pointers to char
as argument and returns a pointer to char. Here, on the other hand,
char functionname(char string[256])
You are declaring a function that takes an array of 256 char
s as argument and returns a char
.
In other words the first function takes an array of strings and returns a string, while the second takes a string and returns a character.
By the RFC7231 it does not matter and may be empty
How we implement json api standard based solution in the project:
post/put: outputs object attributes as in get (field filter/relations applies the same)
delete: data only contains null (for its a representation of missing object)
status for standard delete: 200
I try to modify the repositories and import the cer to java, but both failed, then I upgrade my jdk version from 1.8.0_66 to 1.8.0_74, gradle build success.
You can use git reset
. This will 'unstage' all the files you've added after your last commit.
If you want to unstage only some files, use git reset -- <file 1> <file 2> <file n>
.
Also it's possible to unstage some of the changes in files by using git reset -p
.
in IE you can get the event object by window.event
in other browsers with no 'use strict'
directive, it is possible to get by arguments.callee.caller.arguments[0]
.
function myFunc(p1, p2, p3) {
var evt = window.event || arguments.callee.caller.arguments[0];
}
For Windows 7,
Control Panel --> Programs --> Uninstall
, then
choose the python package to remove.
Having two divs,
<div id="div1">The two divs are</div>
<div id="div2">next to each other.</div>
you could also use the display
property:
#div1 {
display: inline-block;
}
#div2 {
display: inline-block;
}
jsFiddle example here.
If div1
exceeds a certain height, div2
will be placed next to div1
at the bottom. To solve this, use vertical-align:top;
on div2
.
jsFiddle example here.
According to apple doc:
File-Sharing Support
File-sharing support lets apps make user data files available in iTunes 9.1 and later. An app that declares its support for file sharing makes the contents of its /Documents directory available to the user. The user can then move files in and out of this directory as needed from iTunes. This feature does not allow your app to share files with other apps on the same device; that behavior requires the pasteboard or a document interaction controller object.To enable file sharing for your app, do the following:
Add the UIFileSharingEnabled key to your app’s Info.plist file, and set the value of the key to YES. (The actual key name is "Application supports iTunes file sharing")
Put whatever files you want to share in your app’s Documents directory.
When the device is plugged into the user’s computer, iTunes displays a File Sharing section in the Apps tab of the selected device.
The user can add files to this directory or move files to the desktop.
Apps that support file sharing should be able to recognize when files have been added to the Documents directory and respond appropriately. For example, your app might make the contents of any new files available from its interface. You should never present the user with the list of files in this directory and ask them to decide what to do with those files.
For additional information about the UIFileSharingEnabled key, see Information Property List Key Reference.
You can use the output value from stat_summary()
ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group))
+ geom_boxplot()
+ stat_summary(fun.y=mean, colour="darkred", geom="point", hape=18, size=3,show_guide = FALSE)
+ stat_summary(fun.y=mean, colour="red", geom="text", show_guide = FALSE,
vjust=-0.7, aes( label=round(..y.., digits=1)))
Update for 2020: Sticking to the original question of 16x16 versus 32x32 icons: the current recommendation should be to provide a 32x32 icon, skipping 16x16 entirely. All current browsers and devices support 32x32 icons. The icon will routinely be upscaled to as much as 192x192 depending on the environment (assuming there are no larger sizes available or the system didn't recognize them). Upscaling from ultra low resolution has a noticeable effect so better stick to 32x32 as the smallest baseline.
For IE, Microsoft recommends 16x16, 32x32 and 48x48 packed in the favicon.ico file.
For iOS, Apple recommends specific file names and resolutions, at most 180x180 for latest devices running iOS 8.
Android Chrome primarily uses a manifest and also relies on the Apple touch icon.
IE 10 on Windows 8.0 requires PNG pictures and a background color and IE 11 on Windows 8.1 and 10 accepts several PNG pictures declared in a dedicated XML file called browserconfig.xml
.
Safari for Mac OS X El Capitan introduces an SVG icon for pinned tabs.
Some other platforms look for PNG files with various resolutions, like the 96x96 picture for Google TV or the 228x228 picture for Opera Coast.
Look at this favicon pictures list for a complete reference.
TLDR: This favicon generator can generate all these files at once. The generator can also be implemented as a WordPress plugin. Full disclosure: I am the author of this site.
I fixed this problem with sql command line:
connect system/<password>
alter system set processes=300 scope=spfile;
alter system set sessions=300 scope=spfile;
Restart database.
You might try changing this line in your persistence.xml from
<property name="hbm2ddl.auto" value="create"/>
to:
<property name="hibernate.hbm2ddl.auto" value="update"/>
This is supposed to maintain the schema to follow any changes you make to the Model each time you run the app.
Got this from JavaRanch
there is a way you can pass more than one parameter. You can pass "to" as object instead of string.
// your route setup
<Route path="/category/:catId" component={Category} / >
// your link creation
const newTo = {
pathname: "/category/595212758daa6810cbba4104",
param1: "Par1"
};
// link to the "location"
// see (https://reacttraining.com/react-router/web/api/location)
<Link to={newTo}> </Link>
// In your Category Component, you can access the data like this
this.props.match.params.catId // this is 595212758daa6810cbba4104
this.props.location.param1 // this is Par1
Just sort the array in ascending order and print it backwards.
Arrays.sort(arr);
for(int i = arr.length-1; i >= 0 ; i--) {
//print arr[i]
}
PHP has a function called money_format
for doing this. Read about this here.
You could add \singlespacing near the beginning of your table. See the setspace instructions for more options.
I've had this problem. See The Python "Connection Reset By Peer" Problem.
You have (most likely) run afoul of small timing issues based on the Python Global Interpreter Lock.
You can (sometimes) correct this with a time.sleep(0.01)
placed strategically.
"Where?" you ask. Beats me. The idea is to provide some better thread concurrency in and around the client requests. Try putting it just before you make the request so that the GIL is reset and the Python interpreter can clear out any pending threads.
As other answers explain Memory in Java is divided into two portions
1. Stack: One stack is created per thread and it stores stack frames which again stores local variables and if a variable is a reference type then that variable refers to a memory location in heap for the actual object.
2. Heap: All kinds of objects will be created in heap only.
Heap memory is again divided into 3 portions
1. Young Generation: Stores objects which have a short life, Young Generation itself can be divided into two categories Eden Space and Survivor Space.
2. Old Generation: Store objects which have survived many garbage collection cycles and still being referenced.
3. Permanent Generation: Stores metadata about the program e.g. runtime constant pool.
String constant pool belongs to the permanent generation area of Heap memory.
We can see the runtime constant pool for our code in the bytecode by using javap -verbose class_name
which will show us method references (#Methodref), Class objects ( #Class ), string literals ( #String )
You can read more about it on my article How Does JVM Handle Method Overloading and Overriding Internally.
I'm in the same situation. Really like the pattern of keeping the styling in the components but the hover states seems like the last hurdle.
What I did was writing a mixin that you can add to your component that needs hover states.
This mixin will add a new hovered
property to the state of your component. It will be set to true
if the user hovers over the main DOM node of the component and sets it back to false
if the users leaves the element.
Now in your component render function you can do something like:
<button style={m(
this.styles.container,
this.state.hovered && this.styles.hover,
)}>{this.props.children}</button>
Now each time the state of the hovered
state changes the component will rerender.
I've also create a sandbox repo for this that I use to test some of these patterns myself. Check it out if you want to see an example of my implementation.
https://github.com/Sitebase/cssinjs/tree/feature-interaction-mixin
First, you're missing some parentheses in your conditional:
if ($("#about").hasClass("opened")) {
$("#about").animate({right: "-700px"}, 2000);
}
But you can also simplify this to:
$('#about.opened').animate(...);
If #about
doesn't have the opened
class, it won't animate.
If the problem is with the animation itself, we'd need to know more about your element positioning (absolute? absolute inside relative parent? does the parent have layout?)
you can use the some Codeigniter functions and some core functions and make combination to achieve your URL with query string. I found solution of this problem.
base_url($this->uri->uri_string()).strrchr($_SERVER['REQUEST_URI'], "?");
and if you loaded URL helper so you can also do this current_url().strrchr($_SERVER['REQUEST_URI'], "?");
If HTML and use bootstrap they have a helper class.
<span class="text-nowrap">1-866-566-7233</span>
In the absense of cache control directives that specify otherwise, a 301 redirect defaults to being cached without any expiry date.
That is, it will remain cached for as long as the browser's cache can accommodate it. It will be removed from the cache if you manually clear the cache, or if the cache entries are purged to make room for new ones.
You can verify this at least in Firefox by going to about:cache
and finding it under disk cache. It works this way in other browsers including Chrome and the Chromium based Edge, though they don't have an about:cache
for inspecting the cache.
In all browsers it is still possible to override this default behavior using caching directives, as described below:
If you don't want the redirect to be cached
This indefinite caching is only the default caching by these browsers in the absence of headers that specify otherwise. The logic is that you are specifying a "permanent" redirect and not giving them any other caching instructions, so they'll treat it as if you wanted it indefinitely cached.
The browsers still honor the Cache-Control and Expires headers like with any other response, if they are specified.
You can add headers such as Cache-Control: max-age=3600
or Expires: Thu, 01 Dec 2014 16:00:00 GMT
to your 301 redirects. You could even add Cache-Control: no-cache
so it won't be cached permanently by the browser or Cache-Control: no-store
so it can't even be stored in temporary storage by the browser.
Though, if you don't want your redirect to be permanent, it may be a better option to use a 302 or 307 redirect. Issuing a 301 redirect but marking it as non-cacheable is going against the spirit of what a 301 redirect is for, even though it is technically valid. YMMV, and you may find edge cases where it makes sense for a "permanent" redirect to have a time limit. Note that 302 and 307 redirects aren't cached by default by browsers.
If you previously issued a 301 redirect but want to un-do that
If people still have the cached 301 redirect in their browser they will continue to be taken to the target page regardless of whether the source page still has the redirect in place. Your options for fixing this include:
A simple solution is to issue another redirect back again.
If the browser is directed back to a same URL a second time during a redirect, it should fetch it from the origin again instead of redirecting again from cache, in an attempt to avoid a redirect loop. Comments on this answer indicate this now works in all major browsers - but there may be some minor browsers where it doesn't.
If you don't have control over the site where the previous redirect target went to, then you are out of luck. Try and beg the site owner to redirect back to you.
Prevention is better than cure - avoid a 301 redirect if you are not sure you want to permanently de-commission the old URL.
Use is.na
DF <- data.frame(x = c(1, 2, 3), y = c(0, 10, NA), z=c(NA, 33, 22))
DF[!is.na(DF$y),]
You could add a Category partial and a Product partial, each would take a smaller part of the main model as it's own model, i.e. Category's model type might be an IEnumerable, you would pass in Model.Theme to it. The Product's partial might be an IEnumerable that you pass Model.Products into (from within the Category partial).
I'm not sure if that would be the right way forward, but would be interested in knowing.
EDIT
Since posting this answer, I've used EditorTemplates and find this the easiest way to handle repeating input groups or items. It handles all your validation message problems and form submission/model binding woes automatically.
.NET has a built functionality for compressing files in the System.IO.Compression namespace. Using this you do not have to take an extra library as a dependency. This functionality is available from .NET 2.0.
Here is the way to do the compressing from the MSDN page I linked:
public static void Compress(FileInfo fi)
{
// Get the stream of the source file.
using (FileStream inFile = fi.OpenRead())
{
// Prevent compressing hidden and already compressed files.
if ((File.GetAttributes(fi.FullName) & FileAttributes.Hidden)
!= FileAttributes.Hidden & fi.Extension != ".gz")
{
// Create the compressed file.
using (FileStream outFile = File.Create(fi.FullName + ".gz"))
{
using (GZipStream Compress = new GZipStream(outFile,
CompressionMode.Compress))
{
// Copy the source file into the compression stream.
byte[] buffer = new byte[4096];
int numRead;
while ((numRead = inFile.Read(buffer, 0, buffer.Length)) != 0)
{
Compress.Write(buffer, 0, numRead);
}
Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
fi.Name, fi.Length.ToString(), outFile.Length.ToString());
}
}
}
}
You're not assigning any id to the text view, but you're using tv.getId()
to pass it to the addRule
method as a parameter. Try to set a unique id via tv.setId(int)
.
You could also use the LinearLayout with vertical orientation, that might be easier actually. I prefer LinearLayout over RelativeLayouts if not necessary otherwise.
I think its works for everyone
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Search</title>
</head>
<body>
<form action="" method="post">
<input type="text" placeholder="Search" name="search">
<button type="submit" name="submit">Search</button>
</form>
</body>
</html>
<?php
if (isset($_POST['submit'])) {
$searchValue = $_POST['search'];
$con = new mysqli("localhost", "root", "", "testing");
if ($con->connect_error) {
echo "connection Failed: " . $con->connect_error;
} else {
$sql = "SELECT * FROM customer_info WHERE name OR email LIKE '%$searchValue%'";
$result = $con->query($sql);
while ($row = $result->fetch_assoc()) {
echo $row['name'] . "<br>";
echo $row['email'] . "<br>";
}
}
}
?>
I was looking for the answer of the same question but for a while I found my own solution and I wanted to share it for other people who will need those codes in the future. Here is another solution without function.
Dim control As Boolean
Dim controlval As String
Dim resultval As String
Dim i as Integer
controlval = "A1B2C3D4"
For i = 1 To Len(controlval)
control = IsNumeric(Mid(controlval, i, 1))
If control = True Then resultval = resultval & Mid(controlval, i, 1)
Next i
resultval = 1234
SELECT timeEvent
FROM tbEvents
WHERE CONVERT(VARCHAR,startHour,108) >= '01:01:01'
This tells SQL Server to convert the current date/time into a varchar using style 108, which is "hh:mm:ss". You can also replace '01:01:01' which another convert if necessary.
We can use this method instead. Just an example from my projects. Refer the code. Some extras are also included.
Look to the if statements!
/*
Every C++ program should have an entry point. Usually, this is the main function.
Every C++ Statement ends with a ';' (semi-colon)
But, pre-processor statements do not have ';'s at end.
Also, every console program can be ended using "cin.get();" statement, so that the console won't exit instantly.
*/
#include <string>
#include <bits/stdc++.h> //Can Use instead of iostream. Also should be included to use the transform function.
using namespace std;
int main(){ //The main function. This runs first in every program.
string input;
while(input!="exit"){
cin>>input;
transform(input.begin(),input.end(),input.begin(),::tolower); //Converts to lowercase.
if(input.find("name") != std::string::npos){ //Gets a boolean value regarding the availability of the said text.
cout<<"My Name is AI \n";
}
if(input.find("age") != std::string::npos){
cout<<"My Age is 2 minutes \n";
}
}
}
How about this
private Object element[] = new Object[] {};
Its very simple to install Mongo DB on windows 7 ( i used 32 bit win7 OS)
2.u can install Mongodb from thius website ( acc to ur OS) http://www.mongodb.org/downloads?_ga=1.79549524.1754732149.1410784175
4.copy the mongodb folder from c:programfiles to d: [optional]
5.After installation open command prompt ( as administrator .. right click on cmd and u will find the option)
navigate to D:\MongoDB 2.6 Standard\bin
run mongo.exe ... you might get this error
If you get then no isse you just need to do following steps
i) try the coomand in following image yo will get to know the error
ii)This means that u neeed to create a directory \data\db
iii) now you have two options either create above directory in c drive or create any "xyz" name directory somewhere else ( doesnot make and diffrence) .. lets create a directory of mongodata in d:
colured in orange will be the command u need to run .. it will open the new command propmt which we known as mongo shell (or mongodb shell)
11.dont close the shell[any of command promt as well] as in this we will create /delete/insert our databse operations
a) show databases b) show current databse c) creation of collection / inserting data into it (name will be test) d) show data of collection
12.please find scrren shot of results of our operation .. please not :- dont close any command propmt
a diffrent structure type of number is object id :- which is created automatically
Hope you get some important info for installing mongodb DB.
I thought the regular modulus operator would work for this in java, but it can't be hard to code. Just divide the numerator by the denominator, and take the integer portion of the result. Multiply that by the denominator, and subtract the result from the numerator.
x = n / d
xint = Integer portion of x
result = n - d * xint
(For future reference.)
Quite possibly the fastest way to do this would be to use memory mapped files (so primarily copying memory, and the OS handling the file reads/writes via its paging/memory management).
Memory Mapped files are supported in managed code in .NET 4.0.
But as noted, you need to profile, and expect to switch to native code for maximum performance.
Just add map:
" ~/.vimrc
inoremap <c-p> <c-r>*
restart vim and when press Crtl+p
in insert mode,
copied text will be pasted
Here's an optimized implementation:
public static final Comparator<CharSequence> VERSION_ORDER = new Comparator<CharSequence>() {
@Override
public int compare (CharSequence lhs, CharSequence rhs) {
int ll = lhs.length(), rl = rhs.length(), lv = 0, rv = 0, li = 0, ri = 0;
char c;
do {
lv = rv = 0;
while (--ll >= 0) {
c = lhs.charAt(li++);
if (c < '0' || c > '9')
break;
lv = lv*10 + c - '0';
}
while (--rl >= 0) {
c = rhs.charAt(ri++);
if (c < '0' || c > '9')
break;
rv = rv*10 + c - '0';
}
} while (lv == rv && (ll >= 0 || rl >= 0));
return lv - rv;
}
};
Result:
"0.1" - "1.0" = -1
"1.0" - "1.0" = 0
"1.0" - "1.0.0" = 0
"10" - "1.0" = 9
"3.7.6" - "3.7.11" = -5
"foobar" - "1.0" = -1
Swift 4 and above
@IBAction func submitAction(sender: UIButton) {
//declare parameter as a dictionary which contains string as key and value combination. considering inputs are valid
let parameters = ["id": 13, "name": "jack"]
//create the url with URL
let url = URL(string: "www.thisismylink.com/postName.php")! //change the url
//create the session object
let session = URLSession.shared
//now create the URLRequest object using the url object
var request = URLRequest(url: url)
request.httpMethod = "POST" //set http method as POST
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
} catch let error {
print(error.localizedDescription)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//create dataTask using the session object to send data to the server
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
print(json)
// handle json...
}
} catch let error {
print(error.localizedDescription)
}
})
task.resume()
}
You can use sass /sassFile.scss /cssFile.css
Attention: Before using
sass
command you must install ruby and then install sass.For installing sass, after ruby installation type
gem install sass
in your TerminalHint: sass compile
SCSS
files
I think you have added firebase json file "google-services".json with the new file. Make sure to create a new file check the link on how to create json file from firebase and it should match with your package name
Second thing is that if you are changing the package name use the option " replace in path" when you right click under files when you select project from the drop down. You have to search for package name in the whole project and replace it !
Hope this helps !
With ES6 you can now do it like this
Example Codepen URl to load
const iframe = '<iframe height="265" style="width: 100%;" scrolling="no" title="fx." src="//codepen.io/ycw/embed/JqwbQw/?height=265&theme-id=0&default-tab=js,result" frameborder="no" allowtransparency="true" allowfullscreen="true">See the Pen <a href="https://codepen.io/ycw/pen/JqwbQw/">fx.</a> by ycw(<a href="https://codepen.io/ycw">@ycw</a>) on <a href="https://codepen.io">CodePen</a>.</iframe>';
A function component to load Iframe
function Iframe(props) {
return (<div dangerouslySetInnerHTML={ {__html: props.iframe?props.iframe:""}} />);
}
Usage:
import React from "react";
import ReactDOM from "react-dom";
function App() {
return (
<div className="App">
<h1>Iframe Demo</h1>
<Iframe iframe={iframe} />,
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Edit on CodeSandbox:
//JUST ADD urlencode();
$url = urlencode("http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false");
<html>
<head>
<title>Test File</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
</head>
<body>
<?php
$adr = 'Sydney+NSW';
echo $adr;
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=$adr&sensor=false";
echo '<p>'.$url.'</p>';
echo file_get_contents($url);
print '<p>'.file_get_contents($url).'</p>';
$jsonData = file_get_contents($url);
echo $jsonData;
?>
</body>
</html>
You need to specify the column in both expressions.
SELECT * FROM transactions WHERE id NOT LIKE '1%' AND id NOT LIKE '2%'
this.setState({
name:'value'
},() => {
console.log(this.state.name);
});
As explained in other answers, context
is the this
context to be used inside callback passed to each
.
I'll explain this with the help of source code of relevant methods from underscore source code
The definition of _.each
or _.forEach
is as follows:
_.each = _.forEach = function(obj, iteratee, context) {
iteratee = optimizeCb(iteratee, context);
var i, length;
if (isArrayLike(obj)) {
for (i = 0, length = obj.length; i < length; i++) {
iteratee(obj[i], i, obj);
}
} else {
var keys = _.keys(obj);
for (i = 0, length = keys.length; i < length; i++) {
iteratee(obj[keys[i]], keys[i], obj);
}
}
return obj;
};
Second statement is important to note here
iteratee = optimizeCb(iteratee, context);
Here, context
is passed to another method optimizeCb
and the returned function from it is then assigned to iteratee
which is called later.
var optimizeCb = function(func, context, argCount) {
if (context === void 0) return func;
switch (argCount == null ? 3 : argCount) {
case 1:
return function(value) {
return func.call(context, value);
};
case 2:
return function(value, other) {
return func.call(context, value, other);
};
case 3:
return function(value, index, collection) {
return func.call(context, value, index, collection);
};
case 4:
return function(accumulator, value, index, collection) {
return func.call(context, accumulator, value, index, collection);
};
}
return function() {
return func.apply(context, arguments);
};
};
As can be seen from the above method definition of optimizeCb
, if context
is not passed then func
is returned as it is. If context
is passed, callback function is called as
func.call(context, other_parameters);
^^^^^^^
func
is called with call()
which is used to invoke a method by setting this
context of it. So, when this
is used inside func
, it'll refer to context
.
// Without `context`_x000D_
_.each([1], function() {_x000D_
console.log(this instanceof Window);_x000D_
});_x000D_
_x000D_
_x000D_
// With `context` as `arr`_x000D_
var arr = [1, 2, 3];_x000D_
_.each([1], function() {_x000D_
console.log(this);_x000D_
}, arr);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
_x000D_
You can consider context
as the last optional parameter to forEach
in JavaScript.
You can also try my ubuntu repository: https://launchpad.net/~mmk2410/+archive/ubuntu/intellij-idea
To use it just run the following commands:
sudo apt-add-repository ppa:mmk2410/intellij-idea
sudo apt-get update
The community edition can then installed with
sudo apt-get install intellij-idea-community
and the ultimate edition with
sudo apt-get install intellij-idea-ultimate
My dad moved his office after 30 year and they need to update the address in the header of their Crystal Reports 7 (1997!) based billing system.
After buying old copies of Access 97 and Visual Studio 2003 Pro, I found out that both programs were too new - they could open the RPT files, but they saved them with an updated version that would not open in the billing system.
I ended up being able to make the changes using this life-saver program...
http://www.softwareforces.com/Products/rpt-inspector-professional-suite-for-crystal-reports
It was available with a 10 day free trial, and I only needed about 10 minutes to make my changes. That said, I would have happily paid whatever they asked for it. :)
Some hints:
We need to implement two layouts. One to hold listview and another to hold row item of listview. Implement your own custom adapter. Idea is to include one textview and one imageview.
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View single_row = inflater.inflate(R.layout.list_row, null,
true);
TextView textView = (TextView) single_row.findViewById(R.id.textView);
ImageView imageView = (ImageView) single_row.findViewById(R.id.imageView);
textView.setText(color_names[position]);
imageView.setImageResource(image_id[position]);
return single_row;
}
Next we implement functionality in main activity to include images and text data dynamically during runtime. You can pass dynamically created text array and image id array to the constructor of custom adapter.
Customlistadapter adapter = new Customlistadapter(this, image_id, text_name);
Linus' answer to your question is "Because C++ is a horrible language"
His evidence is anecdotal at best, but he has a point..
Being more of a low level language, you would prefer it to C++..C++ is C with added libraries and compiler support for extra features (both languages have features the other language doesn't, and implement things differently), but if you have the time and experience with C, you can benefit from extra added low level related powers...[Edited](because you get used to doing more work manually rather than benefit from some powers coming from the language/compiler itself)
Adding links:
Why are you still using C? PDF
I would google for this.. because there are plenty of commentaries on the web already
CONCAT with a null value returns null, so the easiest solution is:
UPDATE myTable SET spares = IFNULL (CONCAT( spares , "string" ), "string")
If you have or want to keep your elements as variables (jQuery objects), you can also loop over them:
var $class1 = $('.class1');
var $class2 = $('.class2');
$([$class1,$class2]).each(function() {
$(this).on('click', function(e) {
some_function();
});
});
Have a look at this Stack Overflow answer.
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
You can use the method to animate:
I.e.:
var thequerystring = getParameterByName("location");
$('html,body').animate({scrollTop: $("div#" + thequerystring).offset().top}, 500);
"TypeScript Fundamentals" -- a Pluralsight video-course by Dan Wahlin and John Papa is a really good, presently (March 25, 2016) updated to reflect TypeScript 1.8, introduction to Typescript.
For me the really good features, beside the nice possibilities for intellisense, are the classes, interfaces, modules, the ease of implementing AMD, and the possibility to use the Visual Studio Typescript debugger when invoked with IE.
To summarize: If used as intended, Typescript can make JavaScript programming more reliable, and easier. It can increase the productivity of the JavaScript programmer significantly over the full SDLC.
It might be DNS Pollution issue, at least for my case (in China).
If you're also in China or some places that has DNS Pollution issue, you might solve this by modifying the DNS (to 8.8.8.8
as an example) for your Mac as well.
I got this error inner my iPad App & this happens randomly, it's such boring. Keep trying is not a good solution for me, though it might works somehow. Finally, I just changed my Wi-Fi DNS and no more error now. Steps:
8.8.8.8
Now there are a lot of cloud providers , providing solutions like MBaaS (Mobile Backend as a Service). Some only give access to cloud database, some will do the user management for you, some let you place code around cloud database and there are facilities of access control, push notifications, analytics, integrated image and file hosting etc.
Here are some providers which have a "free-tier" (may change in future):
Open source solutions:
In my case (I'm using typescript) I was trying to simulate response with fake data where the data is assigned later on. My first attempt was with:
let response = {status: 200, data: []};
and later, on the assignment of the fake data it starts complaining that it is not assignable to type 'never[]'. Then I defined the response like follows and it accepted it..
let dataArr: MyClass[] = [];
let response = {status: 200, data: dataArr};
and assigning of the fake data:
response.data = fakeData;
After researching for almost 1 month i found the below code which is working very beautifully and 100% perfectly on my website. To check the preview how it is working you can check from the link. https://www.jobsedit.in/state-government-jobs/
CSS CODE-----
@media only screen and (max-width: 500px) {
.resp table {
display: block ;
}
.resp th {
position: absolute;
top: -9999px;
left: -9999px;
display:block ;
}
.resp tr {
border: 1px solid #ccc;
display:block;
}
.resp td {
/* Behave like a "row" */
border: none;
border-bottom: 1px solid #eee;
position: relative;
width:100%;
background-color:White;
text-indent: 50%;
text-align:left;
padding-left: 0px;
display:block;
}
.resp td:nth-child(1) {
border: none;
border-bottom: 1px solid #eee;
position: relative;
font-size:20px;
text-indent: 0%;
text-align:center;
}
.resp td:before {
/* Now like a table header */
position: absolute;
/* Top/left values mimic padding */
top: 6px;
left: 6px;
width: 45%;
text-indent: 0%;
text-align:left;
white-space: nowrap;
background-color:White;
font-weight:bold;
}
/*
Label the data
*/
.resp td:nth-of-type(2):before { content: attr(data-th) }
.resp td:nth-of-type(3):before { content: attr(data-th) }
.resp td:nth-of-type(4):before { content: attr(data-th) }
.resp td:nth-of-type(5):before { content: attr(data-th) }
.resp td:nth-of-type(6):before { content: attr(data-th) }
.resp td:nth-of-type(7):before { content: attr(data-th) }
.resp td:nth-of-type(8):before { content: attr(data-th) }
.resp td:nth-of-type(9):before { content: attr(data-th) }
.resp td:nth-of-type(10):before { content: attr(data-th) }
}
HTML CODE --
<table>
<tr>
<td data-th="Heading 1"></td>
<td data-th="Heading 2"></td>
<td data-th="Heading 3"></td>
<td data-th="Heading 4"></td>
<td data-th="Heading 5"></td>
</tr>
</table>
Using tidyverse/dplyr, you can also remove rows with any zero value in a subset of variables:
# variables starting with Mac must be non-zero
filter_at(df, vars(starts_with("Mac")), all_vars((.) != 0))
# variables x, y, and z must be non-zero
filter_at(df, vars(x, y, z), all_vars((.) != 0))
# all numeric variables must be non-zero
filter_if(df, is.numeric, all_vars((.) != 0))
You need to publish the exposed ports by using the following options:
-P (upper case) or --publish-all that will tell Docker to use random ports from your host and map them to the exposed container's ports.
-p (lower case) or --publish=[] that will tell Docker to use ports you manually set and map them to the exposed container's ports.
The second option is preferred because you already know which ports are mapped. If you use the first option then you will need to call docker inspect demo
and check which random ports are being used from your host at the Ports section.
Just run the following command:
docker run -it -p 8080:8080 demo
After that your url will work.
I improved the code of @JanW as well...
I need it to format results from medical instruments, and they also send ">1000", "23.3e02", "350E-02", and "NEGATIVE".
private string FormatResult(string vResult)
{
string output;
string input = vResult;
// Unify string (no spaces, only .)
output = input.Trim().Replace(" ", "").Replace(",", ".");
// Split it on points
string[] split = output.Split('.');
if (split.Count() > 1)
{
// Take all parts except last
output = string.Join("", split.Take(split.Count() - 1).ToArray());
// Combine token parts with last part
output = string.Format("{0}.{1}", output, split.Last());
}
string sfirst = output.Substring(0, 1);
try
{
if (sfirst == "<" || sfirst == ">")
{
output = output.Replace(sfirst, "");
double res = Double.Parse(output);
return String.Format("{1}{0:0.####}", res, sfirst);
}
else
{
double res = Double.Parse(output);
return String.Format("{0:0.####}", res);
}
}
catch
{
return output;
}
}
In my case it was because I declared a subclass of a subclass of a UITableView cell in the .h file (the declaration of both subclasses were in the same .h file), but forgot to make an empty implementation of that second subclass in the .m file.
don't forget to implement any subclass of a subclass you declare in the .h file! sounds simple, but easy to forget because Xcode will do this for you if you are working with one class per .h/.m file.
From within your batch file:
%cd%
refers to the current working directory (variable)%~dp0
refers to the full path to the batch file's directory (static)%~dpnx0
and %~f0
both refer to the full path to the batch directory and file name (static).INSERT INTO wp_bp_activity
(
user_id,
component,
`type`,
`action`,
content,
primary_link,
item_id,
secondary_item_id,
date_recorded,
hide_sitewide,
mptt_left,
mptt_right
)
VALUES(
1,'activity','activity_update','<a title="admin" href="http://brandnewmusicreleases.com/social-network/members/admin/">admin</a> posted an update','<a title="242925_1" href="http://brandnewmusicreleases.com/social-network/wp-content/uploads/242925_1.jpg" class="buddyboss-pics-picture-link">242925_1</a>','http://brandnewmusicreleases.com/social-network/members/admin/',' ',' ','2012-06-22 12:39:07',0,0,0
)
There is another option not mentioned previously:
Jenkins Pipeline also provides the current build number as the property number
of the currentBuild
. It can be read as currentBuild.number
.
For example:
// Scripted pipeline
def buildNumber = currentBuild.number
// Declarative pipeline
echo "Build number is ${currentBuild.number}"
Other properties of currentBuild
are described in the Pipeline Syntax: Global Variables page that is included on each Pipeline job page. That page describes the global variables available in the Jenkins instance based on the current plugins.
It is working for me
MsgBox(DataGridView1.CurrentRow.Cells(0).Value.ToString)
optionalUsers.orElseThrow(() -> new UsernameNotFoundException("Username not found"));
Try this:
#wrapper {
text-align: center;
}
#wrapper iframe {
display: inline-block;
}
You also can lead your initial string, which you are going to check for pattern matching, to lower case. And use in your pattern lower case symbols respectively.
You've got what rebase
does backwards. git rebase master
does what you're asking for — takes the changes on the current branch (since its divergence from master) and replays them on top of master
, then sets the head of the current branch to be the head of that new history. It doesn't replay the changes from master
on top of the current branch.
You are looking to see if a single value is in an array. Use in_array
.
However note that case is important, as are any leading or trailing spaces. Use var_dump
to find out the length of the strings too, and see if they fit.
Using print function without parentheses works with older versions of Python but is no longer supported on Python3, so you have to put the arguments inside parentheses. However, there are workarounds, as mentioned in the answers to this question. Since the support for Python2 has ended in Jan 1st 2020, the answer has been modified to be compatible with Python3.
You could do any of these (and there may be other ways):
(1) print("First number is {} and second number is {}".format(first, second))
(1b) print("First number is {first} and number is {second}".format(first=first, second=second))
or
(2) print('First number is', first, 'second number is', second)
(Note: A space will be automatically added afterwards when separated from a comma)
or
(3) print('First number %d and second number is %d' % (first, second))
or
(4) print('First number is ' + str(first) + ' second number is' + str(second))
Using format() (1/1b) is preferred where available.
Follow these steps to fix this it looks too long but trust me it won't take more than 5 minutes:
Step-1: Create two ssh key pairs:
ssh-keygen -t rsa -C "[email protected]"
Step-2: It will create two ssh keys here:
~/.ssh/id_rsa_account1
~/.ssh/id_rsa_account2
Step-3: Now we need to add these keys:
ssh-add ~/.ssh/id_rsa_account2
ssh-add ~/.ssh/id_rsa_account1
- You can see the added keys list by using this command:
ssh-add -l
- You can remove old cached keys by this command:
ssh-add -D
Step-4: Modify the ssh config
cd ~/.ssh/
touch config
subl -a config
or code config
or nano config
Step-5: Add this to config file:
#Github account1
Host github.com-account1
HostName github.com
User account1
IdentityFile ~/.ssh/id_rsa_account1
#Github account2
Host github.com-account2
HostName github.com
User account2
IdentityFile ~/.ssh/id_rsa_account2
Step-6: Update your .git/config
file:
Step-6.1: Navigate to account1's project and update host:
[remote "origin"]
url = [email protected]:account1/gfs.git
If you are invited by some other user in their git Repository. Then you need to update the host like this:
[remote "origin"]
url = [email protected]:invitedByUserName/gfs.git
Step-6.2: Navigate to account2's project and update host:
[remote "origin"]
url = [email protected]:account2/gfs.git
Step-7: Update user name and email for each repository separately if required this is not an amendatory step:
Navigate to account1 project and run these:
git config user.name "account1"
git config user.email "[email protected]"
Navigate to account2 project and run these:
git config user.name "account2"
git config user.email "[email protected]"
You can also use a regexp with re.sub
:
article_title_str = re.sub(r'(\s?-?\|?\s?Times of India|\s?-?\|?\s?the Times of India|\s?-?\|?\s+?Gadgets No'',
article_title_str, flags=re.IGNORECASE)
For those looking for a plain JS solution:
let el = document.querySelector("#myElementId");
// including the element's border
let width = el.offsetWidth;
let height = el.offsetHeight;
// not including the element's border:
let width = el.clientWidth;
let height = el.clientHeight;
Check out this article for more details.
The task boils down to iterating over characters of the string and collecting them into a list. The most naïve solution would look like
result = []
for character in string:
result.append(character)
Of course, it can be shortened to just
result = [character for character in string]
but there still are shorter solutions that do the same thing.
list
constructor can be used to convert any iterable (iterators, lists, tuples, string etc.) to list.
>>> list('abc')
['a', 'b', 'c']
The big plus is that it works the same in both Python 2 and Python 3.
Also, starting from Python 3.5 (thanks to the awesome PEP 448) it's now possible to build a list from any iterable by unpacking it to an empty list literal:
>>> [*'abc']
['a', 'b', 'c']
This is neater, and in some cases more efficient than calling list
constructor directly.
I'd advise against using map
-based approaches, because map
does not return a list in Python 3. See How to use filter, map, and reduce in Python 3.
Taking the answer from @jack-allan I modified the function slightly to allow ES6 default properties such as:
function( a, b = 1, c ){};
to still return [ 'a', 'b' ]
/**
* Get the keys of the paramaters of a function.
*
* @param {function} method Function to get parameter keys for
* @return {array}
*/
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var ARGUMENT_NAMES = /(?:^|,)\s*([^\s,=]+)/g;
function getFunctionParameters ( func ) {
var fnStr = func.toString().replace(STRIP_COMMENTS, '');
var argsList = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')'));
var result = argsList.match( ARGUMENT_NAMES );
if(result === null) {
return [];
}
else {
var stripped = [];
for ( var i = 0; i < result.length; i++ ) {
stripped.push( result[i].replace(/[\s,]/g, '') );
}
return stripped;
}
}
Please refer to other answers that are more up-to-date.
This works for me: <div innerHTML = "{{ myVal }}"></div>
(Angular2, Alpha 33)
According to another SO: Inserting HTML from server into DOM with angular2 (general DOM manipulation in Angular2), "inner-html" is equivalent to "ng-bind-html" in Angular 1.X
Nice one, big thanks to Max.
I've wrapped the functionality in his answer into jQuery if anyone wants to use it.
(function($) {
$.fn.getCursorPosition = function() {
var input = this.get(0);
if (!input) return; // No (input) element found
if ('selectionStart' in input) {
// Standard-compliant browsers
return input.selectionStart;
} else if (document.selection) {
// IE
input.focus();
var sel = document.selection.createRange();
var selLen = document.selection.createRange().text.length;
sel.moveStart('character', -input.value.length);
return sel.text.length - selLen;
}
}
})(jQuery);
This is more general than .NET and Windows. Managed is an environment where you have automatic memory management, garbage collection, type safety, ... unmanaged is everything else. So for example .NET is a managed environment and C/C++ is unmanaged.
Adding a FileUpload control from the code behind should work just fine, where the HasFile property should be available (for instance in your Click event).
If the properties don't appear to be available (either as a compiler error or via intellisense), you probably are referencing a different variable than you think you are.
While you really shouldn't use scanf()
for this sort of thing, because there are much better calls such as gets()
or getline()
, it can be done:
#include <stdio.h>
char* scan_line(char* buffer, int buffer_size);
char* scan_line(char* buffer, int buffer_size) {
char* p = buffer;
int count = 0;
do {
char c;
scanf("%c", &c); // scan a single character
// break on end of line, string terminating NUL, or end of file
if (c == '\r' || c == '\n' || c == 0 || c == EOF) {
*p = 0;
break;
}
*p++ = c; // add the valid character into the buffer
} while (count < buffer_size - 1); // don't overrun the buffer
// ensure the string is null terminated
buffer[buffer_size - 1] = 0;
return buffer;
}
#define MAX_SCAN_LENGTH 1024
int main()
{
char s[MAX_SCAN_LENGTH];
printf("Enter a string: ");
scan_line(s, MAX_SCAN_LENGTH);
printf("got: \"%s\"\n\n", s);
return 0;
}
If you want to support more than one space at a time, or support any whitespace, you can do this:
NSString* noSpaces =
[[myString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]
componentsJoinedByString:@""];
Much of the other answers provide shallow sizes - e.g. the size of a HashMap without any of the keys or values, which isn't likely what you want.
The jamm project uses the java.lang.instrumentation package above but walks the tree and so can give you the deep memory use.
new MemoryMeter().measureDeep(myHashMap);
https://github.com/jbellis/jamm
To use MemoryMeter, start the JVM with "-javaagent:/jamm.jar"
It'll have the same behavior as the underlying recv libc call see the man page for an official description of behavior (or read a more general description of the sockets api).