I had to uninstall my anti virus! Before uninstalling I clicked on the option where it said to disable auto-protect for 15 min. I also clicked on another option that supposibly disabled the anti-virus. That still was blocking my server! I don't understand why Norton makes it so hard to literally stop doing everything it's doing. I know I could had solve it by adding an exception to the firewall but Norton was taking care of windows firewall as well.
I just checked the status of the response object:
$promise.then( function successCallback(response) {
console.log(response);
if (response.status === 200) { ... }
});
Have you taken a look at this Java Tutorial?
Further, I'd advise you to stay the heck away from playing with this kind of stuff in real software. It's good to play with it so you know what it is, but concurrency has pitfalls all over the place. It's better to use higher level abstractions and synchronized collections or JMS queues if you are building software for other people.
That is at least what I do. I'm not a concurrency expert so I stay away from handling threads by hand wherever possible.
There is a fairly well maintained repo on github that has a CSV (with semicolon delimiters), XML, and JSON source of countries, country codes, and other information.
It looks like you were on the right track - get_FOO_display()
is most certainly what you want:
In templates, you don't include ()
in the name of a method. Do the following:
{{ person.get_gender_display }}
When there is no concern about invalid string input or range issues, use the simplest: atoi()
Otherwise, the method with best error/range detection is neither atoi()
, nor sscanf()
.
This good answer all ready details the lack of error checking with atoi()
and some error checking with sscanf()
.
strtol()
is the most stringent function in converting a string to int
. Yet it is only a start. Below are detailed examples to show proper usage and so the reason for this answer after the accepted one.
// Over-simplified use
int strtoi(const char *nptr) {
int i = (int) strtol(nptr, (char **)NULL, 10);
return i;
}
This is the like atoi()
and neglects to use the error detection features of strtol()
.
To fully use strtol()
, there are various features to consider:
Detection of no conversion: Examples: "xyz"
, or ""
or "--0"
? In these cases, endptr
will match nptr
.
char *endptr;
int i = (int)strtol(nptr, &endptr, 10);
if (nptr == endptr) return FAIL_NO_CONVERT;
Should the whole string convert or just the leading portion: Is "123xyz"
OK?
char *endptr;
int i = (int)strtol(nptr, &endptr, 10);
if (*endptr != '\0') return FAIL_EXTRA_JUNK;
Detect if value was so big, the the result is not representable as a long
like "999999999999999999999999999999"
.
errno = 0;
long L = strtol(nptr, &endptr, 10);
if (errno == ERANGE) return FAIL_OVERFLOW;
Detect if the value was outside the range of than int
, but not long
. If int
and long
have the same range, this test is not needed.
long L = strtol(nptr, &endptr, 10);
if (L < INT_MIN || L > INT_MAX) return FAIL_INT_OVERFLOW;
Some implementations go beyond the C standard and set errno
for additional reasons such as errno to EINVAL in case no conversion was performed or EINVAL
The value of the Base parameter is not valid.. The best time to test for these errno
values is implementation dependent.
Putting this all together: (Adjust to your needs)
#include <errno.h>
#include <stdlib.h>
int strtoi(const char *nptr, int *error_code) {
char *endptr;
errno = 0;
long i = strtol(nptr, &endptr, 10);
#if LONG_MIN < INT_MIN || LONG_MAX > INT_MAX
if (errno == ERANGE || i > INT_MAX || i < INT_MIN) {
errno = ERANGE;
i = i > 0 : INT_MAX : INT_MIN;
*error_code = FAIL_INT_OVERFLOW;
}
#else
if (errno == ERANGE) {
*error_code = FAIL_OVERFLOW;
}
#endif
else if (endptr == nptr) {
*error_code = FAIL_NO_CONVERT;
} else if (*endptr != '\0') {
*error_code = FAIL_EXTRA_JUNK;
} else if (errno) {
*error_code = FAIL_IMPLEMENTATION_REASON;
}
return (int) i;
}
Note: All functions mentioned allow leading spaces, an optional leading sign character and are affected by locale change. Additional code is required for a more restrictive conversion.
Note: Non-OP title change skewed emphasis. This answer applies better to original title "convert string to integer sscanf or atoi"
In all schemas:
=> \dt *.*
In a particular schema:
=> \dt public.*
It is possible to use regular expressions with some restrictions
\dt (public|s).(s|t)
List of relations
Schema | Name | Type | Owner
--------+------+-------+-------
public | s | table | cpn
public | t | table | cpn
s | t | table | cpn
Advanced users can use regular-expression notations such as character classes, for example [0-9] to match any digit. All regular expression special characters work as specified in Section 9.7.3, except for
.
which is taken as a separator as mentioned above,*
which is translated to the regular-expression notation.*
,?
which is translated to.
, and$
which is matched literally. You can emulate these pattern characters at need by writing?
for.
,(R+|)
forR*
, or(R|)
forR?
.$
is not needed as a regular-expression character since the pattern must match the whole name, unlike the usual interpretation of regular expressions (in other words,$
is automatically appended to your pattern). Write*
at the beginning and/or end if you don't wish the pattern to be anchored. Note that within double quotes, all regular expression special characters lose their special meanings and are matched literally. Also, the regular expression special characters are matched literally in operator name patterns (i.e., the argument of\do
).
In Turkish language, mb_convert_encoding or any other charset conversion did not work.
And also urlencode did not work because of space char converted to + char. It must be %20 for percent encoding.
This one worked!
$url = rawurlencode($url);
$url = str_replace("%3A", ":", $url);
$url = str_replace("%2F", "/", $url);
$data = file_get_contents($url);
If both columns can contain NULL
, but you still want to merge them to a single string, the easiest solution is to use CONCAT_WS():
SELECT FirstName AS First_Name
, LastName AS Last_Name
, CONCAT_WS('', ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone
FROM TABLE1
This way you won't have to check for NULL
-ness of each column separately.
Alternatively, if both columns are actually defined as NOT NULL
, CONCAT() will be quite enough:
SELECT FirstName AS First_Name
, LastName AS Last_Name
, CONCAT(ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone
FROM TABLE1
As for COALESCE
, it's a bit different beast: given the list of arguments, it returns the first that's not NULL
.
OSX's Python binary (version 2) is located at /usr/bin/python
if you use which python
it will tell you where the python
command is being resolved to. Typically, what happens is third parties redefine things in /usr/local/bin
(which takes precedence, by default over /usr/bin
). To fix, you can either run /usr/bin/python
directly to use 2.x or find the errant redefinition (probably in /usr/local/bin
or somewhere else in your PATH
)
Actually you are right: it runs another instance of make. A possible solution would be:
.PHONY : clearscr fresh clean all
all :
compile executable
clean :
rm -f *.o $(EXEC)
fresh : clean clearscr all
clearscr:
clear
By calling make fresh
you get first the clean
target, then the clearscreen
which runs clear
and finally all
which does the job.
EDIT Aug 4
What happens in the case of parallel builds with make’s -j
option?
There's a way of fixing the order. From the make manual, section 4.2:
Occasionally, however, you have a situation where you want to impose a specific ordering on the rules to be invoked without forcing the target to be updated if one of those rules is executed. In that case, you want to define order-only prerequisites. Order-only prerequisites can be specified by placing a pipe symbol (|) in the prerequisites list: any prerequisites to the left of the pipe symbol are normal; any prerequisites to the right are order-only: targets : normal-prerequisites | order-only-prerequisites
The normal prerequisites section may of course be empty. Also, you may still declare multiple lines of prerequisites for the same target: they are appended appropriately. Note that if you declare the same file to be both a normal and an order-only prerequisite, the normal prerequisite takes precedence (since they are a strict superset of the behavior of an order-only prerequisite).
Hence the makefile becomes
.PHONY : clearscr fresh clean all
all :
compile executable
clean :
rm -f *.o $(EXEC)
fresh : | clean clearscr all
clearscr:
clear
EDIT Dec 5
It is not a big deal to run more than one makefile instance since each command inside the task will be a sub-shell anyways. But you can have reusable methods using the call function.
log_success = (echo "\x1B[32m>> $1\x1B[39m")
log_error = (>&2 echo "\x1B[31m>> $1\x1B[39m" && exit 1)
install:
@[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
command1 # this line will be a subshell
command2 # this line will be another subshell
@command3 # Use `@` to hide the command line
$(call log_error, "It works, yey!")
uninstall:
@[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
....
$(call log_error, "Nuked!")
Adding "user instance=False" to connection string solved the problem for me.
<connectionStrings>
<add name="NorthwindEntities" connectionString="metadata=res://*/Models.Northwind.csdl|res://*/Models.Northwind.ssdl|res://*/Models.Northwind.msl;provider=System.Data.SqlClient;provider connection string="data source=.\SQLEXPRESS2008R2;attachdbfilename=|DataDirectory|\Northwind.mdf;integrated security=True;user instance=False;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
In a linked question, there's some Objective-C code to get the mime type for a file URL. I've created a Swift extension based on that Objective-C code to get the mime type:
import Foundation
import MobileCoreServices
extension URL {
var mimeType: String? {
guard self.pathExtension.count != 0 else {
return nil
}
let pathExtension = self.pathExtension as CFString
if let preferredIdentifier = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil) {
guard let mimeType = UTTypeCopyPreferredTagWithClass(preferredIdentifier.takeRetainedValue(), kUTTagClassMIMEType) else {
return nil
}
return mimeType.takeRetainedValue() as String
}
return nil
}
}
try this solution and it is working fine for me
## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>
<IfModule mod_headers.c>
<FilesMatch "\.(js|css|xml|gz)$">
Header append Vary: Accept-Encoding
</FilesMatch>
</IfModule>
<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>
<IfModule mod_deflate.c>
SetOutputFilter DEFLATE
AddOutputFilterByType DEFLATE text/html text/css text/plain text/xml text/x-js text/js
</IfModule>
## EXPIRES CACHING ##
It is a library from SSL. You need to install openssl.
You might also meet missing readline()
function in python. You have to install pyreadline Lib.
Try this , its working and simple
HTML
?????????????????????<html>
<head></head>
<body>
<div class="forum">
test
</div>
</body>
</html>?????????????????????????????????????????????
Javascript
$(document).ready(function() {
var colorOrig=$(".forum").css('background-color');
$(".forum").hover(
function() {
//mouse over
$(this).css('background', '#ff0')
}, function() {
//mouse out
$(this).css('background', colorOrig)
});
});?
css ?
.forum{
background:#f0f;
}?
live demo
You can initialize the values as empty strings and fill them in later as they are found.
dictionary = {'one':'','two':''}
dictionary['one']=1
dictionary['two']=2
Use 'a'
, 'a'
means append
. Anything written to a file opened with 'a'
attribute is written at the end of the file.
with open('file.txt', 'a') as file:
file.write('input')
h = ['a','b','c','d','e','f']
g = ''
for f in h:
g = g + f
>>> g
'abcdef'
If you want to check for false and alert if not, then no there isn't.
If you use if(val)
, then anything that evaluates to 'truthy', like a non-empty string, will also pass. So it depends on how stringent your criterion is. Using ===
and !==
is generally considered good practice, to avoid accidentally matching truthy or falsy conditions via JavaScript's implicit boolean tests.
none of these methods worked for me, so I just solved this with CSS:
.upvotes:before {
content:"";
float: left;
width: 100%;
height: 100%;
position: absolute;
left: 0;
top: 0;
}
use a negative character class:
[^,;]+
For Python 3.x
import urllib.request
from urllib.error import HTTPError
try:
urllib.request.urlretrieve(url, fullpath)
except urllib.error.HTTPError as err:
print(err.code)
var text = "" &<>";
text = text.replaceHtmlEntites();
String.prototype.replaceHtmlEntites = function() {
var s = this;
var translate_re = /&(nbsp|amp|quot|lt|gt);/g;
var translate = {"nbsp": " ","amp" : "&","quot": "\"","lt" : "<","gt" : ">"};
return ( s.replace(translate_re, function(match, entity) {
return translate[entity];
}) );
};
try this.....this worked for me
VUE_APP_API_ENDPOINT ='http://localtest.me:8000'
axios.defaults.baseURL = process.env.VUE_APP_API_ENDPOINT
And that's it. Axios default base Url is replaced with build mode specific API endpoint. If you need specific baseURL for specific request, do it like this:
this.$axios({ url: 'items', baseURL: 'http://new-url.com' })
Matplolib now allows for 'annotation lines' as the OP was seeking. The annotate()
function allows several forms of connecting paths and a headless and tailess arrow, i.e., a simple line, is one of them.
ax.annotate("",
xy=(0.2, 0.2), xycoords='data',
xytext=(0.8, 0.8), textcoords='data',
arrowprops=dict(arrowstyle="-",
connectionstyle="arc3, rad=0"),
)
In the documentation it says you can draw only an arrow with an empty string as the first argument.
From the OP's example:
%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(5)
x = np.arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
plt.plot(x, y, "o")
# draw vertical line from (70,100) to (70, 250)
plt.annotate("",
xy=(70, 100), xycoords='data',
xytext=(70, 250), textcoords='data',
arrowprops=dict(arrowstyle="-",
connectionstyle="arc3,rad=0."),
)
# draw diagonal line from (70, 90) to (90, 200)
plt.annotate("",
xy=(70, 90), xycoords='data',
xytext=(90, 200), textcoords='data',
arrowprops=dict(arrowstyle="-",
connectionstyle="arc3,rad=0."),
)
plt.show()
Just as in the approach in gcalmettes's answer, you can choose the color, line width, line style, etc..
Here is an alteration to a portion of the code that would make one of the two example lines red, wider, and not 100% opaque.
# draw vertical line from (70,100) to (70, 250)
plt.annotate("",
xy=(70, 100), xycoords='data',
xytext=(70, 250), textcoords='data',
arrowprops=dict(arrowstyle="-",
edgecolor = "red",
linewidth=5,
alpha=0.65,
connectionstyle="arc3,rad=0."),
)
You can also add curve to the connecting line by adjusting the connectionstyle
.
Not necessary to use \restylefloat
and destroys other options, like caption placement. just use [H]
or [!h]
after \begin{table}
.
If you just want to show label below the marker, then you can extend google maps Marker to add a setter method for label and you can define the label object by extending google maps overlayView like this..
<script type="text/javascript">
var point = { lat: 22.5667, lng: 88.3667 };
var markerSize = { x: 22, y: 40 };
google.maps.Marker.prototype.setLabel = function(label){
this.label = new MarkerLabel({
map: this.map,
marker: this,
text: label
});
this.label.bindTo('position', this, 'position');
};
var MarkerLabel = function(options) {
this.setValues(options);
this.span = document.createElement('span');
this.span.className = 'map-marker-label';
};
MarkerLabel.prototype = $.extend(new google.maps.OverlayView(), {
onAdd: function() {
this.getPanes().overlayImage.appendChild(this.span);
var self = this;
this.listeners = [
google.maps.event.addListener(this, 'position_changed', function() { self.draw(); })];
},
draw: function() {
var text = String(this.get('text'));
var position = this.getProjection().fromLatLngToDivPixel(this.get('position'));
this.span.innerHTML = text;
this.span.style.left = (position.x - (markerSize.x / 2)) - (text.length * 3) + 10 + 'px';
this.span.style.top = (position.y - markerSize.y + 40) + 'px';
}
});
function initialize(){
var myLatLng = new google.maps.LatLng(point.lat, point.lng);
var gmap = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 5,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var myMarker = new google.maps.Marker({
map: gmap,
position: myLatLng,
label: 'Hello World!',
draggable: true
});
}
</script>
<style>
.map-marker-label{
position: absolute;
color: blue;
font-size: 16px;
font-weight: bold;
}
</style>
This will work.
wrap button inside <div class="text-xs-center">
<div class="text-xs-center">
<v-btn primary>
Signup
</v-btn>
</div>
Dev uses it in his examples.
For centering buttons in v-card-actions
we can add class="justify-center"
(note in v2 class is text-center
(so without xs
):
<v-card-actions class="justify-center">
<v-btn>
Signup
</v-btn>
</v-card-actions>
For more examples with regards to centering see here
If your static URL is correct but still:
Not found: /static/css/main.css
Perhaps your WSGI problem.
? Config WSGI serves both development env and production env
==========================project/project/wsgi.py==========================
import os
from django.conf import settings
from django.contrib.staticfiles.handlers import StaticFilesHandler
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
if settings.DEBUG:
application = StaticFilesHandler(get_wsgi_application())
else:
application = get_wsgi_application()
For me, i make JavaScript redirection to another page to get rid of #_=_
. The ideas below should work. :)
function redirect($url){
echo "<script>window.location.href='{$url}?{$_SERVER["QUERY_STRING"]}'</script>";
}
The Provider piece must be Provider=Microsoft.ACE.OLEDB.12.0
if your target database is ACCDB format. Provider=Microsoft.Jet.OLEDB.4.0
only works for the older MDB format.
You shouldn't even need Access installed if you're running 32 bit Windows. Jet 4 is included as part of the operating system. If you're using 64 bit Windows, Jet 4 is not included, but you still wouldn't need Access itself installed. You can install the Microsoft Access Database Engine 2010 Redistributable. Make sure to download the matching version (AccessDatabaseEngine.exe for 32 bit Windows, or AccessDatabaseEngine_x64.exe for 64 bit).
You can avoid the issue about which ADO version reference by using late binding, which doesn't require any reference.
Dim conn As Object
Set conn = CreateObject("ADODB.Connection")
Then assign your ConnectionString property to the conn object. Here is a quick example which runs from a code module in Excel 2003 and displays a message box with the row count for MyTable. It uses late binding for the ADO connection and recordset objects, so doesn't require setting a reference.
Public Sub foo()
Dim cn As Object
Dim rs As Object
Dim strSql As String
Dim strConnection As String
Set cn = CreateObject("ADODB.Connection")
strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\Access\webforums\whiteboard2003.mdb"
strSql = "SELECT Count(*) FROM MyTable;"
cn.Open strConnection
Set rs = cn.Execute(strSql)
MsgBox rs.fields(0) & " rows in MyTable"
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
If this answer doesn't resolve the problem, edit your question to show us the full connection string you're trying to use and the exact error message you get in response for that connection string.
When we say
width:auto;
width will never exceed the total width of parent element. Maximum width is it's parent width. Even if we add border, padding and margin, content of element itself will become smaller in order to give space for border, padding and margin. In case if space required for border + padding + margin is greater than total width of parent element then width of content will become zero.
When we say
width:100%;
width of content of element will become 100% of parent element and from now if we add border, padding or margin then it will cause child element to exceed parent element's width and it will starts overflowing out of parent element.
Webkit's support for scrollbars is quite sophisticated. This CSS gives a very minimal scrollbar, with a light grey track and a darker thumb:
::-webkit-scrollbar
{
width: 12px; /* for vertical scrollbars */
height: 12px; /* for horizontal scrollbars */
}
::-webkit-scrollbar-track
{
background: rgba(0, 0, 0, 0.1);
}
::-webkit-scrollbar-thumb
{
background: rgba(0, 0, 0, 0.5);
}
This answer is a fantastic source of additional information.
A SOAP request is an XML file consisting of the parameters you are sending to the server.
The SOAP response is equally an XML file, but now with everything the service wants to give you.
Basically the WSDL is a XML file that explains the structure of those two XML.
To implement simple SOAP clients in Java, you can use the SAAJ framework (it is shipped with JSE 1.6 and above):
SOAP with Attachments API for Java (SAAJ) is mainly used for dealing directly with SOAP Request/Response messages which happens behind the scenes in any Web Service API. It allows the developers to directly send and receive soap messages instead of using JAX-WS.
See below a working example (run it!) of a SOAP web service call using SAAJ. It calls this web service.
import javax.xml.soap.*;
public class SOAPClientSAAJ {
// SAAJ - SOAP Client Testing
public static void main(String args[]) {
/*
The example below requests from the Web Service at:
http://www.webservicex.net/uszip.asmx?op=GetInfoByCity
To call other WS, change the parameters below, which are:
- the SOAP Endpoint URL (that is, where the service is responding from)
- the SOAP Action
Also change the contents of the method createSoapEnvelope() in this class. It constructs
the inner part of the SOAP envelope that is actually sent.
*/
String soapEndpointUrl = "http://www.webservicex.net/uszip.asmx";
String soapAction = "http://www.webserviceX.NET/GetInfoByCity";
callSoapWebService(soapEndpointUrl, soapAction);
}
private static void createSoapEnvelope(SOAPMessage soapMessage) throws SOAPException {
SOAPPart soapPart = soapMessage.getSOAPPart();
String myNamespace = "myNamespace";
String myNamespaceURI = "http://www.webserviceX.NET";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration(myNamespace, myNamespaceURI);
/*
Constructed SOAP Request Message:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:myNamespace="http://www.webserviceX.NET">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<myNamespace:GetInfoByCity>
<myNamespace:USCity>New York</myNamespace:USCity>
</myNamespace:GetInfoByCity>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
*/
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("GetInfoByCity", myNamespace);
SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("USCity", myNamespace);
soapBodyElem1.addTextNode("New York");
}
private static void callSoapWebService(String soapEndpointUrl, String soapAction) {
try {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(soapAction), soapEndpointUrl);
// Print the SOAP Response
System.out.println("Response SOAP Message:");
soapResponse.writeTo(System.out);
System.out.println();
soapConnection.close();
} catch (Exception e) {
System.err.println("\nError occurred while sending SOAP Request to Server!\nMake sure you have the correct endpoint URL and SOAPAction!\n");
e.printStackTrace();
}
}
private static SOAPMessage createSOAPRequest(String soapAction) throws Exception {
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
createSoapEnvelope(soapMessage);
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", soapAction);
soapMessage.saveChanges();
/* Print the request message, just for debugging purposes */
System.out.println("Request SOAP Message:");
soapMessage.writeTo(System.out);
System.out.println("\n");
return soapMessage;
}
}
We can use Angular event bindings to respond to any DOM event. The syntax is simple. We surround the DOM event name in parentheses and assign a quoted template statement to it. -- reference
Since change
is on the list of standard DOM events, we can use it:
(change)="saverange()"
In your particular case, since you're using NgModel, you could break up the two-way binding like this instead:
[ngModel]="range" (ngModelChange)="saverange($event)"
Then
saverange(newValue) {
this.range = newValue;
this.Platform.ready().then(() => {
this.rootRef.child("users").child(this.UserID).child('range').set(this.range)
})
}
However, with this approach saverange()
is called with every keystroke, so you're probably better off using (change)
.
import os
print os.path.dirname(__file__)
This is strictly not speaking using jQuery, but I have found this method easier than using jQuery. There are probably endless methods of achieving this and many clever ones here, but not all have worked for me. However the following method has always worked and I am passing it one in case it helps someone else.
Three javascript libraries are required, createCookie
, readCookie
and eraseCookie
. These libraries are not mine but I began using them about 5 years ago and don't know their origin.
createCookie = function(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
readCookie = function (name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
eraseCookie = function (name) {
createCookie(name, "", -1);
}
To call them you need to create a small PHP function, normally as part of your support library, as follows:
<?php
function createjavaScriptCookie($sessionVarible) {
$s = "<script>";
$s = $s.'createCookie('. '"'. $sessionVarible
.'",'.'"'.$_SESSION[$sessionVarible].'"'. ',"1"'.')';
$s = $s."</script>";
echo $s;
}
?>
So to use all you now have to include within your index.php file is
$_SESSION["video_dir"] = "/video_dir/";
createjavaScriptCookie("video_dir");
Now in your javascript library.js you can recover the cookie with the following code:
var videoPath = readCookie("video_dir") +'/'+ video_ID + '.mp4';
I hope this helps.
Same solution, but just to remind you: You can define the shadow directly in the storyboard.
Ex:
Hope it help. :)
const unsigned attribName = getname();
const unsigned attribVal = getvalue();
const char *attrName=NULL, *attrVal=NULL;
attrName = (const char*) attribName;
attrVal = (const char*) attribVal;
Unfortunately, there are a lot of misinformation and misconceptions around REST. Not only your question and the answer by @cmd reflect those, but most of the questions and answers related to the subject on Stack Overflow.
SOAP and REST can't be compared directly, since the first is a protocol (or at least tries to be) and the second is an architectural style. This is probably one of the sources of confusion around it, since people tend to call REST any HTTP API that isn't SOAP.
Pushing things a little and trying to establish a comparison, the main difference between SOAP and REST is the degree of coupling between client and server implementations. A SOAP client works like a custom desktop application, tightly coupled to the server. There's a rigid contract between client and server, and everything is expected to break if either side changes anything. You need constant updates following any change, but it's easier to ascertain if the contract is being followed.
A REST client is more like a browser. It's a generic client that knows how to use a protocol and standardized methods, and an application has to fit inside that. You don't violate the protocol standards by creating extra methods, you leverage on the standard methods and create the actions with them on your media type. If done right, there's less coupling, and changes can be dealt with more gracefully. A client is supposed to enter a REST service with zero knowledge of the API, except for the entry point and the media type. In SOAP, the client needs previous knowledge on everything it will be using, or it won't even begin the interaction. Additionally, a REST client can be extended by code-on-demand supplied by the server itself, the classical example being JavaScript code used to drive the interaction with another service on the client-side.
I think these are the crucial points to understand what REST is about, and how it differs from SOAP:
REST is protocol independent. It's not coupled to HTTP. Pretty much like you can follow an ftp link on a website, a REST application can use any protocol for which there is a standardized URI scheme.
REST is not a mapping of CRUD to HTTP methods. Read this answer for a detailed explanation on that.
REST is as standardized as the parts you're using. Security and authentication in HTTP are standardized, so that's what you use when doing REST over HTTP.
REST is not REST without hypermedia and HATEOAS. This means that a client only knows the entry point URI and the resources are supposed to return links the client should follow. Those fancy documentation generators that give URI patterns for everything you can do in a REST API miss the point completely. They are not only documenting something that's supposed to be following the standard, but when you do that, you're coupling the client to one particular moment in the evolution of the API, and any changes on the API have to be documented and applied, or it will break.
REST is the architectural style of the web itself. When you enter Stack Overflow, you know what a User, a Question and an Answer are, you know the media types, and the website provides you with the links to them. A REST API has to do the same. If we designed the web the way people think REST should be done, instead of having a home page with links to Questions and Answers, we'd have a static documentation explaining that in order to view a question, you have to take the URI stackoverflow.com/questions/<id>
, replace id with the Question.id and paste that on your browser. That's nonsense, but that's what many people think REST is.
This last point can't be emphasized enough. If your clients are building URIs from templates in documentation and not getting links in the resource representations, that's not REST. Roy Fielding, the author of REST, made it clear on this blog post: REST APIs must be hypertext-driven.
With the above in mind, you'll realize that while REST might not be restricted to XML, to do it correctly with any other format you'll have to design and standardize some format for your links. Hyperlinks are standard in XML, but not in JSON. There are draft standards for JSON, like HAL.
Finally, REST isn't for everyone, and a proof of that is how most people solve their problems very well with the HTTP APIs they mistakenly called REST and never venture beyond that. REST is hard to do sometimes, especially in the beginning, but it pays over time with easier evolution on the server side, and client's resilience to changes. If you need something done quickly and easily, don't bother about getting REST right. It's probably not what you're looking for. If you need something that will have to stay online for years or even decades, then REST is for you.
I know this is a really old question, but in case someone is looking for the newer way to do this, use the spring util namespace:
<util:constant static-field="my.pkg.types.MyEnumType.TYPE1" />
As described in the spring documentation.
In my case, I was getting this error because I had an input named x
and I was creating (without realizing it) a local variable called x
. I thought I was trying to access an element of the input x
(which was an array), while I was actually trying to access an element of the local variable x
(which was a scalar).
Better to use arc4random_uniform
. However, this isn't available below iOS 4.3. Luckily iOS will bind this symbol at runtime, not at compile time (so don't use the #if preprocessor directive to check if it's available).
The best way to determine if arc4random_uniform
is available is to do something like this:
#include <stdlib.h>
int r = 0;
if (arc4random_uniform != NULL)
r = arc4random_uniform (74);
else
r = (arc4random() % 74);
double myDouble = 420.5;
//Type cast double to int
int i = (int)myDouble;
System.out.println(i);
The double value is 420.5 and the application prints out the integer value of 420
I use code below:
var fileSplit = filename.split('.');
var fileExt = '';
if (fileSplit.length > 1) {
fileExt = fileSplit[fileSplit.length - 1];
}
return fileExt;
Use font
property of UILabel
:
label.font = UIFont(name:"HelveticaNeue-Bold", size: 16.0)
or use default system font
to bold text:
label.font = UIFont.boldSystemFont(ofSize: 16.0)
This would be more performant than trimming the whole string, since you only need to check for at least a single non-space character existing
// Strempty checks whether string contains only whitespace or not
func Strempty(s string) bool {
if len(s) == 0 {
return true
}
r := []rune(s)
l := len(r)
for l > 0 {
l--
if !unicode.IsSpace(r[l]) {
return false
}
}
return true
}
You can't redirect to a function. What you can do is pass some flag on the URL when redirecting, then check that flag in the server side code and if raised, execute the function.
For example:
document.location = "MyPage.php?action=DoThis";
Then in your PHP code check for "action" in the query string and if equal to "DoThis" execute whatever function you need.
Here is my copen pen on how to make fixed table header with scrollable rows and columns. The columns are also been fixed width, http://codepen.io/abhilashn/pen/GraJyp
<!-- Listing table -->
<div class="row">
<div class="col-sm-12">
<div class="cust-table-cont">
<div class="table-responsive">
<table border="0" class="table cust-table">
<thead>
<tr style="">
<th style="width:80px;">#</th>
<th style="width:150px;" class="text-center"><li class="fa fa-gear"></li></th>
<th style="width:250px;">Title</th>
<th style="width:200px;">Company</th>
<th style="width:100px;">Priority</th>
<th style="width:120px;">Type</th>
<th style="width:150px;">Assigned to</th>
<th style="width:120px;">Status</th>
</tr>
</thead>
<tbody>
<tr>
<th style="width:80px;">1</th>
<td style="width:150px;" class="text-center"><button class="btn btn-outline-danger del-icon"><span class="fa fa-trash-o"></span></button> <button class="btn btn-outline-success"><span class="fa fa-pencil"></span></button></td>
<td style="width:250px;">Lorem ipsum dolor sit</td>
<td style="width:200px;">lorem ispusm</td>
<td style="width:100px;">high</td>
<td style="width:120px;">lorem ipsum</td>
<td style="width:150px;">lorem ipsum</td>
<td style="width:120px;">lorem ipsum</td>
</tr>
<tr>
<th scope="row">2</th>
<td class="text-center"><button class="btn btn-outline-danger del-icon"><span class="fa fa-trash-o"></span></button> <button class="btn btn-outline-success"><span class="fa fa-pencil"></span></button></td>
<td>Lorem ipsum dolor sit</td>
<td>lorem ispusm</td>
<td>high</td>
<td>lorem ipsum</td>
<td>lorem ipsum</td>
<td>lorem ipsum</td>
</tr>
<tr>
<th scope="row">3</th>
<td class="text-center"><button class="btn btn-outline-danger del-icon"><span class="fa fa-trash-o"></span></button> <button class="btn btn-outline-success"><span class="fa fa-pencil"></span></button></td>
<td>Lorem ipsum dolor sit</td>
<td>lorem ispusm</td>
<td>high</td>
<td>lorem ipsum</td>
<td>lorem ipsum</td>
<td>lorem ipsum</td>
</tr>
<tr>
<th scope="row">4</th>
<td class="text-center"><button class="btn btn-outline-danger del-icon"><span class="fa fa-trash-o"></span></button> <button class="btn btn-outline-success"><span class="fa fa-pencil"></span></button></td>
<td>Lorem ipsum dolor sit</td>
<td>lorem ispusm</td>
<td>high</td>
<td>lorem ipsum</td>
<td>lorem ipsum</td>
<td>lorem ipsum</td>
</tr>
<tr>
<th scope="row">5</th>
<td class="text-center"><button class="btn btn-outline-danger del-icon"><span class="fa fa-trash-o"></span></button> <button class="btn btn-outline-success"><span class="fa fa-pencil"></span></button></td>
<td>Lorem ipsum dolor sit</td>
<td>lorem ispusm</td>
<td>high</td>
<td>lorem ipsum</td>
<td>lorem ipsum</td>
<td>lorem ipsum</td>
</tr>
<tr>
<th scope="row">6</th>
<td class="text-center"><button class="btn btn-outline-danger del-icon"><span class="fa fa-trash-o"></span></button> <button class="btn btn-outline-success"><span class="fa fa-pencil"></span></button></td>
<td>Lorem ipsum dolor sit</td>
<td>lorem ispusm</td>
<td>high</td>
<td>lorem ipsum</td>
<td>lorem ipsum</td>
<td>lorem ipsum</td>
</tr>
<tr>
<th scope="row">7</th>
<td class="text-center"><button class="btn btn-outline-danger del-icon"><span class="fa fa-trash-o"></span></button> <button class="btn btn-outline-success"><span class="fa fa-pencil"></span></button></td>
<td>Lorem ipsum dolor sit</td>
<td>lorem ispusm</td>
<td>high</td>
<td>lorem ipsum</td>
<td>lorem ipsum</td>
<td>lorem ipsum</td>
</tr>
<tr>
<th scope="row">8</th>
<td class="text-center"><button class="btn btn-outline-danger del-icon"><span class="fa fa-trash-o"></span></button> <button class="btn btn-outline-success"><span class="fa fa-pencil"></span></button></td>
<td>Lorem ipsum dolor sit</td>
<td>lorem ispusm</td>
<td>high</td>
<td>lorem ipsum</td>
<td>lorem ipsum</td>
<td>lorem ipsum</td>
</tr>
<tr>
<th scope="row">9</th>
<td class="text-center"><button class="btn btn-outline-danger del-icon"><span class="fa fa-trash-o"></span></button> <button class="btn btn-outline-success"><span class="fa fa-pencil"></span></button></td>
<td>Lorem ipsum dolor sit</td>
<td>lorem ispusm</td>
<td>high</td>
<td>lorem ipsum</td>
<td>lorem ipsum</td>
<td>lorem ipsum</td>
</tr>
<tr>
<th scope="row">10</th>
<td class="text-center"><button class="btn btn-outline-danger del-icon"><span class="fa fa-trash-o"></span></button> <button class="btn btn-outline-success"><span class="fa fa-pencil"></span></button></td>
<td>Lorem ipsum dolor sit</td>
<td>lorem ispusm</td>
<td>high</td>
<td>lorem ipsum</td>
<td>lorem ipsum</td>
<td>lorem ipsum</td>
</tr>
<tr>
<th scope="row">11</th>
<td class="text-center"><button class="btn btn-outline-danger del-icon"><span class="fa fa-trash-o"></span></button> <button class="btn btn-outline-success"><span class="fa fa-pencil"></span></button></td>
<td>Lorem ipsum dolor sit</td>
<td>lorem ispusm</td>
<td>high</td>
<td>lorem ipsum</td>
<td>lorem ipsum</td>
<td>lorem ipsum</td>
</tr>
<tr>
<th scope="row">12</th>
<td class="text-center"><button class="btn btn-outline-danger del-icon"><span class="fa fa-trash-o"></span></button> <button class="btn btn-outline-success"><span class="fa fa-pencil"></span></button></td>
<td>Lorem ipsum dolor sit</td>
<td>lorem ispusm</td>
<td>high</td>
<td>lorem ipsum</td>
<td>lorem ipsum</td>
<td>lorem ipsum</td>
</tr>
</tbody>
</table>
</div>
</div> <!-- End of cust-table-cont block -->
</div>
</div> <!-- ENd of row -->
.cust-table-cont { width:100%; overflow-x:auto; } _x000D_
.cust-table-cont .table-responsive { width:1190px; }_x000D_
.cust-table { table-layout:fixed; } _x000D_
.cust-table thead, .cust-table tbody { _x000D_
display: block;_x000D_
}_x000D_
.cust-table tbody { max-height:620px; overflow-y:auto; }
_x000D_
html
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">
Dropdown Example <span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><a href="#">HTML</a></li>
<li><a href="#">CSS</a></li>
<li><a href="#">JavaScript</a></li>
</ul>
</div>
jquery
$(document).ready( function() {
/* $(selector).hover( inFunction, outFunction ) */
$('.dropdown').hover(
function() {
$(this).find('ul').css({
"display": "block",
"margin-top": 0
});
},
function() {
$(this).find('ul').css({
"display": "none",
"margin-top": 0
});
}
);
});
If you need to send the FULL model to the controller, you first need the model to be available to your javascript code.
In our app, we do this with an extension method:
public static class JsonExtensions
{
public static string ToJson(this Object obj)
{
return new JavaScriptSerializer().Serialize(obj);
}
}
On the view, we use it to render the model:
<script type="javascript">
var model = <%= Model.ToJson() %>
</script>
You can then pass the model variable into your $.ajax call.
Add the linked server first with
exec sp_addlinkedserver
@server = 'SNRJDI\SLAMANAGEMENT',
@srvproduct=N'',
@provider=N'SQLNCLI'
# This code works fine in QtSpim simulator
.data
buffer: .space 20
str1: .asciiz "Enter string"
str2: .asciiz "You wrote:\n"
.text
main:
la $a0, str1 # Load and print string asking for string
li $v0, 4
syscall
li $v0, 8 # take in input
la $a0, buffer # load byte space into address
li $a1, 20 # allot the byte space for string
move $t0, $a0 # save string to t0
syscall
la $a0, str2 # load and print "you wrote" string
li $v0, 4
syscall
la $a0, buffer # reload byte space to primary address
move $a0, $t0 # primary address = t0 address (load pointer)
li $v0, 4 # print string
syscall
li $v0, 10 # end program
syscall
The syntax to store the command output into a variable is var=$(command)
.
So you can directly do:
result=$(ls -l | grep -c "rahul.*patle")
And the variable $result
will contain the number of matches.
You can download the 32bit or 64bit version of "Express With Tools" or "SQL Server Management Studio Express" (SSMSE tools only) from:
This link is for SQL Server 2012 Express Service Pack 1 released 11/09/2012 (11.0.3000.00) The original RTM release was 11.0.2100.60 from March or May of 2012.
I just discovered the Hmisc package:
Contains many functions useful for data analysis, high-level graphics, utility operations, functions for computing sample size and power, importing and annotating datasets, imputing missing values, advanced table making, variable clustering, character string manipulation, conversion of R objects to LaTeX and html code, and recoding variables.
library(Hmisc)
plot(...)
minor.tick(nx=10, ny=10) # make minor tick marks (without labels) every 10th
Give a style inside the td element or in your scss file, like this:
vertical-align:
middle;
What about thinking the following way:
So when you have an abstract class Mammals, a subclass Human, and an interface Driving, then you can say
My suggestion is that the book knowledge phrase indicates that he wanted to hear the semantic difference between both (like others here already suggested).
Hopefully I'm understanding your question correctly in that you are wondering about the differences between dispatch_async and dispatch_sync?
dispatch_async
will dispatch the block to a queue asynchronously. Meaning it will send the block to the queue and not wait for it to return before continuing on the execution of the remaining code in your method.
dispatch_sync
will dispatch the block to a queue synchronously. This will prevent any more execution of remaining code in the method until the block has finished executing.
I've mostly used a dispatch_async
to a background queue to get work off the main queue and take advantage of any extra cores that the device may have. Then dispatch_async
to the main thread if I need to update the UI.
Good luck
Easier way:
#required_number = 18
required_number=input("Insert a number: ")
while required_number != 18
print("Oops! Something is wrong")
required_number=input("Try again: ")
if required_number == '18'
print("That's right!")
#continue the code
I found Robert Love's Linux Kernel Development quite interesting. It tells you about how the different subsystems in the Linux kernel works in a very down-to-earth way. Since the source is available Linux is a prime candidate for something to hack on.
Props
props use to pass data in the child component
props change a value outside a component(child component)
State
state use inside a class component
state change a value inside a component
If you render the page, you call setState to update DOM(update page value)
State has an important role in react
you call function on page load time but not call on button event, you will need to call function onclick
event, you may add event inline element style or event bining
function Choice(elem) {_x000D_
var box = document.getElementById("box");_x000D_
if (elem.id == "no") {_x000D_
box.style.backgroundColor = "red";_x000D_
} else if (elem.id == "yes") {_x000D_
box.style.backgroundColor = "green";_x000D_
} else {_x000D_
box.style.backgroundColor = "purple";_x000D_
};_x000D_
};
_x000D_
<div id="box">dd</div>_x000D_
<button id="yes" onclick="Choice(this);">yes</button>_x000D_
<button id="no" onclick="Choice(this);">no</button>_x000D_
<button id="other" onclick="Choice(this);">other</button>
_x000D_
or event binding,
window.onload = function() {_x000D_
var box = document.getElementById("box");_x000D_
document.getElementById("yes").onclick = function() {_x000D_
box.style.backgroundColor = "red";_x000D_
}_x000D_
document.getElementById("no").onclick = function() {_x000D_
box.style.backgroundColor = "green";_x000D_
}_x000D_
}
_x000D_
<div id="box">dd</div>_x000D_
<button id="yes">yes</button>_x000D_
<button id="no">no</button>
_x000D_
The best one I have used and researched on it is $request->merge([])
(Check My Piece of Code):
public function index(Request $request) {
not_permissions_redirect(have_premission(2));
$filters = (!empty($request->all())) ? true : false;
$request->merge(['type' => 'admin']);
$users = $this->service->getAllUsers($request->all());
$roles = $this->roles->getAllAdminRoles();
return view('users.list', compact(['users', 'roles', 'filters']));
}
Check line # 3 inside the index function.
This will round down correctly as well:
>>> n = 46
>>> rem = n % 10
>>> if rem < 5:
... n = int(n / 10) * 10
... else:
... n = int((n + 10) / 10) * 10
...
>>> 50
This is a security feature in Rails. Add this line of code in the form:
<%= hidden_field_tag :authenticity_token, form_authenticity_token %>
Documentation can be found here: http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html
This will drop the outermost level from the hierarchical column index:
df = data.groupby(...).agg(...)
df.columns = df.columns.droplevel(0)
If you'd like to keep the outermost level, you can use the ravel() function on the multi-level column to form new labels:
df.columns = ["_".join(x) for x in df.columns.ravel()]
For example:
import pandas as pd
import pandas.rpy.common as com
import numpy as np
data = com.load_data('Loblolly')
print(data.head())
# height age Seed
# 1 4.51 3 301
# 15 10.89 5 301
# 29 28.72 10 301
# 43 41.74 15 301
# 57 52.70 20 301
df = data.groupby('Seed').agg(
{'age':['sum'],
'height':['mean', 'std']})
print(df.head())
# age height
# sum std mean
# Seed
# 301 78 22.638417 33.246667
# 303 78 23.499706 34.106667
# 305 78 23.927090 35.115000
# 307 78 22.222266 31.328333
# 309 78 23.132574 33.781667
df.columns = df.columns.droplevel(0)
print(df.head())
yields
sum std mean
Seed
301 78 22.638417 33.246667
303 78 23.499706 34.106667
305 78 23.927090 35.115000
307 78 22.222266 31.328333
309 78 23.132574 33.781667
Alternatively, to keep the first level of the index:
df = data.groupby('Seed').agg(
{'age':['sum'],
'height':['mean', 'std']})
df.columns = ["_".join(x) for x in df.columns.ravel()]
yields
age_sum height_std height_mean
Seed
301 78 22.638417 33.246667
303 78 23.499706 34.106667
305 78 23.927090 35.115000
307 78 22.222266 31.328333
309 78 23.132574 33.781667
I tried the initial example (see 7 above) and it did not work in ipython. Note that cmp(obj1,obj2) returns a "1" when implemented using two identical object instances. Oddly enough when I modify one of the attribute values and recompare, using cmp(obj1,obj2) the object continues to return a "1". (sigh...)
Ok, so what you need to do is iterate two objects and compare each attribute using the == sign.
Try this using apache commons:
String src = "Hello"; //This will work with any serialisable object
System.out.println(
"Object Size:" + SerializationUtils.serialize((Serializable) src).length)
Use Query.setParameterList()
, Javadoc here.
There are four variants to pick from.
You can implicitly convert between numerical types, even when that loses precision:
char c = i;
However, you might like to enable compiler warnings to avoid potentially lossy conversions like this. If you do, then use static_cast
for the conversion.
Of the other casts:
dynamic_cast
only works for pointers or references to polymorphic class types;const_cast
can't change types, only const
or volatile
qualifiers;reinterpret_cast
is for special circumstances, converting between pointers or references and completely unrelated types. Specifically, it won't do numeric conversions.static_cast
, const_cast
and reinterpret_cast
is needed to get the job done.The recommended approach in this case is to sort the data in the database, adding an ORDER BY
at the end of the query that fetches the results, something like this:
SELECT temperature FROM temperatures ORDER BY temperature ASC; -- ascending order
SELECT temperature FROM temperatures ORDER BY temperature DESC; -- descending order
If for some reason that is not an option, you can change the sorting order like this in Python:
templist = [25, 50, 100, 150, 200, 250, 300, 33]
sorted(templist, key=int) # ascending order
> [25, 33, 50, 100, 150, 200, 250, 300]
sorted(templist, key=int, reverse=True) # descending order
> [300, 250, 200, 150, 100, 50, 33, 25]
As has been pointed in the comments, the int
key (or float
if values with decimals are being stored) is required for correctly sorting the data if the data received is of type string
, but it'd be very strange to store temperature values as strings, if that is the case, go back and fix the problem at the root, and make sure that the temperatures being stored are numbers.
class Globals {
static String ouch = "I'm global.."
}
println Globals.ouch
As far as I can tell, whether you throw an exception, or you return Request.CreateErrorResponse, the result is the same. If you look at the source code for System.Web.Http.dll, you will see as much. Take a look at this general summary, and a very similar solution that I have made: Web Api, HttpError, and the behavior of exceptions
Presuming 17px header height
List css:
height: 100%;
padding-top: 17px;
Header css:
height: 17px;
float: left;
width: 100%;
Option 3
Iterators are faster than using the get
operation, since the get
operation has to start from the beginning if it has to do some traversal. It probably wouldn't make a difference in an ArrayList, but other data structures could see a noticeable speed difference. This is also compatible with things that aren't lists, like sets.
String[] out = new String[n];
Iterator<String> iterator = in.iterator();
for (int i = 0; i < n && iterator.hasNext(); i++)
out[i] = iterator.next();
Use this:
var arr = $('input:checkbox:checked').map(function () {
return this.value;
}).get();
A one line solution. Add this anywhere before calling the server on the client side:
System.Net.ServicePointManager.ServerCertificateValidationCallback += delegate { return true; };
This should only be used for testing purposes because the client will skip SSL/TLS security checks.
You are actually trying to redirect a page which has some response to throw. So first you keep the information you have throw in a buffer using response.buffer = true
in beginning of the page and then flush it when required using response.flush
this error will get fixed
take a look at this code
<form action="result.php" method="post">
Answer 1 <input type="radio" name="ans" value="ans1" /><br />
Answer 2 <input type="radio" name="ans" value="ans2" /><br />
Answer 3 <input type="radio" name="ans" value="ans3" /><br />
Answer 4 <input type="radio" name="ans" value="ans4" /><br />
<input type="submit" value="submit" />
</form>
php
<?php
if(isset($_POST['submit'])){
if(isset( $_POST['ans'])){
echo "This is the value you are selected".$_POST['ans'];
}
}
?>
Would you want the same form with different parts, showing each part accordingly with a button?
Here an example with three steps, that is, three form parts, but it is expandable to any number of form parts. The HTML characters «
and »
just print respectively « and » which might be interesting for the previous and next button characters.
shows_form_part(1)_x000D_
_x000D_
/* this function shows form part [n] and hides the remaining form parts */_x000D_
function shows_form_part(n){_x000D_
var i = 1, p = document.getElementById("form_part"+1);_x000D_
while (p !== null){_x000D_
if (i === n){_x000D_
p.style.display = "";_x000D_
}_x000D_
else{_x000D_
p.style.display = "none";_x000D_
}_x000D_
i++;_x000D_
p = document.getElementById("form_part"+i);_x000D_
}_x000D_
}_x000D_
_x000D_
/* this is called at the last step using info filled during the previous steps*/_x000D_
function calc_sum() {_x000D_
var sum =_x000D_
parseInt(document.getElementById("num1").value) +_x000D_
parseInt(document.getElementById("num2").value) +_x000D_
parseInt(document.getElementById("num3").value);_x000D_
_x000D_
alert("The sum is: " + sum);_x000D_
}
_x000D_
<div id="form_part1">_x000D_
Part 1<br>_x000D_
<input type="number" value="1" id="num1"><br>_x000D_
<button type="button" onclick="shows_form_part(2)">»</button>_x000D_
</div>_x000D_
_x000D_
<div id="form_part2">_x000D_
Part 2<br>_x000D_
<input type="number" value="2" id="num2"><br>_x000D_
<button type="button" onclick="shows_form_part(1)">«</button>_x000D_
<button type="button" onclick="shows_form_part(3)">»</button>_x000D_
</div>_x000D_
_x000D_
<div id="form_part3">_x000D_
Part 3<br>_x000D_
<input type="number" value="3" id="num3"><br>_x000D_
<button type="button" onclick="shows_form_part(2)">«</button>_x000D_
<button type="button" onclick="calc_sum()">Sum</button>_x000D_
</div>
_x000D_
You can't. Full stop.
switch
is only for integral types, if you want to branch depending on a string you need to use if/else
.
Use which:
set.seed(1)
x <- sample(10, 50, replace = TRUE)
length(which(x > 3 & x < 5))
# [1] 6
1) Go to your Xampp Root folder
For Ex : C:xampp/phpmyadmin/config.inc.php
2) In that find the following :
$cfg['servers'][$i]['password'] = '';
3) Here enter which password you set.
Ex : $cfg['servers'][$i]['password'] = '1234';
4) Then Save it and Restart your Xamp server.
The new version of this should read like so:
xcrun g++ hw.cpp
./a.out
If you are returning ActionResult in .net core web api, or IHttpAction result then you can just wrap up your model in an Ok() method which will match the case on your front end and serialise it for you. No need to use JsonConvert. :)
As others have said, this is bad practice, but if you don't have a choice because you need to integrate with a third-party library that uses the default package, then you could create your own class in the default package and access the other class that way. Classes in the default package basically share a single namespace, so you can access the other class even if it resides in a separate JAR file. Just make sure the JAR file is in the classpath.
This trick doesn't work if your class is not in the default package.
You can run npx webpack
. The npx command, which ships with Node 8.2/npm 5.2.0 or higher, runs the webpack binary (./node_modules/.bin/webpack) of the webpack package.
Source of info: https://webpack.js.org/guides/getting-started/
According to the official ReactJs documentation, you need to pass argument in the default format witch is:
P = {} // default for your props
S = {} // default for yout state
interface Component<P = {}, S = {}> extends ComponentLifecycle<P, S> { }
Or to define your own type like below: (just an exp)
interface IProps {
clients: Readonly<IClientModel[]>;
onSubmit: (data: IClientModel) => void;
}
interface IState {
clients: Readonly<IClientModel[]>;
loading: boolean;
}
class ClientsPage extends React.Component<IProps, IState> {
// ...
}
-vm C:\Program Files\Java\jdk1.6.0_07\bin\javaw.exe
this regex can help you, you should get the first group by \1 or whatever method you have in your language.
href="([^"]*)
example:
<a href="http://www.amghezi.com">amgheziName</a>
result:
http://www.amghezi.com
try below code it will solve your problem.
Configuration configuration = new Configuration().configure("/logic/hibernate.cfg.xml");
I don't know whenever I use "/" in repository name it is replaced by "-" maybe github changed method of creating folders.
So I'm going to tell you what I did to create a empty folder and to add files.
you use that code
ImageView[] ivCard = new ImageView[1];
@override
protected void onCreate(Bundle savedInstanceState)
ivCard[0]=(ImageView)findViewById(R.id.imageView1);
Most of the answers seem to assume that iterative
= for loop
. If your for loop is unrestricted (a la C, you can do whatever you want with your loop counter), then that is correct. If it's a real for
loop (say as in Python or most functional languages where you cannot manually modify the loop counter), then it is not correct.
All (computable) functions can be implemented both recursively and using while
loops (or conditional jumps, which are basically the same thing). If you truly restrict yourself to for loops
, you will only get a subset of those functions (the primitive recursive ones, if your elementary operations are reasonable). Granted, it's a pretty large subset which happens to contain every single function you're likely to encouter in practice.
What is much more important is that a lot of functions are very easy to implement recursively and awfully hard to implement iteratively (manually managing your call stack does not count).
Example working with grouping, union and stuff.
Problem:
$qb = $em->createQueryBuilder()
->select('m.id', 'rm.id')
->from('Model', 'm')
->join('m.relatedModels', 'rm')
->groupBy('m.id');
For this to work possible solution is to use custom hydrator and this weird thing called 'CUSTOM OUTPUT WALKER HINT':
class CountHydrator extends AbstractHydrator
{
const NAME = 'count_hydrator';
const FIELD = 'count';
/**
* {@inheritDoc}
*/
protected function hydrateAllData()
{
return (int)$this->_stmt->fetchColumn(0);
}
}
class CountSqlWalker extends SqlWalker
{
/**
* {@inheritDoc}
*/
public function walkSelectStatement(AST\SelectStatement $AST)
{
return sprintf("SELECT COUNT(*) AS %s FROM (%s) AS t", CountHydrator::FIELD, parent::walkSelectStatement($AST));
}
}
$doctrineConfig->addCustomHydrationMode(CountHydrator::NAME, CountHydrator::class);
// $qb from example above
$countQuery = clone $qb->getQuery();
// Doctrine bug ? Doesn't make a deep copy... (as of "doctrine/orm": "2.4.6")
$countQuery->setParameters($this->getQuery()->getParameters());
// set custom 'hint' stuff
$countQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, CountSqlWalker::class);
$count = $countQuery->getResult(CountHydrator::NAME);
$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark`
ADD COLUMN `ping_status` INT(1) NOT NULL
AFTER `<TABLE COLUMN BEFORE THIS COLUMN>`";
I believe you need to have ADD COLUMN
and use AFTER
, not BEFORE
.
In case you want to place column at the beginning of a table, use the FIRST
statement:
$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark`
ADD COLUMN `ping_status` INT(1) NOT NULL
FIRST";
I allways use UPPER(text)
like UPPER('%blah%')
If you have a more complicated use case than described in the answer of Glennie Helles Sindholt e.g. you have other/few non-join column names that are also same and want to distinguish them while selecting it's best to use aliasses, e.g:
df3 = df1.select("a", "b").alias("left")\
.join(df2.select("a", "b").alias("right"), ["a"])\
.select("left.a", "left.b", "right.b")
df3.columns
['a', 'b', 'b']
Escape special characters with a backslash. \.
, \*
, \+
, \\d
, and so on. If you are unsure, you may escape any non-alphabetical character whether it is special or not. See the javadoc for java.util.regex.Pattern for further information.
I think project size and the number of developers involved are big factors in this. I'm far above this over my career but I've worked alone all that time so there's no loss to working with other programmers.
Not a technology podcast, but I really have to mention FreelanceRadio. A really great and sometimes hilarious resource. I'm listening to them in the morning, on the way to work. And sometimes feel really stupid just giggling by myself :P
You should try something running Mono (its compatible with .NET).
For game development, I recommend unity: http://unity3d.com/
for general aplications: http://xamarin.com/monoforandroid
LEA : just an "arithmetic" instruction..
MOV transfers data between operands but lea is just calculating
Adding strings concatenates them:
> "1" + "1"
"11"
You have to parse them into numbers first:
/* parseFloat is used here.
* Because of it's not known that
* whether the number has fractional places.
*/
var a = parseFloat($('#a').val()),
b = parseFloat($('#b').val());
Also, you have to get the values from inside of the click handler:
$("submit").on("click", function() {
var a = parseInt($('#a').val(), 10),
b = parseInt($('#b').val(), 10);
});
Otherwise, you're using the values of the textboxes from when the page loads.
This is most commonly because it is not found on environment variables as others have pointed out. This is what worked for me.
echo %PATH%
This will show you what's one your PATH environment variable. If node_modules is not there there do the following to add it from your APPDATA path.
PATH = %PATH%; %APPDATA%\npm
I was searching to get a result for this either and I ended up with;
const MyObject = {
SubObject: {
'eu': [0, "asd", true, undefined],
'us': [0, "asd", false, null],
'aus': [0, "asd", false, 0]
}
};
For those who wanted the result as a string:
Object.keys(MyObject.SubObject).toString()
output: "eu,us,aus"
For those who wanted the result as an array:
Array.from(Object.keys(MyObject))
output: Array ["eu", "us", "aus"]
For those who are looking for a "contains" type method: as numeric result:
console.log(Object.keys(MyObject.SubObject).indexOf("k"));
output: -1
console.log(Object.keys(MyObject.SubObject).indexOf("eu"));
output: 0
console.log(Object.keys(MyObject.SubObject).indexOf("us"));
output: 3
as boolean result:
console.log(Object.keys(MyObject.SubObject).includes("eu"));
output: true
In your case;
var myVar = { typeA: { option1: "one", option2: "two" } }_x000D_
_x000D_
// Example 1_x000D_
console.log(Object.keys(myVar.typeA).toString()); // Result: "option1, option2"_x000D_
_x000D_
// Example 2_x000D_
console.log(Array.from(Object.keys(myVar.typeA))); // Result: Array ["option1", "option2" ]_x000D_
_x000D_
// Example 3 as numeric_x000D_
console.log((Object.keys(myVar.typeA).indexOf("option1")>=0)?'Exist!':'Does not exist!'); // Result: Exist!_x000D_
_x000D_
// Example 3 as boolean_x000D_
console.log(Object.keys(myVar.typeA).includes("option2")); // Result: True!_x000D_
_x000D_
// if you would like to know about SubObjects_x000D_
for(var key in myVar){_x000D_
// do smt with SubObject_x000D_
console.log(key); // Result: typeA_x000D_
}_x000D_
_x000D_
// if you already know your "SubObject"_x000D_
for(var key in myVar.typeA){_x000D_
// do smt with option1, option2_x000D_
console.log(key); // Result: option1 // Result: option2_x000D_
}
_x000D_
var path = "path/to/myfile.png?foo=bar#hash";
console.log(
path.replace(/(\?.*)|(#.*)/g, "")
);
for i in ('apple', 'banana', 'carrot'):
fruitdict[i] = locals()[i]
for sub in the_list:
for key in sub:
sub[key] = int(sub[key])
Gives it a casting as an int instead of as a string.
Firstly, just to remind you there is a logical error you better keep result=1 or else your output will be result=0 even after the loop runs.
Secondly you can write it like this:
import sys
def Factorial(n): # Return factorial
result = 0
for i in range (1,n):
result = result * i
print "factorial is ",result
return result
Leaving a line will tell the python shell that the FOR statements have ended. If you have experience using the python shell then you can understand why we have to leave a line.
ES6 is the way of the future.
arr.reduce((a, b) => Math.min(a, b));
I prefer this form because it's easily generalized for other use cases
A simple way to structure ur express app:
In main index.js the following order should be maintained.
all app.set should be first.
all app.use should be second.
followed by other apis with their functions or route-continue in other files
Exapmle
app.use("/password", passwordApi);
app.use("/user", userApi);
app.post("/token", passport.createToken);
app.post("/logout", passport.logout)
Just use:
<?php
include("/path/to/file.html");
?>
That will echo it as well. This also has the benefit of executing any PHP in the file.
If you need to do anything with the contents, use file_get_contents(),
For example,
<?php
$pagecontents = file_get_contents("/path/to/file.html");
echo str_replace("Banana", "Pineapple", $pagecontents);
?>
This doesn't execute code in that file, so be careful if you expect that to work.
I usually use:
include($_SERVER['DOCUMENT_ROOT']."/path/to/file/as/in/url.html");
as then I can move files without breaking the includes.
You can do timer.Interval = timer.Interval
Textarea resize control is available via the CSS3 resize property:
textarea { resize: both; } /* none|horizontal|vertical|both */
textarea.resize-vertical{ resize: vertical; }
textarea.resize-none { resize: none; }
Allowable values self-explanatory: none
(disables textarea resizing), both
, vertical
and horizontal
.
Notice that in Chrome, Firefox and Safari the default is both
.
If you want to constrain the width and height of the textarea element, that's not a problem: these browsers also respect max-height
, max-width
, min-height
, and min-width
CSS properties to provide resizing within certain proportions.
Code example:
#textarea-wrapper {_x000D_
padding: 10px;_x000D_
background-color: #f4f4f4;_x000D_
width: 300px;_x000D_
}_x000D_
_x000D_
#textarea-wrapper textarea {_x000D_
min-height:50px;_x000D_
max-height:120px;_x000D_
width: 290px;_x000D_
}_x000D_
_x000D_
#textarea-wrapper textarea.vertical { _x000D_
resize: vertical;_x000D_
}
_x000D_
<div id="textarea-wrapper">_x000D_
<label for="resize-default">Textarea (default):</label>_x000D_
<textarea name="resize-default" id="resize-default"></textarea>_x000D_
_x000D_
<label for="resize-vertical">Textarea (vertical):</label>_x000D_
<textarea name="resize-vertical" id="resize-vertical" class="vertical">Notice this allows only vertical resize!</textarea>_x000D_
</div>
_x000D_
Sometimes you want to sort an array of objects on an arbitrary value. Since compareTo() always uses the same information about the instance, you might want to use a different technique. One way is to use a standard sorting algorithm. Let's say you have an array of books and you want to sort them on their height, which is stored as an int and accessible through the method getHeight(). Here's how you could sort the books in your array. (If you don't want to change the original array, simply make a copy and sort that.)
`int tallest; // the index of tallest book found thus far
Book temp; // used in the swap
for(int a = 0; a < booksArray.length - 1; a++) {
tallest = a; // reset tallest to current index
// start inner loop at next index
for(int b = a + 1; b < booksArray.length; b++)
// check if the book at this index is taller than the
// tallest found thus far
if(booksArray[b].getHeight() > booksArray[tallest].getHeight())
tallest = b;
// once inner loop is complete, swap the tallest book found with
// the one at the current index of the outer loop
temp = booksArray[a];
booksArray[a] = booksArray[tallest];
booksArray[tallest] = temp;
}`
When this code is done, the array of Book object will be sorted by height in descending order--an interior designer's dream!
The best way in my eyes is to use the concat()
method provided by the String
class itself.
The useage would, in your case, look like this:
String myConcatedString = cursor.getString(numcol).concat('-').
concat(cursor.getString(cursor.getColumnIndexOrThrow(db.KEY_DESTINATIE)));
In some cases you may not be able to suspend, or for that matter take any of the "Power" actions on the VM. You may also already have multiple VMs up and running. Use this process to identify the correct PID to kill.
On Windows 7 - Open Task Manager - Look for processes with the name, "vmware-vmx.exe", note the PIDs.
Switch to the Performance tab and start the "Resource Monitor". Expand the "Disk Activity" panel. Sort the "File" column. Look for the appropriate vmdk file for the VM you want to kill. The "Image" column will have the "vmware-vmx" process listed. Note the PID.
Switch back to the "Processes" tab and kill the PID.
This can be used to download the file to your SD card Tested with Android version 2.3.3 and 4.0.3
======= php =========================
<?php
// this php file (example saved as name is vCardDL.php) is placed in my html subdirectory
//
header('Content-Type: application/octet-stream');
// the above line is needed or else the .vcf file will be downloaded as a .htm file
header('Content-disposition: attachment; filename="xxxxxxxxxx.vcf"');
//
//header('Content-type: application/vcf'); remove this so android doesn't complain that it does not have a valid application
readfile('../aaa/bbb/xxxxxxxxxx.vcf');
//The above is the parth to where the file is located - if in same directory as the php, then just the file name
?>
======= html ========================
<FONT COLOR="#CC0033"><a href="vCardDL.php">Download vCARD</A></FONT>
I know that this has been answered, but it's at least useful to note that you can use:
http://msdn.microsoft.com/en-us/library/system.object.referenceequals.aspx
Which will not give you a "unique id" directly, but combined with WeakReferences (and a hashset?) could give you a pretty easy way of tracking various instances.
As it have been said, the issue comes from a security function of Mac OSX since "El Capitan".
Using the default system Ruby, the install process happens in the /Library/Ruby/Gems/2.0.0
directory which is not available to the user and gives the error.
You can have a look to your Ruby environments parameters with the command
$ gem env
There is an INSTALLATION DIRECTORY and a USER INSTALLATION DIRECTORY. To use the user installation directory instead of the default installation directory, you can use --user-install
parameter instead as using sudo
which is never a recommanded way of doing.
$ gem install myGemName --user-install
There should not be any rights issue anymore in the process. The gems are then installed in the user directory : ~/.gem/Ruby/2.0.0/bin
But to make the installed gems available, this directory should be available in your path. According to the Ruby’s faq, you can add the following line to your ~/.bash_profile
or ~/.bashrc
if which ruby >/dev/null && which gem >/dev/null; then
PATH="$(ruby -rubygems -e 'puts Gem.user_dir')/bin:$PATH"
fi
Then close and reload your terminal or reload your .bash_profile
or .bashrc
(. ~/.bash_profile
)
Not sure what you have tried so far, but its pretty simple. Just do this: http://plnkr.co/edit/kmEWh7?p=preview
html, body {
height: 100%;
}
footer {
position: absolute;
bottom: 0;
}
I've summarised most of the versions in this table. The only ones missing should be ASP.NET Core versions. I've also added different versions of ASP.NET MVC.
Note that ASP.NET 5 has been rebranded as ASP.NET Core 1.0 and ASP.NET MVC 6 has been rebranded as ASP.NET Core MVC 1.0.0. I believe this change occurred sometime around Jan 2016.
I have included the release date of ASP.NET 5 RC1 in the table, but I've yet to include ASP.NET core 1.0 and other core versions, because I couldn't find the exact release dates. You can read more about the release dates regarding ASP.NET Core here: When is ASP.NET Core 1.0 (ASP.NET 5 / vNext) scheduled for release?
The python timedelta library should do what you need. A timedelta
is returned when you subtract two datetime
instances.
import datetime
dt_started = datetime.datetime.utcnow()
# do some stuff
dt_ended = datetime.datetime.utcnow()
print((dt_ended - dt_started).total_seconds())
Instead of "returning true", you can also use the "noop" or null utility (as referred in the POSIX specs) :
and just "do nothing". You'll save a few letters. :)
#!/usr/bin/env bash
set -e
man nonexistentghing || :
echo "It's ok.."
var timedifference = new Date().getTimezoneOffset();
This returns the difference from the clients timezone from UTC time. You can then play around with it as you like.
To replace multiples columns convert to numpy array using .values
:
df.loc[df.A==0, ['B', 'C']] = df.loc[df.A==0, ['B', 'C']].values / 2
If you are on windows you can run this command on cmd:
mklink /j /path/to/laravel/public/avatars /path/to/laravel/storage/avatars
from: http://www.sevenforums.com/tutorials/278262-mklink-create-use-links-windows.html
.htaccess:
php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
php_flag log_errors on
php_value error_log /home/path/public_html/domain/PHP_errors.log
Leonbloy's answer is quite complete. I would only add the special case in which one needs to get the last inserted value from within a PL/pgSQL function where OPTION 3 doesn't fit exactly.
For example, if we have the following tables:
CREATE TABLE person(
id serial,
lastname character varying (50),
firstname character varying (50),
CONSTRAINT person_pk PRIMARY KEY (id)
);
CREATE TABLE client (
id integer,
CONSTRAINT client_pk PRIMARY KEY (id),
CONSTRAINT fk_client_person FOREIGN KEY (id)
REFERENCES person (id) MATCH SIMPLE
);
If we need to insert a client record we must refer to a person record. But let's say we want to devise a PL/pgSQL function that inserts a new record into client but also takes care of inserting the new person record. For that, we must use a slight variation of leonbloy's OPTION 3:
INSERT INTO person(lastname, firstname)
VALUES (lastn, firstn)
RETURNING id INTO [new_variable];
Note that there are two INTO clauses. Therefore, the PL/pgSQL function would be defined like:
CREATE OR REPLACE FUNCTION new_client(lastn character varying, firstn character varying)
RETURNS integer AS
$BODY$
DECLARE
v_id integer;
BEGIN
-- Inserts the new person record and retrieves the last inserted id
INSERT INTO person(lastname, firstname)
VALUES (lastn, firstn)
RETURNING id INTO v_id;
-- Inserts the new client and references the inserted person
INSERT INTO client(id) VALUES (v_id);
-- Return the new id so we can use it in a select clause or return the new id into the user application
RETURN v_id;
END;
$BODY$
LANGUAGE plpgsql VOLATILE;
Now we can insert the new data using:
SELECT new_client('Smith', 'John');
or
SELECT * FROM new_client('Smith', 'John');
And we get the newly created id.
new_client
integer
----------
1
I'm with this error in VS2019 and I think that it starts to occurs when Windows has clock changed.
Use a for loop. There's nothing built into array. Or switch to a java.util Collection class.
Function pointers in C can be used to perform object-oriented programming in C.
For example, the following lines is written in C:
String s1 = newString();
s1->set(s1, "hello");
Yes, the ->
and the lack of a new
operator is a dead give away, but it sure seems to imply that we're setting the text of some String
class to be "hello"
.
By using function pointers, it is possible to emulate methods in C.
How is this accomplished?
The String
class is actually a struct
with a bunch of function pointers which act as a way to simulate methods. The following is a partial declaration of the String
class:
typedef struct String_Struct* String;
struct String_Struct
{
char* (*get)(const void* self);
void (*set)(const void* self, char* value);
int (*length)(const void* self);
};
char* getString(const void* self);
void setString(const void* self, char* value);
int lengthString(const void* self);
String newString();
As can be seen, the methods of the String
class are actually function pointers to the declared function. In preparing the instance of the String
, the newString
function is called in order to set up the function pointers to their respective functions:
String newString()
{
String self = (String)malloc(sizeof(struct String_Struct));
self->get = &getString;
self->set = &setString;
self->length = &lengthString;
self->set(self, "");
return self;
}
For example, the getString
function that is called by invoking the get
method is defined as the following:
char* getString(const void* self_obj)
{
return ((String)self_obj)->internal->value;
}
One thing that can be noticed is that there is no concept of an instance of an object and having methods that are actually a part of an object, so a "self object" must be passed in on each invocation. (And the internal
is just a hidden struct
which was omitted from the code listing earlier -- it is a way of performing information hiding, but that is not relevant to function pointers.)
So, rather than being able to do s1->set("hello");
, one must pass in the object to perform the action on s1->set(s1, "hello")
.
With that minor explanation having to pass in a reference to yourself out of the way, we'll move to the next part, which is inheritance in C.
Let's say we want to make a subclass of String
, say an ImmutableString
. In order to make the string immutable, the set
method will not be accessible, while maintaining access to get
and length
, and force the "constructor" to accept a char*
:
typedef struct ImmutableString_Struct* ImmutableString;
struct ImmutableString_Struct
{
String base;
char* (*get)(const void* self);
int (*length)(const void* self);
};
ImmutableString newImmutableString(const char* value);
Basically, for all subclasses, the available methods are once again function pointers. This time, the declaration for the set
method is not present, therefore, it cannot be called in a ImmutableString
.
As for the implementation of the ImmutableString
, the only relevant code is the "constructor" function, the newImmutableString
:
ImmutableString newImmutableString(const char* value)
{
ImmutableString self = (ImmutableString)malloc(sizeof(struct ImmutableString_Struct));
self->base = newString();
self->get = self->base->get;
self->length = self->base->length;
self->base->set(self->base, (char*)value);
return self;
}
In instantiating the ImmutableString
, the function pointers to the get
and length
methods actually refer to the String.get
and String.length
method, by going through the base
variable which is an internally stored String
object.
The use of a function pointer can achieve inheritance of a method from a superclass.
We can further continue to polymorphism in C.
If for example we wanted to change the behavior of the length
method to return 0
all the time in the ImmutableString
class for some reason, all that would have to be done is to:
length
method.length
method.Adding an overriding length
method in ImmutableString
may be performed by adding an lengthOverrideMethod
:
int lengthOverrideMethod(const void* self)
{
return 0;
}
Then, the function pointer for the length
method in the constructor is hooked up to the lengthOverrideMethod
:
ImmutableString newImmutableString(const char* value)
{
ImmutableString self = (ImmutableString)malloc(sizeof(struct ImmutableString_Struct));
self->base = newString();
self->get = self->base->get;
self->length = &lengthOverrideMethod;
self->base->set(self->base, (char*)value);
return self;
}
Now, rather than having an identical behavior for the length
method in ImmutableString
class as the String
class, now the length
method will refer to the behavior defined in the lengthOverrideMethod
function.
I must add a disclaimer that I am still learning how to write with an object-oriented programming style in C, so there probably are points that I didn't explain well, or may just be off mark in terms of how best to implement OOP in C. But my purpose was to try to illustrate one of many uses of function pointers.
For more information on how to perform object-oriented programming in C, please refer to the following questions:
if you want to get the whole period:
from sqlalchemy import and_, func
query = DBSession.query(User).filter(and_(func.date(User.birthday) >= '1985-01-17'),\
func.date(User.birthday) <= '1988-01-17'))
That means range: 1985-01-17 00:00 - 1988-01-17 23:59
You should not pass the call function hi() to the loop() function, This will give the result.
def hi():
print('hi')
def loop(f, n): #f repeats n times
if n<=0:
return
else:
f()
loop(f, n-1)
loop(hi, 5) # Do not use hi() function inside loop() function
I used the below to solve this problem.
import org.apache.commons.lang.StringUtils;
StringUtils.capitalize(MyString);
Thanks to Ted Hopp for rightly pointing out that the question should have been TITLE CASE instead of modified CAMEL CASE.
Camel Case is usually without spaces between words.
Gooye if it's possible to use Joda Time in your project then this code works for me:
String dateStr = "2012-10-01T09:45:00.000+02:00";
String customFormat = "yyyy-MM-dd HH:mm:ss";
DateTimeFormatter dtf = ISODateTimeFormat.dateTime();
LocalDateTime parsedDate = dtf.parseLocalDateTime(dateStr);
String dateWithCustomFormat = parsedDate.toString(DateTimeFormat.forPattern(customFormat));
System.out.println(dateWithCustomFormat);
Fluid layout in Bootstrap 3.
Unlike Boostrap 2, Bootstrap 3 doesn't have a .container-fluid mixin to make a fluid container. The .container is a fixed width responsive grid layout. In a large screen, there are excessive white spaces in both sides of one's Web page content.
container-fluid
is added back in Bootstrap 3.1
A fluid grid layout uses all screen width and works better in large screen. It turns out that it is easy to create a fluid grid layout using Bootstrap 3 mixins. The following line makes a fluid responsive grid layout:
.container-fixed;
The .container-fixed mixin sets the content to the center of the screen and add paddings. It doesn't specifies a fixed page width.
Another approach is to use Eric Flowers' CSS style
.my-fluid-container {
padding-left: 15px;
padding-right: 15px;
margin-left: auto;
margin-right: auto;
}
$(document).ready(function () {
$('input:radio[name=bedStatus]:checked').change(function () {
if ($("input:radio[name='bedStatus']:checked").val() == 'allot') {
alert("Allot Thai Gayo Bhai");
}
if ($("input:radio[name='bedStatus']:checked").val() == 'transfer') {
alert("Transfer Thai Gayo");
}
});
});
Java:
public static boolean isValidEmail(CharSequence target) {
return (!TextUtils.isEmpty(target) && Patterns.EMAIL_ADDRESS.matcher(target).matches());
}
Kotlin:
fun CharSequence?.isValidEmail() = !isNullOrEmpty() && Patterns.EMAIL_ADDRESS.matcher(this).matches()
Edit: It will work On Android 2.2+ onwards !!
Edit: Added missing ;
As other answers have mentioned, the &&
token in this context is new to C++0x (the next C++ standard) and represent an "rvalue reference".
Rvalue references are one of the more important new things in the upcoming standard; they enable support for 'move' semantics on objects and permit perfect forwarding of function calls.
It's a rather complex topic - one of the best introductions (that's not merely cursory) is an article by Stephan T. Lavavej, "Rvalue References: C++0x Features in VC10, Part 2"
Note that the article is still quite heavy reading, but well worthwhile. And even though it's on a Microsoft VC++ Blog, all (or nearly all) the information is applicable to any C++0x compiler.
The solution found here helped us to update master to a previous commit that had already been pushed:
git checkout master
git reset --hard e3f1e37
git push --force origin e3f1e37:master
The key difference from the accepted answer is the commit hash "e3f1e37:" before master in the push command.
Got this from Bing. Seems Microsoft has removed some features from the core framework and added it to a separate optional(?) framework component.
To quote from MSDN (http://msdn.microsoft.com/en-us/library/cc656912.aspx)
The .NET Framework 4 Client Profile does not include the following features. You must install the .NET Framework 4 to use these features in your application:
* ASP.NET * Advanced Windows Communication Foundation (WCF) functionality * .NET Framework Data Provider for Oracle * MSBuild for compiling
There's a jQuery Timer plugin you may want to try
This code creates the file temp.xls in the desktop but it uses the SpecialFolders property, which is very useful sometimes!
set WshShell = WScript.CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("Desktop")
set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Add()
objWorkbook.SaveAs(strDesktop & "\temp.xls")
Click on the class and press the Alt + Shift + R
keys, then you can change it to the required name and the corresponding file name will also be changed.
You need to set the "default value" for the date field to getdate()
. Any records inserted into the table will automatically have the insertion date as their value for this field.
The location of the "default value" property is dependent on the version of SQL Server Express you are running, but it should be visible if you select the date field of your table when editing the table.
You can use querySelectorAll to get all span elements and then use new ES2015 (ES6) spread operator convert StaticNodeList that querySelectorAll returns to array of spans, and then use map operator to get list of items.
See example bellow
([...document.querySelectorAll('#test span')]).map(x => console.log(x.innerHTML))
_x000D_
<div id="test">_x000D_
<span>1</span>_x000D_
<span>2</span>_x000D_
<span>3</span>_x000D_
<span>4</span>_x000D_
<div>
_x000D_
Here is an example. (I am using CompareToBuilder
class from Apache for convenience, although this can be done without using it.)
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.lang.builder.CompareToBuilder;
public class Tester {
boolean ascending = true;
public static void main(String args[]) {
Tester tester = new Tester();
tester.printValues();
}
public void printValues() {
List<HashMap<String, Object>> list =
new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> map =
new HashMap<String, Object>();
map.put( "actionId", new Integer(1234) );
map.put( "eventId", new Integer(21) );
map.put( "fromDate", getDate(1) );
map.put( "toDate", getDate(7) );
list.add(map);
map = new HashMap<String, Object>();
map.put( "actionId", new Integer(456) );
map.put( "eventId", new Integer(11) );
map.put( "fromDate", getDate(1) );
map.put( "toDate", getDate(1) );
list.add(map);
map = new HashMap<String, Object>();
map.put( "actionId", new Integer(1234) );
map.put( "eventId", new Integer(20) );
map.put( "fromDate", getDate(4) );
map.put( "toDate", getDate(16) );
list.add(map);
map = new HashMap<String, Object>();
map.put( "actionId", new Integer(1234) );
map.put( "eventId", new Integer(22) );
map.put( "fromDate", getDate(8) );
map.put( "toDate", getDate(11) );
list.add(map);
map = new HashMap<String, Object>();
map.put( "actionId", new Integer(1234) );
map.put( "eventId", new Integer(11) );
map.put( "fromDate", getDate(1) );
map.put( "toDate", getDate(10) );
list.add(map);
map = new HashMap<String, Object>();
map.put( "actionId", new Integer(1234) );
map.put( "eventId", new Integer(11) );
map.put( "fromDate", getDate(4) );
map.put( "toDate", getDate(15) );
list.add(map);
map = new HashMap<String, Object>();
map.put( "actionId", new Integer(567) );
map.put( "eventId", new Integer(12) );
map.put( "fromDate", getDate(-1) );
map.put( "toDate", getDate(1) );
list.add(map);
System.out.println("\n Before Sorting \n ");
for( int j = 0; j < list.size(); j++ )
System.out.println(list.get(j));
Collections.sort( list, new HashMapComparator2() );
System.out.println("\n After Sorting \n ");
for( int j = 0; j < list.size(); j++ )
System.out.println(list.get(j));
}
public static Date getDate(int days) {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.DATE, days);
return cal.getTime();
}
public class HashMapComparator2 implements Comparator {
public int compare(Object object1, Object object2) {
if( ascending ) {
return new CompareToBuilder()
.append(
((HashMap)object1).get("actionId"),
((HashMap)object2).get("actionId")
)
.append(
((HashMap)object2).get("eventId"),
((HashMap)object1).get("eventId")
)
.toComparison();
} else {
return new CompareToBuilder()
.append(
((HashMap)object2).get("actionId"),
((HashMap)object1).get("actionId")
)
.append(
((HashMap)object2).get("eventId"),
((HashMap)object1).get("eventId")
)
.toComparison();
}
}
}
}
If you have a specific code that you are working on and are having issues, you can post your pseudo code and we can try to help you out!
Function using the approaches of Travis J, JLewkovich and Nick Craver...
// NOTE: Clears residual validation errors from the library "jquery.validate.js".
// By Travis J and Questor
// [Ref.: https://stackoverflow.com/a/16025232/3223785 ]
function clearJqValidErrors(formElement) {
// NOTE: Internal "$.validator" is exposed through "$(form).validate()". By Travis J
var validator = $(formElement).validate();
// NOTE: Iterate through named elements inside of the form, and mark them as
// error free. By Travis J
$(":input", formElement).each(function () {
// NOTE: Get all form elements (input, textarea and select) using JQuery. By Questor
// [Refs.: https://stackoverflow.com/a/12862623/3223785 ,
// https://api.jquery.com/input-selector/ ]
validator.successList.push(this); // mark as error free
validator.showErrors(); // remove error messages if present
});
validator.resetForm(); // remove error class on name elements and clear history
validator.reset(); // remove all error and success data
// NOTE: For those using bootstrap, there are cases where resetForm() does not
// clear all the instances of ".error" on the child elements of the form. This
// will leave residual CSS like red text color unless you call ".removeClass()".
// By JLewkovich and Nick Craver
// [Ref.: https://stackoverflow.com/a/2086348/3223785 ,
// https://stackoverflow.com/a/2086363/3223785 ]
$(formElement).find("label.error").hide();
$(formElement).find(".error").removeClass("error");
}
clearJqValidErrors($("#some_form_id"));
Some times you may make silly mistakes like writing insert query on the same .sql file (in the same workspace/tab) so once you execute the insert query where your create query was written just above and already executed, it will again start executing along with the insert query.
This is the reason why we are getting the object name (table name) exists already, since it's getting executed for the second time.
So go to a separate tab to write the insert or drop or whatever queries you are about to execute.
Or else use comment lines preceding all queries in the same workspace like
CREATE -- …
-- Insert query
INSERT INTO -- …
You will have to use cookie to store the value across page refresh. You can use any one of the many javascript based cookie libraries to simplify the cookie access, like this one
If you want to support only html5 then you can think of Storage api like localStorage/sessionStorage
Ex: using localStorage and cookies library
var mode = getStoredValue('myPageMode');
function buttonClick(mode) {
mode = mode;
storeValue('myPageMode', mode);
}
function storeValue(key, value) {
if (localStorage) {
localStorage.setItem(key, value);
} else {
$.cookies.set(key, value);
}
}
function getStoredValue(key) {
if (localStorage) {
return localStorage.getItem(key);
} else {
return $.cookies.get(key);
}
}
Well, you can just sort the files first, and diff the sorted files.
sort file1 > file1.sorted
sort file2 > file2.sorted
diff file1.sorted file2.sorted
You can also filter the output to report lines in file2 which are absent from file1:
diff -u file1.sorted file2.sorted | grep "^+"
As indicated in comments, you in fact do not need to sort the files. Instead, you can use a process substitution and say:
diff <(sort file1) <(sort file2)
Using this code you can write to a text file in the SDCard. Along with it, you need to set a permission in the Android Manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
This is the code :
public void generateNoteOnSD(Context context, String sFileName, String sBody) {
try {
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
Before writing files you must also check whether your SDCard is mounted & the external storage state is writable.
Environment.getExternalStorageState()
I have written a shell script which will read data from properties file and then run mysql script on shell script. sharing this may help to others.
#!/bin/bash
PROPERTY_FILE=filename.properties
function getProperty {
PROP_KEY=$1
PROP_VALUE=`cat $PROPERTY_FILE | grep "$PROP_KEY" | cut -d'=' -f2`
echo $PROP_VALUE
}
echo "# Reading property from $PROPERTY_FILE"
DB_USER=$(getProperty "db.username")
DB_PASS=$(getProperty "db.password")
ROOT_LOC=$(getProperty "root.location")
echo $DB_USER
echo $DB_PASS
echo $ROOT_LOC
echo "Writing on DB ... "
mysql -u$DB_USER -p$DB_PASS dbname<<EOFMYSQL
update tablename set tablename.value_ = "$ROOT_LOC" where tablename.name_="Root directory location";
EOFMYSQL
echo "Writing root location($ROOT_LOC) is done ... "
counter=`mysql -u${DB_USER} -p${DB_PASS} dbname -e "select count(*) from tablename where tablename.name_='Root directory location' and tablename.value_ = '$ROOT_LOC';" | grep -v "count"`;
if [ "$counter" = "1" ]
then
echo "ROOT location updated"
fi
How to use conditional in ng-class:
Solution 1:
<i ng-class="{'icon-autoscroll': autoScroll, 'icon-autoscroll-disabled': !autoScroll}"></i>
Solution 2:
<i ng-class="{true: 'icon-autoscroll', false: 'icon-autoscroll-disabled'}[autoScroll]"></i>
Solution 3 (angular v.1.1.4+ introduced support for ternary operator):
<i ng-class="autoScroll ? 'icon-autoscroll' : 'icon-autoscroll-disabled'"></i>
In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:
CSS solution:
HTML4's scrolling="no"
is kind of an alias of the CSS's overflow: hidden
, to do so it is important to set size attributes width/height:
iframe.noScrolling{
width: 250px; /*or any other size*/
height: 300px; /*or any other size*/
overflow: hidden;
}
Add this class to your iframe and you're done:
<iframe src="http://www.example.com/" class="noScrolling"></iframe>
! IMPORTANT NOTE ! : overflow: hidden
for <iframe>
is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no"
and overflow:hidden
at the same time :)
UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors
I just want to suggest another way to add an option
.
Instead of setting the value
and text
as a string one can also do:
var option = $('<option/>')
.val('option5')
.text('option5');
$('#selectBox').append(option);
This is a less error-prone solution when adding options' values and texts dynamically.
"datetime" expects the date to be formated like this: YYYY-MM-DD HH:MM:SS
so format your date like that when you are inserting.
We have noticed that using the MediaQuery
class can be a bit cumbersome, and it’s also missing a couple of key pieces of information.
Here We have a small Screen helper class, that we use across all our new projects:
class Screen {
static double get _ppi => (Platform.isAndroid || Platform.isIOS)? 150 : 96;
static bool isLandscape(BuildContext c) => MediaQuery.of(c).orientation == Orientation.landscape;
//PIXELS
static Size size(BuildContext c) => MediaQuery.of(c).size;
static double width(BuildContext c) => size(c).width;
static double height(BuildContext c) => size(c).height;
static double diagonal(BuildContext c) {
Size s = size(c);
return sqrt((s.width * s.width) + (s.height * s.height));
}
//INCHES
static Size inches(BuildContext c) {
Size pxSize = size(c);
return Size(pxSize.width / _ppi, pxSize.height/ _ppi);
}
static double widthInches(BuildContext c) => inches(c).width;
static double heightInches(BuildContext c) => inches(c).height;
static double diagonalInches(BuildContext c) => diagonal(c) / _ppi;
}
To use
bool isLandscape = Screen.isLandscape(context)
bool isLargePhone = Screen.diagonal(context) > 720;
bool isTablet = Screen.diagonalInches(context) >= 7;
bool isNarrow = Screen.widthInches(context) < 3.5;
To More, See: https://blog.gskinner.com/archives/2020/03/flutter-simplify-platform-detection-responsive-sizing.html
Following can also be done. If you want to append prepend icon. This will be helpful.
<?php $form = ActiveForm::begin();
echo $form->field($model, 'field')->begin();
echo Html::activeLabel($model, 'field', ["class"=>"control-label col-md-4"]); ?>
<div class="col-md-5">
<?php echo Html::activeDropDownList($model, 'field', $array_list, ['class'=>'form-control']); ?>
<p><i><small>Please select field</small></i>.</p>
<?php echo Html::error($model, 'field', ['class'=>'help-block']); ?>
</div>
<?php echo $form->field($model, 'field')->end();
ActiveForm::end();?>
in my case i was using compile sdk 23
and build tools 25.0.0
just changed compile sdk
to 25 and done..
I guess this feature was added since the OP but for future reference errors that would output in the command window can be redirected to a file independent of the standard output
command 1> file - Write the standard output of command to file
command 2> file - Write the standard error of command to file
Here is my dark theme (based on Darcula IntelliJ Theme):
https://github.com/mervick/Qt-Creator-Darcula
AndroidStudioFrontScreenI simply double clicked the Android dmg install file that I saved on the hard drive and when the initial screen came up I dragged the icon for Android Studio into the Applications folder, now I know where it is!!! Also when you run it, be sure to right click the Android Studio while on the Dock and select "Options" -> "Keep on Dock". Everything else works. Dr. Roger Webster
I had trouble with the accepted answer due to no type hinting on the "document" variable: var document = ...
So I'm posting what worked for me as an alternative in case anybody else is having trouble.
public ActionResult DownloadFile()
{
string filename = "File.pdf";
string filepath = AppDomain.CurrentDomain.BaseDirectory + "/Path/To/File/" + filename;
byte[] filedata = System.IO.File.ReadAllBytes(filepath);
string contentType = MimeMapping.GetMimeMapping(filepath);
var cd = new System.Net.Mime.ContentDisposition
{
FileName = filename,
Inline = true,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(filedata, contentType);
}
I also faced this error and I believe there can be multiple reasons behind it. Mine was, ARR was getting timed-out.
In my case, browser was making a request to a reverse proxy site where I have set my redirection rules and that proxy site is eventually requesting the actual site. Now for huge data it was taking more than 2 minutes 5 seconds and Application Request Routing timeout for my server was set to 2 minutes. I fixed this by increasing the ARR timeout by below steps: 1. Go to IIS 2. Click on server name 3. Click on Application Request Routing Cache in the middle pane 4. Click Server Proxy settings in right pane 5. Increase the timeout 6. Click Apply
I would just do:
$('#submiteButtonID').click(function(e){
e.preventDefault();
//do your stuff.
$('#formId').submit();
});
Call preventDefault
at first and use submit()
function later, if you just need to submit the form
Are you talking about seeing the line numbers or knowing the total number of lines in a project? Here is the 1st one
This is actually very simple. It is much easier to find unique values, if the values are sorted first:
function sort_unique(arr) {
if (arr.length === 0) return arr;
arr = arr.sort(function (a, b) { return a*1 - b*1; });
var ret = [arr[0]];
for (var i = 1; i < arr.length; i++) { //Start loop at 1: arr[0] can never be a duplicate
if (arr[i-1] !== arr[i]) {
ret.push(arr[i]);
}
}
return ret;
}
console.log(sort_unique(['237','124','255','124','366','255']));
//["124", "237", "255", "366"]
#if DEBUG
bool bypassCheck=TRUE_OR_FALSE;//i will decide depending on what i am debugging
#else
bool bypassCheck = false; //NEVER bypass it
#endif
Make sure you have the checkbox to define DEBUG checked in your build properties.
In order to execute simple queries and return to my shell script, I think this works well:
$ sqlite3 example.db 'SELECT * FROM some_table;'
The current answer can be simplified to...
@Component({
...
template: '<child [myCallback]="theCallback"></child>',
directives: [ChildComponent]
})
export class ParentComponent{
public theCallback(){
...
}
}
@Component({...})
export class ChildComponent{
//This will be bound to the ParentComponent.theCallback
@Input()
public myCallback: Function;
...
}
The other answers are valid, but the Official Symfony Best Practices guide suggests using the web/
folder to store all assets, instead of different bundles.
Scattering your web assets across tens of different bundles makes it more difficult to manage them. Your designers' lives will be much easier if all the application assets are in one location.
Templates also benefit from centralizing your assets, because the links are much more concise[...]
I'd add to this by suggesting that you only put micro-assets within micro-bundles, such as a few lines of styles only required for a button in a button bundle, for example.
For those using the serialize()
function:
(function ($) {
var serialize = $.fn.serialize;
$.fn.serialize = function () {
let values = serialize.call(this);
let checkboxes = [];
checkboxes = checkboxes.concat(
$('input[type=checkbox]:not(:checked)', this).map(
function () {
return this.name + '=false';
}).get()
);
if(checkboxes.length > 0)
values = checkboxes.join('&') + '&' + values;
return values;
};
})(jQuery);
@Esteban Küber is absolutely right.
Maybe one additional hint for bloody beginners like me. If you speciify the variables with %s, you have to follow this principle for EVERY input value, which means for the SET-variables as well as for the WHERE-variables.
Otherwise, you will have to face a termination message like 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s WHERE'
variable=" Hello..."
print (variable)
print("This is the Test File "+variable)
for integer type ...
variable=" 10"
print (variable)
print("This is the Test File "+str(variable))
If you're in a client-side web environment, the new auth2 javascript API contains a much-needed getBasicProfile()
function, which returns the user's name, email, and image URL.
https://developers.google.com/identity/sign-in/web/reference#googleusergetbasicprofile
You can use a watchpoint for this (A breakpoint on data instead of code).
You can start by using watch i
.
Then set a condition for it using condition <breakpoint num> i == 5
You can get the breakpoint number by using info watch
If you are looking to edit the speed in which the slides come in and out (not the time in between changing slides called interval) for bootstrap 3.3.5 | After loading CDN bootstrap styles, overwrite the styles in your own css styleseet using the following classes. the 1.5 is the time change.
.carousel-inner > .item {
-webkit-transition: 1.5s ease-in-out ;
-o-transition: 1.5s ease-in-out ;
transition: 1.5s ease-in-out ;
}
.carousel-inner > .item {
-webkit-transition: -webkit-transform 1.5s ease-in-out;
-o-transition: -o-transform 1.5s ease-in-out;
transition: transform 1.5s ease-in-out;
}
after that, you will need to replace the carousel function in javascript. To do this you will overwrite the default bootstrap.min.js function after it loads. (In my opinion it is not a good idea to overwrite bootstrap files directly). so create a mynewscript.js and load it after bootstrap.min.js and add the new carousel function. The only line you will want to edit is this one, Carousel.TRANSITION_DURATION = 1500. 1500 being 1.5. Hope this helps.
+function ($) {
'use strict';
// CAROUSEL CLASS DEFINITION
// =========================
var Carousel = function (element, options) {
this.$element = $(element)
this.$indicators = this.$element.find('.carousel-indicators')
this.options = options
this.paused = null
this.sliding = null
this.interval = null
this.$active = null
this.$items = null
this.options.keyboard && this.$element.on('keydown.bs.carousel', $.proxy(this.keydown, this))
this.options.pause == 'hover' && !('ontouchstart' in document.documentElement) && this.$element
.on('mouseenter.bs.carousel', $.proxy(this.pause, this))
.on('mouseleave.bs.carousel', $.proxy(this.cycle, this))
}
Carousel.VERSION = '3.3.5'
Carousel.TRANSITION_DURATION = 1500
Carousel.DEFAULTS = {
interval: 5000,
pause: 'hover',
wrap: true,
keyboard: true
}
Carousel.prototype.keydown = function (e) {
if (/input|textarea/i.test(e.target.tagName)) return
switch (e.which) {
case 37: this.prev(); break
case 39: this.next(); break
default: return
}
e.preventDefault()
}
Carousel.prototype.cycle = function (e) {
e || (this.paused = false)
this.interval && clearInterval(this.interval)
this.options.interval
&& !this.paused
&& (this.interval = setInterval($.proxy(this.next, this), this.options.interval))
return this
}
Carousel.prototype.getItemIndex = function (item) {
this.$items = item.parent().children('.item')
return this.$items.index(item || this.$active)
}
Carousel.prototype.getItemForDirection = function (direction, active) {
var activeIndex = this.getItemIndex(active)
var willWrap = (direction == 'prev' && activeIndex === 0)
|| (direction == 'next' && activeIndex == (this.$items.length - 1))
if (willWrap && !this.options.wrap) return active
var delta = direction == 'prev' ? -1 : 1
var itemIndex = (activeIndex + delta) % this.$items.length
return this.$items.eq(itemIndex)
}
Carousel.prototype.to = function (pos) {
var that = this
var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active'))
if (pos > (this.$items.length - 1) || pos < 0) return
if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) // yes, "slid"
if (activeIndex == pos) return this.pause().cycle()
return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos))
}
Carousel.prototype.pause = function (e) {
e || (this.paused = true)
if (this.$element.find('.next, .prev').length && $.support.transition) {
this.$element.trigger($.support.transition.end)
this.cycle(true)
}
this.interval = clearInterval(this.interval)
return this
}
Carousel.prototype.next = function () {
if (this.sliding) return
return this.slide('next')
}
Carousel.prototype.prev = function () {
if (this.sliding) return
return this.slide('prev')
}
Carousel.prototype.slide = function (type, next) {
var $active = this.$element.find('.item.active')
var $next = next || this.getItemForDirection(type, $active)
var isCycling = this.interval
var direction = type == 'next' ? 'left' : 'right'
var that = this
if ($next.hasClass('active')) return (this.sliding = false)
var relatedTarget = $next[0]
var slideEvent = $.Event('slide.bs.carousel', {
relatedTarget: relatedTarget,
direction: direction
})
this.$element.trigger(slideEvent)
if (slideEvent.isDefaultPrevented()) return
this.sliding = true
isCycling && this.pause()
if (this.$indicators.length) {
this.$indicators.find('.active').removeClass('active')
var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)])
$nextIndicator && $nextIndicator.addClass('active')
}
var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid"
if ($.support.transition && this.$element.hasClass('slide')) {
$next.addClass(type)
$next[0].offsetWidth // force reflow
$active.addClass(direction)
$next.addClass(direction)
$active
.one('bsTransitionEnd', function () {
$next.removeClass([type, direction].join(' ')).addClass('active')
$active.removeClass(['active', direction].join(' '))
that.sliding = false
setTimeout(function () {
that.$element.trigger(slidEvent)
}, 0)
})
.emulateTransitionEnd(Carousel.TRANSITION_DURATION)
} else {
$active.removeClass('active')
$next.addClass('active')
this.sliding = false
this.$element.trigger(slidEvent)
}
isCycling && this.cycle()
return this
}
// CAROUSEL PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.carousel')
var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option)
var action = typeof option == 'string' ? option : options.slide
if (!data) $this.data('bs.carousel', (data = new Carousel(this, options)))
if (typeof option == 'number') data.to(option)
else if (action) data[action]()
else if (options.interval) data.pause().cycle()
})
}
var old = $.fn.carousel
$.fn.carousel = Plugin
$.fn.carousel.Constructor = Carousel
// CAROUSEL NO CONFLICT
// ====================
$.fn.carousel.noConflict = function () {
$.fn.carousel = old
return this
}
// CAROUSEL DATA-API
// =================
var clickHandler = function (e) {
var href
var $this = $(this)
var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7
if (!$target.hasClass('carousel')) return
var options = $.extend({}, $target.data(), $this.data())
var slideIndex = $this.attr('data-slide-to')
if (slideIndex) options.interval = false
Plugin.call($target, options)
if (slideIndex) {
$target.data('bs.carousel').to(slideIndex)
}
e.preventDefault()
}
$(document)
.on('click.bs.carousel.data-api', '[data-slide]', clickHandler)
.on('click.bs.carousel.data-api', '[data-slide-to]', clickHandler)
$(window).on('load', function () {
$('[data-ride="carousel"]').each(function () {
var $carousel = $(this)
Plugin.call($carousel, $carousel.data())
})
})
}(jQuery);
My SQL teacher said that if you specify both a DEFAULT
value and NOT NULL
or NULL
, DEFAULT
should always be expressed before NOT NULL
or NULL
.
Like this:
ALTER TABLE tbl ADD COLUMN col VARCHAR(20) DEFAULT "MyDefault" NOT NULL
ALTER TABLE tbl ADD COLUMN col VARCHAR(20) DEFAULT "MyDefault" NULL
If you use MyISAM tables, then you can recover any data you deleted, just
open file: mysql/data/[your_db]/[your_table].MYD
with any text editor
Another type of solution would be to autogenerate the nginx conf files via Jinja2 templates from ansible. The advantage of this is easy deployment to a cloud environment, and easy to replicate on multiple dev machines
out.write(c.toString());
out.newLine();
here is a simple solution, I hope it works
EDIT: I was using "\n" which was obviously not recommended approach, modified answer.
The reason you aren't finding easy examples for how to do this in T-SQL is that it is generally considered bad practice to implement formatting logic in SQL code. RDBMS's simply are not designed for presentation. While it is possible to do some limited formatting, it is almost always better to let the application or user interface handle formatting of this type.
But if you must (and sometimes we must!) use T-SQL, cast your int to money and convert it to varchar, like this:
select convert(varchar,cast(1234567 as money),1)
If you don't want the trailing decimals, do this:
select replace(convert(varchar,cast(1234567 as money),1), '.00','')
Good luck!
You would use the focus
and blur
events of the window:
var interval_id;
$(window).focus(function() {
if (!interval_id)
interval_id = setInterval(hard_work, 1000);
});
$(window).blur(function() {
clearInterval(interval_id);
interval_id = 0;
});
To Answer the Commented Issue of "Double Fire" and stay within jQuery ease of use:
$(window).on("blur focus", function(e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) { // reduce double fire issues
switch (e.type) {
case "blur":
// do work
break;
case "focus":
// do work
break;
}
}
$(this).data("prevType", e.type);
})
Click to view Example Code Showing it working (JSFiddle)
I think the project you are looking for is: https://github.com/sarxos/webcam-capture (I'm the author)
There is an example working exactly as you've described - after it's run, the window appear where, after you press "Start" button, you can see live image from webcam device and save it to file after you click on "Snapshot" (source code available, please note that FPS counter in the corner can be disabled):
The project is portable (WinXP, Win7, Win8, Linux, Mac, Raspberry Pi) and does not require any additional software to be installed on the PC.
API is really nice and easy to learn. Example how to capture single image and save it to PNG file:
Webcam webcam = Webcam.getDefault();
webcam.open();
ImageIO.write(webcam.getImage(), "PNG", new File("test.png"));
My short explanation is:
assert
raises AssertionError
if expression is false, otherwise just continues the code, and if there's a comma whatever it is it will be AssertionError: whatever after comma
, and to code is like: raise AssertionError(whatever after comma)
A related tutorial about this:
https://www.tutorialspoint.com/python/assertions_in_python.htm
I'll take a stab at it:
/^[a-z](?:_?[a-z0-9]+)*$/i
Explained:
/
^ # match beginning of string
[a-z] # match a letter for the first char
(?: # start non-capture group
_? # match 0 or 1 '_'
[a-z0-9]+ # match a letter or number, 1 or more times
)* # end non-capture group, match whole group 0 or more times
$ # match end of string
/i # case insensitive flag
The non-capture group takes care of a) not allowing two _
's (it forces at least one letter or number per group) and b) only allowing the last char to be a letter or number.
Some test strings:
"a": match
"_": fail
"zz": match
"a0": match
"A_": fail
"a0_b": match
"a__b": fail
"a_1_c": match
@Transactional =javax.transaction.Transactional
. Put it just beside @Repository
.
Just to reload everything , use window.location.reload(); with angularjs
Check out working example
HTML
<div ng-controller="MyCtrl">
<button ng-click="reloadPage();">Reset</button>
</div>
angularJS
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.reloadPage = function(){window.location.reload();}
}
You can avoid rolling your own Component subclass completely by using the JXImagePanel class from the free SwingX libraries.
If you use cmake, add DYLIB_INSTALL_NAME_BASE "@rpath"
to target properties:
set_target_properties(target_dyLib PROPERTIES
# # for FRAMEWORK begin
# FRAMEWORK TRUE
# FRAMEWORK_VERSION C
# MACOSX_FRAMEWORK_IDENTIFIER com.cmake.targetname
# MACOSX_FRAMEWORK_INFO_PLIST ./Info.plist
# PUBLIC_HEADER targetname.h
# # for FRAMEWORK end
IPHONEOS_DEPLOYMENT_TARGET "8.0"
DYLIB_INSTALL_NAME_BASE "@rpath" # this is the key point
XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY "iPhone Developer"
DEVELOPMENT_TEAM "${DEVELOPMENT_TEAM}"
)
or in Xcode dynamic library project Target -> Build Setting set Dynamic Library Install Name Base to @rpath
According to book of "The C++ Programming Language 4th Editon" by Bjarne Stroustrup
• const: meaning roughly ‘‘I promise not to change this value’’ (§7.5). This is used primarily
to specify interfaces, so that data can be passed to functions without fear of it being modified.
The compiler enforces the promise made by const.
• constexpr: meaning roughly ‘‘to be evaluated at compile time’’ (§10.4). This is used primarily to specify constants, to allow
For example:
const int dmv = 17; // dmv is a named constant
int var = 17; // var is not a constant
constexpr double max1 = 1.4*square(dmv); // OK if square(17) is a constant expression
constexpr double max2 = 1.4*square(var); // error : var is not a constant expression
const double max3 = 1.4*square(var); //OK, may be evaluated at run time
double sum(const vector<double>&); // sum will not modify its argument (§2.2.5)
vector<double> v {1.2, 3.4, 4.5}; // v is not a constant
const double s1 = sum(v); // OK: evaluated at run time
constexpr double s2 = sum(v); // error : sum(v) not constant expression
For a function to be usable in a constant expression, that is, in an expression that will be evaluated
by the compiler, it must be defined constexpr.
For example:
constexpr double square(double x) { return x*x; }
To be constexpr, a function must be rather simple: just a return-statement computing a value. A
constexpr function can be used for non-constant arguments, but when that is done the result is not a
constant expression. We allow a constexpr function to be called with non-constant-expression arguments
in contexts that do not require constant expressions, so that we don’t hav e to define essentially
the same function twice: once for constant expressions and once for variables.
In a few places, constant expressions are required by language rules (e.g., array bounds (§2.2.5,
§7.3), case labels (§2.2.4, §9.4.2), some template arguments (§25.2), and constants declared using
constexpr). In other cases, compile-time evaluation is important for performance. Independently of
performance issues, the notion of immutability (of an object with an unchangeable state) is an
important design concern (§10.4).
Why not a/b/(c|d|e)
? I just tried with Saxon XML library (wrapped up nicely with some Clojure goodness), and it seems to work.
abc.xml
is the doc described by OP.
(require '[saxon :as xml])
(def abc-doc (xml/compile-xml (slurp "abc.xml")))
(xml/query "a/b/(c|d|e)" abc-doc)
=> (#<XdmNode <c>C1</c>>
#<XdmNode <d>D1</d>>
#<XdmNode <e>E1</e>>
#<XdmNode <c>C2</c>>
#<XdmNode <d>D2</d>>
#<XdmNode <e>E1</e>>)
Use this:
os.path.splitext("name.fasta")[0]+".aln"
And here is how the above works:
The splitext method separates the name from the extension creating a tuple:
os.path.splitext("name.fasta")
the created tuple now contains the strings "name" and "fasta". Then you need to access only the string "name" which is the first element of the tuple:
os.path.splitext("name.fasta")[0]
And then you want to add a new extension to that name:
os.path.splitext("name.fasta")[0]+".aln"
For MySql WorkBench, Please use below :
update emp as a
inner join department b on a.department_id=b.id
set a.department_name=b.name
where a.emp_id in (10,11,12);