In my experience over the past few months, I've realized that the best way to achieve this is:
class App extends React.Component{
constructor(){
super();
this.state = {
serverResponse: ''
}
}
componentDidMount(){
this.getData();
}
async getData(){
const res = await axios.get('url-to-get-the-data');
const { data } = await res;
this.setState({serverResponse: data})
}
render(){
return(
<div>
{this.state.serverResponse}
</div>
);
}
}
If you are trying to make post request on events such as click, then call getData()
function on the event and replace the content of it like so:
async getData(username, password){
const res = await axios.post('url-to-post-the-data', {
username,
password
});
...
}
Furthermore, if you are making any request when the component is about to load then simply replace async getData()
with async componentDidMount()
and change the render function like so:
render(){
return (
<div>{this.state.serverResponse}</div>
)
}
If you have a browser that doesn't support the calc
expression, it's not hard to mimic with jQuery:
$('#yourEl').css('width', '100%').css('width', '-=100px');
It's much easier to let jQuery handle the relative calculation than doing it yourself.
I haven't played around with it much but eclipse/pydev feels nice.
For those that are following the example on this GoogleMaps - MapWithMarker project, you may remove the marker by doing so
override fun onMapReady(googleMap: GoogleMap?) {
googleMap?.apply {
// Remove marker
clear()
val sydney = LatLng(-33.852, 151.211)
addMarker(
MarkerOptions()
.position(sydney)
.title("Marker in Sydney")
)
moveCamera(CameraUpdateFactory.newLatLng(sydney))
}
}
Here is the snippet you can use to programmatically get user.config file location:
public static string GetDefaultExeConfigPath(ConfigurationUserLevel userLevel)
{
try
{
var UserConfig = ConfigurationManager.OpenExeConfiguration(userLevel);
return UserConfig.FilePath;
}
catch (ConfigurationException e)
{
return e.Filename;
}
}
ApplicationSettings (i.e. settings.settings) use PerUserRoamingAndLocal for user settings by default (as I remembered).
Update: Strange but there are too many incorrect answers here. If you are looking for you user scoped settings file (user.config) it will be located in the following folder (for Windows XP):
C:\Documents and Settings\(username)\Local Settings\Application Data\(company-name-if-exists)\(app-name).exe_(Url|StrongName)_(hash)\(app-version)\
Url or StrongName depends on have you application assembly strong name or not.
since jQuery1.8
, using $.parseHTML()
to create elements is a better choice.
there are two benefits:
1.if you use the old way, which may be something like $(string)
, jQuery will examine the string to make sure you want to select a html tag or create a new element. By using $.parseHTML()
, you tell jQuery that you want to create a new element explicitly, so the performance may be a little better.
2.much more important thing is that you may suffer from cross site attack (more info) if you use the old way. if you have something like:
var userInput = window.prompt("please enter selector");
$(userInput).hide();
a bad guy can input <script src="xss-attach.js"></script>
to tease you. fortunately, $.parseHTML()
avoid this embarrassment for you:
var a = $('<div>')
// a is [<div>?</div>?]
var b = $.parseHTML('<div>')
// b is [<div>?</div>?]
$('<script src="xss-attach.js"></script>')
// jQuery returns [<script src=?"xss-attach.js">?</script>?]
$.parseHTML('<script src="xss-attach.js"></script>')
// jQuery returns []
However, please notice that a
is a jQuery object while b
is a html element:
a.html('123')
// [<div>?123?</div>?]
b.html('123')
// TypeError: Object [object HTMLDivElement] has no method 'html'
$(b).html('123')
// [<div>?123?</div>?]
Based on the example here: http://drupal.org/node/550488
The following will probably work in .htaccess
<IfModule mod_expires.c>
# Enable expirations.
ExpiresActive On
# Cache all files for 2 weeks after access (A).
ExpiresDefault A1209600
<FilesMatch (\.js|\.html)$>
ExpiresActive Off
</FilesMatch>
</IfModule>
Try the rename
command in the folder with the files:
rename 's/^/Unix_/' *
The argument of rename (sed s command) indicates to replace the regex ^ with Unix_. The caret (^) is a special character that means start of the line.
@Richie Cotton has a pretty good answer above. I can only add that this page provides some examples. Try the following:
x <- 1:20
y <- runif(20)
plot(x,y,xaxt = "n")
axis(side = 1, at = x, labels = FALSE, tck = -0.01)
PowerShell is very powerful, more powerful than the standard built-ins of the Unix shells (but only because it includes much of the functionality usually shelled out to subprograms). Also, consider that you can write applets in any .NET language, including IronPython, IronRuby, PerlNet, etc.. or you can simply call your Cygwin commands from PowerShell, ignoring all the extra functionality and it will work similarly to Bash, KornShell, or whatever...
In general, when "Bad File Descriptor" is encountered, it means that the socket file descriptor you passed into the API is not valid, which has multiple possible reasons:
There are built in classes, namely:
.padding-xs { padding: .25em; }
.padding-sm { padding: .5em; }
.padding-md { padding: 1em; }
.padding-lg { padding: 1.5em; }
.padding-xl { padding: 3em; }
.padding-x-xs { padding: .25em 0; }
.padding-x-sm { padding: .5em 0; }
.padding-x-md { padding: 1em 0; }
.padding-x-lg { padding: 1.5em 0; }
.padding-x-xl { padding: 3em 0; }
.padding-y-xs { padding: 0 .25em; }
.padding-y-sm { padding: 0 .5em; }
.padding-y-md { padding: 0 1em; }
.padding-y-lg { padding: 0 1.5em; }
.padding-y-xl { padding: 0 3em; }
.padding-top-xs { padding-top: .25em; }
.padding-top-sm { padding-top: .5em; }
.padding-top-md { padding-top: 1em; }
.padding-top-lg { padding-top: 1.5em; }
.padding-top-xl { padding-top: 3em; }
.padding-right-xs { padding-right: .25em; }
.padding-right-sm { padding-right: .5em; }
.padding-right-md { padding-right: 1em; }
.padding-right-lg { padding-right: 1.5em; }
.padding-right-xl { padding-right: 3em; }
.padding-bottom-xs { padding-bottom: .25em; }
.padding-bottom-sm { padding-bottom: .5em; }
.padding-bottom-md { padding-bottom: 1em; }
.padding-bottom-lg { padding-bottom: 1.5em; }
.padding-bottom-xl { padding-bottom: 3em; }
.padding-left-xs { padding-left: .25em; }
.padding-left-sm { padding-left: .5em; }
.padding-left-md { padding-left: 1em; }
.padding-left-lg { padding-left: 1.5em; }
.padding-left-xl { padding-left: 3em; }
.margin-xs { margin: .25em; }
.margin-sm { margin: .5em; }
.margin-md { margin: 1em; }
.margin-lg { margin: 1.5em; }
.margin-xl { margin: 3em; }
.margin-x-xs { margin: .25em 0; }
.margin-x-sm { margin: .5em 0; }
.margin-x-md { margin: 1em 0; }
.margin-x-lg { margin: 1.5em 0; }
.margin-x-xl { margin: 3em 0; }
.margin-y-xs { margin: 0 .25em; }
.margin-y-sm { margin: 0 .5em; }
.margin-y-md { margin: 0 1em; }
.margin-y-lg { margin: 0 1.5em; }
.margin-y-xl { margin: 0 3em; }
.margin-top-xs { margin-top: .25em; }
.margin-top-sm { margin-top: .5em; }
.margin-top-md { margin-top: 1em; }
.margin-top-lg { margin-top: 1.5em; }
.margin-top-xl { margin-top: 3em; }
.margin-right-xs { margin-right: .25em; }
.margin-right-sm { margin-right: .5em; }
.margin-right-md { margin-right: 1em; }
.margin-right-lg { margin-right: 1.5em; }
.margin-right-xl { margin-right: 3em; }
.margin-bottom-xs { margin-bottom: .25em; }
.margin-bottom-sm { margin-bottom: .5em; }
.margin-bottom-md { margin-bottom: 1em; }
.margin-bottom-lg { margin-bottom: 1.5em; }
.margin-bottom-xl { margin-bottom: 3em; }
.margin-left-xs { margin-left: .25em; }
.margin-left-sm { margin-left: .5em; }
.margin-left-md { margin-left: 1em; }
.margin-left-lg { margin-left: 1.5em; }
.margin-left-xl { margin-left: 3em; }
You should \usepackage{longtable}
.
This is the Windows version of a fork bomb.
%0
is the name of the currently executing batch file. A batch file that contains just this line:
%0|%0
Is going to recursively execute itself forever, quickly creating many processes and slowing the system down.
This is not a bug in windows, it is just a very stupid thing to do in a batch file.
If your chart uses both fill
and color
aesthetics, you can remove the legend with:
+ guides(fill=FALSE, color=FALSE)
youmap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentlocation, 16));
16 is the zoom level
This is probably what you need:
$('div').html();
This says get the div
and return all the contents inside it. See more here: http://api.jquery.com/html/
If you had many div
s on the page and needed to target just one, you could set an id
on the div
and call it like so
$('#whatever').html();
where whatever is the id
EDIT
Now that you have clarified your question re this being a string, here is a way to do it with vanilla js:
var l = x.length;
var y = x.indexOf('<div>');
var s = x.slice(y,l);
alert(s);
div
occursI find Visual Studio Code is awesome for debugging Django apps. The standard python launch.json parameters run python manage.py
with the debugger attached, so you can set breakpoints and step through your code as you like.
If you want to be able to access images.main
then you must define it explicitly:
interface Images {
main: string;
[key:string]: string;
}
function getMainImageUrl(images: Images): string {
return images.main;
}
You can not access indexed properties using the dot notation because typescript has no way of knowing whether or not the object has that property.
However, when you specifically define a property then the compiler knows that it's there (or not), whether it's optional or not and what's the type.
You can have a helper class for map instances, something like:
class Map<T> {
private items: { [key: string]: T };
public constructor() {
this.items = Object.create(null);
}
public set(key: string, value: T): void {
this.items[key] = value;
}
public get(key: string): T {
return this.items[key];
}
public remove(key: string): T {
let value = this.get(key);
delete this.items[key];
return value;
}
}
function getMainImageUrl(images: Map<string>): string {
return images.get("main");
}
I have something like that implemented, and I find it very useful.
I think this working CodePen example that I created will show you exactly how to do what you want.
The template:
<section ng-app="app" ng-controller="MainCtrl">
<span class="label">Ordered By: {{orderByField}}, Reverse Sort: {{reverseSort}}</span><br><br>
<table class="table table-bordered">
<thead>
<tr>
<th>
<a href="#" ng-click="orderByField='firstName'; reverseSort = !reverseSort">
First Name <span ng-show="orderByField == 'firstName'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span>
</a>
</th>
<th>
<a href="#" ng-click="orderByField='lastName'; reverseSort = !reverseSort">
Last Name <span ng-show="orderByField == 'lastName'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span>
</a>
</th>
<th>
<a href="#" ng-click="orderByField='age'; reverseSort = !reverseSort">
Age <span ng-show="orderByField == 'age'"><span ng-show="!reverseSort">^</span><span ng-show="reverseSort">v</span></span>
</a>
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="emp in data.employees|orderBy:orderByField:reverseSort">
<td>{{emp.firstName}}</td>
<td>{{emp.lastName}}</td>
<td>{{emp.age}}</td>
</tr>
</tbody>
</table>
</section>
The JavaScript code:
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.orderByField = 'firstName';
$scope.reverseSort = false;
$scope.data = {
employees: [{
firstName: 'John',
lastName: 'Doe',
age: 30
},{
firstName: 'Frank',
lastName: 'Burns',
age: 54
},{
firstName: 'Sue',
lastName: 'Banter',
age: 21
}]
};
});
First of all, the provided long code:
<xsl:choose>
<xsl:when test="OU_NAME='OU_ADDR1'"> --comparing two elements coming from XML
<!--remove if adrees already contain operating unit name <xsl:value-of select="OU_NAME"/> <fo:block/>-->
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="OU_NAME"/>
<fo:block/>
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
</xsl:otherwise>
</xsl:choose>
is equivalent to this, much shorter code:
<xsl:if test="not(OU_NAME='OU_ADDR1)'">
<xsl:value-of select="OU_NAME"/>
</xsl:if>
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
Now, to your question:
how to compare two elements coming from xml as string
In Xpath 1.0 strings can be compared only for equality (or inequality), using the operator =
and the function not()
together with the operator =
.
$str1 = $str2
evaluates to true()
exactly when the string $str1
is equal to the string $str2
.
not($str1 = $str2)
evaluates to true()
exactly when the string $str1
is not equal to the string $str2
.
There is also the !=
operator. It generally should be avoided because it has anomalous behavior whenever one of its operands is a node-set.
Now, the rules for comparing two element nodes are similar:
$el1 = $el2
evaluates to true()
exactly when the string value of $el1
is equal to the string value of $el2
.
not($el1 = $el2)
evaluates to true()
exactly when the string value of $el1
is not equal to the string value of $el2
.
However, if one of the operands of =
is a node-set, then
$ns = $str
evaluates to true()
exactly when there is at least one node in the node-set $ns1
, whose string value is equal to the string $str
$ns1 = $ns2
evaluates to true()
exactly when there is at least one node in the node-set $ns1
, whose string value is equal to the string value of some node from $ns2
Therefore, the expression:
OU_NAME='OU_ADDR1'
evaluates to true()
only when there is at least one element child of the current node that is named OU_NAME
and whose string value is the string 'OU_ADDR1'.
This is obviously not what you want!
Most probably you want:
OU_NAME=OU_ADDR1
This expression evaluates to true
exactly there is at least one OU_NAME
child of the current node and one OU_ADDR1
child of the current node with the same string value.
Finally, in XPath 2.0, strings can be compared also using the value comparison operators lt
, le
, eq
, gt
, ge
and the inherited from XPath 1.0 general comparison operator =
.
Trying to evaluate a value comparison operator when one or both of its arguments is a sequence of more than one item results in error.
Arrays are special objects in java, they have a simple attribute named length
which is final
.
There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.
10.7. Array Members
The members of an array type are all of the following:
- The
public
final
fieldlength
, which contains the number of components of the array.length
may be positive or zero.The
public
methodclone
, which overrides the method of the same name in classObject
and throws no checked exceptions. The return type of theclone
method of an array typeT[]
isT[]
.A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.
- All the members inherited from class
Object
; the only method ofObject
that is not inherited is itsclone
method.
Resources:
I searched for a the same solution with a variable instead of the String.
I hope i can help someone with my solution :)
var numb = "3";
$(`#myid[data-tab-id=${numb}]`);
read hash < <(genhash --use-ssl -s $IP -p 443 --url $URL | grep MD5 | grep -c $MD5)
This technique uses Bash's "process substitution" not to be confused with "command substitution".
Here are a few good references:
MD5 is perfectly fine if you don't need the best security, and if you're doing something like checking file integrity then security is not a consideration. In such as case you might want to consider something simpler and faster, such as Adler32, which is also supported by the Java libraries.
$_POST
is an array in itsself you don't need to make an array out of it. What you did is nest the $_POST
array inside a new array. This is why you print Array
.
Change it to:
foreach ($_POST as $key => $value) {
echo "<p>".$key."</p>";
echo "<p>".$value."</p>";
echo "<hr />";
}
package com.server;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import org.w3c.dom.*;
import com.gwtext.client.data.XmlReader;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
public class XmlServlet extends HttpServlet
{
NodeList list;
Connection con=null;
Statement st=null;
ResultSet rs = null;
String xmlString ;
BufferedWriter bw;
String displayTo;
String displayFrom;
String addressto;
String addressFrom;
Date send;
String Subject;
String body;
String category;
Document doc1;
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
System.out.print("on server");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
System.out.print("on server");
try
{
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
//creating a new instance of a DOM to build a DOM tree.
doc1 = docBuilder.newDocument();
new XmlServlet().createXmlTree(doc1);
System.out.print("on server");
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
public void createXmlTree(Document doc) throws Exception {
//This method creates an element node
System.out.println("ruchipaliwal111");
try
{
System.out.println("ruchi111");
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3308/plz","root","root1");
st = con.createStatement();
rs = st.executeQuery("select * from data");
Element root = doc.createElement("message");
doc.appendChild(root);
while(rs.next())
{
displayTo=rs.getString(1).toString();
System.out.println(displayTo+"getdataname");
displayFrom=rs.getString(2).toString();
System.out.println(displayFrom +"getdataname");
addressto=rs.getString(3).toString();
System.out.println(addressto +"getdataname");
addressFrom=rs.getString(4).toString();
System.out.println(addressFrom +"getdataname");
send=rs.getDate(5);
System.out.println(send +"getdataname");
Subject=rs.getString(6).toString();
System.out.println(Subject +"getdataname");
body=rs.getString(7).toString();
System.out.println(body+"getdataname");
category=rs.getString(8).toString();
System.out.println(category +"getdataname");
//adding a node after the last child node of ssthe specified node.
Element element1 = doc.createElement("Header");
root.appendChild(element1);
Element child1 = doc.createElement("To");
element1.appendChild(child1);
child1.setAttribute("displayNameTo",displayTo);
child1.setAttribute("addressTo",addressto);
Element child2 = doc.createElement("From");
element1.appendChild(child2);
child2.setAttribute("displayNameFrom",displayFrom);
child2.setAttribute("addressFrom",addressFrom);
Element child3 = doc.createElement("Send");
element1.appendChild(child3);
Text text2 = doc.createTextNode(send.toString());
child3.appendChild(text2);
Element child4 = doc.createElement("Subject");
element1.appendChild(child4);
Text text3 = doc.createTextNode(Subject);
child4.appendChild(text3);
Element child5 = doc.createElement("category");
element1.appendChild(child5);
Text text44 = doc.createTextNode(category);
child5.appendChild(text44);
Element element2 = doc.createElement("Body");
root.appendChild(element2);
Text text1 = doc.createTextNode(body);
element2.appendChild(text1);
/*
Element child1 = doc.createElement("name");
root.appendChild(child1);
Text text = doc.createTextNode(getdataname);
child1.appendChild(text);
Element element = doc.createElement("address");
root.appendChild(element);
Text text1 = doc.createTextNode( getdataaddress);
element.appendChild(text1);
*/
}
//TransformerFactory instance is used to create Transformer objects.
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.METHOD,"xml");
// transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");
// create string from xml tree
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
xmlString = sw.toString();
File file = new File("./war/ds/newxml.xml");
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
bw.write(xmlString);
}
catch(Exception e)
{
System.out.print("after while loop exception"+e.toString());
}
bw.flush();
bw.close();
System.out.println("successfully done.....");
}
}
I look for a good way to deal with this issue and I am looking at the same question. Hopefully, this answer will be helping everyone who has the same problem likes me.
using (var client = new HttpClient())
{
var url = "https://www.theidentityhub.com/{tenant}/api/identity/v1";
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
var response = await client.GetStringAsync(url);
// Parse JSON response.
....
}
reference from https://www.theidentityhub.com/hub/Documentation/CallTheIdentityHubApi
ul li{
display: inline;
}
For more see the basic list options and a basic horizontal list at listamatic. (thanks to Daniel Straight below for the links).
Also, as pointed out in the comments, you probably want styling on the ul and whatever elements go inside the li's and the li's themselves to get things to look nice.
Swift solution
Create two outlets, one for your view and one for your scroll view:
@IBOutlet weak var myView: UIView!
@IBOutlet weak var scrollView: UIScrollView!
Then in your viewDidLayoutSubviews you can add the following code:
let scrollSize = CGSize(width: myView.frame.size.width,
height: myView.frame.size.height)
scrollView.contentSize = scrollSize
What we've done is collected the height and width of the view and set the scrollViews content size to match it. This will stop your scrollview from scrolling horizontally.
More Thoughts:
CGSizeMake takes a width & height using CGFloats. You may need to use your UIScrollViews existing height for the second parameter. Which would look like this:
let scrollSize = CGSize(width: myView.frame.size.width,
height: scrollView.contentSize.height)
If you are looking for an authentication framework for Connect or Express, Passport is worth investigating: https://github.com/jaredhanson/passport
(Disclosure: I'm the developer of Passport)
I developed Passport after investigating both connect-auth and everyauth. While they are both great modules, they didn't suit my needs. I wanted something that was more light-weight and unobtrusive.
Passport is broken down into separate modules, so you can choose to use only what you need (OAuth, only if necessary). Passport also does not mount any routes in your application, giving you the flexibility to decide when and where you want authentication, and hooks to control what happens when authentication succeeds or fails.
For example, here is the two-step process to setup form-based (username and password) authentication:
passport.use(new LocalStrategy(
function(username, password, done) {
// Find the user from your DB (MongoDB, CouchDB, other...)
User.findOne({ username: username, password: password }, function (err, user) {
done(err, user);
});
}
));
app.post('/login',
passport.authenticate('local', { failureRedirect: '/login' }),
function(req, res) {
// Authentication successful. Redirect home.
res.redirect('/');
});
Additional strategies are available for authentication via Facebook, Twitter, etc. Custom strategies can be plugged-in, if necessary.
Runtime runtime = Runtime.getRuntime();
try {
Process p1 = runtime.exec("cmd /c start D:\\temp\\a.bat");
InputStream is = p1.getInputStream();
int i = 0;
while( (i = is.read() ) != -1) {
System.out.print((char)i);
}
} catch(IOException ioException) {
System.out.println(ioException.getMessage() );
}
Put this at onStart
PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "no sleep"); wakeLock.acquire();
And this at you manifest
<uses-permission android:name="android.permission.WAKE_LOCK" />
Don't forget to
wakeLock.release();
at onStop
This is the fastest and easiest way that I have found;
while (tableModel.getRowCount()>0)
{
tableModel.removeRow(0);
}
This clears the table lickety split and leaves it ready for new data.
In C++, structs and classes are pretty much the same; the only difference is that where access modifiers (for member variables, methods, and base classes) in classes default to private, access modifiers in structs default to public.
However, in C, a struct is just an aggregate collection of (public) data, and has no other class-like features: no methods, no constructor, no base classes, etc. Although C++ inherited the keyword, it extended the semantics. (This, however, is why things default to public in structs—a struct written like a C struct behaves like one.)
While it's possible to fake some OOP in C—for instance, defining functions which all take a pointer to a struct as their first parameter, or occasionally coercing structs with the same first few fields to be "sub/superclasses"—it's always sort of bolted on, and isn't really part of the language.
I use the filter solution above, for ie8. However.. In order to solve the freezing links problem , do also the following:
background: no-repeat center center fixed\0/; /* IE8 HACK */
This has solved the frozen links problem for me.
I just looked at code that did this today. This is a variation on AviewAnew's answer.
collectionOfStrings = /* source string collection */;
String csList = StringUtils.join(collectionOfStrings.toArray(), ",");
The StringUtils ( <-- commons.lang 2.x, or commons.lang 3.x link) we used is from Apache Commons.
I see you would want to do this if you wanted to make, say, the whole box of a menu item clickable. I used to insert an 'li' tag in 'a' tags to do this but this seems more valid.
@RequestMapping(value = "/books", method = { RequestMethod.GET,
RequestMethod.POST })
public ModelAndView listBooks(@ModelAttribute("booksFilter") BooksFilter filter,
HttpServletRequest request)
throws ParseException {
//your code
}
This will works for both GET and POST.
For GET if your pojo(BooksFilter) have to contain the attribute which you're using in request parameter
like below
public class BooksFilter{
private String parameter1;
private String parameter2;
//getters and setters
URl should be like below
/books?parameter1=blah
Like this way u can use it for both GET and POST
Your CSV file might have variable number of columns and read_csv
inferred the number of columns from the first few rows. Two ways to solve it in this case:
1) Change the CSV file to have a dummy first line with max number of columns (and specify header=[0]
)
2) Or use names = list(range(0,N))
where N is the max number of columns.
Did you include
#!/usr/bin/python
as your first line?
You need to set the classpath to find your compiled class:
java -cp C:\Users\Matt\workspace\HelloWorld2\bin HelloWorld2
All of these answers are so complicated, but there is a simple built-in method that accomplishes this: canScrollVertically(int)
For example:
@Override
public void onScrollChanged() {
if (!scrollView.canScrollVertically(1)) {
// bottom of scroll view
}
if (!scrollView.canScrollVertically(-1)) {
// top of scroll view
}
}
This also works with RecyclerView, ListView, and actually any other view since the method is implemented on View
.
If you have a horizontal ScrollView, the same can be achieved with canScrollHorizontally(int)
To throw in another solution that has no need for subclassing:
UITextField *txtField = [UITextField new];
txtField.borderStyle = UITextBorderStyleRoundedRect;
// grab BG layer
CALayer *bgLayer = txtField.layer.sublayers.lastObject;
bgLayer.opacity = 0.f;
// add new bg view
UIView *bgView = [UIView new];
bgView.backgroundColor = [UIColor whiteColor];
bgView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
bgView.userInteractionEnabled = NO;
[txtField addSubview: bgView];
[txtField sendSubviewToBack: bgView];
Tested with iOS 7 and iOS 8. Both working. Still there might be the chance of Apple modifying the UITextField's layer hierarchy screwing up things badly.
I am using Debian 8 live off a USB. I was locked out of the system after 10 min of inactivity. The password that was required to log back in to the system for the user was:
login : Debian Live User
password : live
I hope this helps
This is how I implemented my URL builder. I have created one Service class to provide the params for the URL
public interface ParamsProvider {
String queryProvider(List<BasicNameValuePair> params);
String bodyProvider(List<BasicNameValuePair> params);
}
The Implementation of methods are below
@Component
public class ParamsProviderImp implements ParamsProvider {
@Override
public String queryProvider(List<BasicNameValuePair> params) {
StringBuilder query = new StringBuilder();
AtomicBoolean first = new AtomicBoolean(true);
params.forEach(basicNameValuePair -> {
if (first.get()) {
query.append("?");
query.append(basicNameValuePair.toString());
first.set(false);
} else {
query.append("&");
query.append(basicNameValuePair.toString());
}
});
return query.toString();
}
@Override
public String bodyProvider(List<BasicNameValuePair> params) {
StringBuilder body = new StringBuilder();
AtomicBoolean first = new AtomicBoolean(true);
params.forEach(basicNameValuePair -> {
if (first.get()) {
body.append(basicNameValuePair.toString());
first.set(false);
} else {
body.append("&");
body.append(basicNameValuePair.toString());
}
});
return body.toString();
}
}
When we need the query params for our URL, I simply call the service and build it. Example for that is below.
Class Mock{
@Autowired
ParamsProvider paramsProvider;
String url ="http://www.google.lk";
// For the query params price,type
List<BasicNameValuePair> queryParameters = new ArrayList<>();
queryParameters.add(new BasicNameValuePair("price", 100));
queryParameters.add(new BasicNameValuePair("type", "L"));
url = url+paramsProvider.queryProvider(queryParameters);
// You can use it in similar way to send the body params using the bodyProvider
}
you never change the value of rng
so it always points to the initial cell
copy the Set rng = rng.Offset(1, 0)
to a new line before loop
also, your InStr
test will always fail
True
is -1, but the return from InStr
will be greater than 0 when the string is found. change the test to remove = True
new code:
Sub IfTest()
'This should split the information in a table up into cells
Dim Splitter() As String
Dim LenValue As Integer 'Gives the number of characters in date string
Dim LeftValue As Integer 'One less than the LenValue to drop the ")"
Dim rng As Range, cell As Range
Set rng = ActiveCell
Do While ActiveCell.Value <> Empty
If InStr(rng, "%") Then
ActiveCell.Offset(0, 0).Select
Splitter = Split(ActiveCell.Value, "% Change")
ActiveCell.Offset(0, 10).Select
ActiveCell.Value = Splitter(1)
ActiveCell.Offset(0, -1).Select
ActiveCell.Value = "% Change"
ActiveCell.Offset(1, -9).Select
Else
ActiveCell.Offset(0, 0).Select
Splitter = Split(ActiveCell.Value, "(")
ActiveCell.Offset(0, 9).Select
ActiveCell.Value = Splitter(0)
ActiveCell.Offset(0, 1).Select
LenValue = Len(Splitter(1))
LeftValue = LenValue - 1
ActiveCell.Value = Left(Splitter(1), LeftValue)
ActiveCell.Offset(1, -10).Select
End If
Set rng = rng.Offset(1, 0)
Loop
End Sub
I bumped into the same problem, I used:
if "Mel" in a["Names"].values:
print("Yep")
But this solution may be slower since internally pandas create a list from a Series.
You should have one listview in your mainlist.xml
file with id as @android:id/list
<ListView
android:id="@android:id/list"
android:layout_height="wrap_content"
android:layout_height="fill_parent"/>
XPath queries are case sensitive. Having looked at your example (which, by the way, is awesome, nobody seems to provide examples anymore!), I can get the result you want just by changing "business", to "Business"
//production[not(contains(category,'Business'))]
I have tested this by opening the XML file in Chrome, and using the Developer tools to execute that XPath queries, and it gave me just the Film category back.
I'd suggest using TradeKing's developer API. It is very good and free to use. All that is required is that you have an account with them and to my knowledge you don't have to carry a balance ... only to be registered.
Solution can be the following:
DECLARE @UnixTimeStamp bigint = 1564646400000 /*2019-08-01 11:00 AM*/
DECLARE @LocalTimeOffset bigint = DATEDIFF(MILLISECOND, GETDATE(), GETUTCDATE());
DECLARE @AdjustedTimeStamp bigint = @UnixTimeStamp - @LocalTimeOffset;
SELECT [DateTime] = DATEADD(SECOND, @AdjustedTimeStamp % 1000, DATEADD(SECOND, @AdjustedTimeStamp / 1000, '19700101'));
I hope this is helpful.
enum TESTENUM
{
T1 = 0,
T2 = 1,
T3 = 2,
T4 = 3
}
get string value
string enumValueString = "T1";
List<string> stringValueList = typeof(TESTENUM).GetEnumValues().Cast<object>().Select(m =>
Convert.ToString(m)
).ToList();
if(!stringValueList.Exists(m => m == enumValueString))
{
throw new Exception("cannot find type");
}
TESTENUM testEnumValueConvertString;
Enum.TryParse<TESTENUM>(enumValueString, out testEnumValueConvertString);
get integer value
int enumValueInt = 1;
List<int> enumValueIntList = typeof(TESTENUM).GetEnumValues().Cast<object>().Select(m =>
Convert.ToInt32(m)
).ToList();
if(!enumValueIntList.Exists(m => m == enumValueInt))
{
throw new Exception("cannot find type");
}
TESTENUM testEnumValueConvertInt;
Enum.TryParse<TESTENUM>(enumValueString, out testEnumValueConvertInt);
If you are splitting from Linux, you can still reassemble in Windows.
copy /b file1 + file2 + file3 + file4 filetogether
Working solution October 2018, for videos including audio channel
$(document).ready(function() {
$('video').prop('muted',true).play()
});
Have a look at another of mine, more in-depth answer: https://stackoverflow.com/a/57723549/3049675
This is an old question, and Jason's answer works fine, but I would like to add this:
ssh user@host <<'ENDSSH'
#commands to run on remote host
ENDSSH
This can also be used with su and commands which require user input. (note the '
escaped heredoc)
Edit: Since this answer keeps getting bits of traffic, i would add even more info to this wonderful use of heredoc:
You can nest commands with this syntax, and thats the only way nesting seems to work (in a sane way)
ssh user@host <<'ENDSSH'
#commands to run on remote host
ssh user@host2 <<'END2'
# Another bunch of commands on another host
wall <<'ENDWALL'
Error: Out of cheese
ENDWALL
ftp ftp.secureftp-test.com <<'ENDFTP'
test
test
ls
ENDFTP
END2
ENDSSH
You can actually have a conversation with some services like telnet, ftp, etc. But remember that heredoc just sends the stdin as text, it doesn't wait for response between lines
Edit: I just found out that you can indent the insides with tabs if you use <<-END
!
ssh user@host <<-'ENDSSH'
#commands to run on remote host
ssh user@host2 <<-'END2'
# Another bunch of commands on another host
wall <<-'ENDWALL'
Error: Out of cheese
ENDWALL
ftp ftp.secureftp-test.com <<-'ENDFTP'
test
test
ls
ENDFTP
END2
ENDSSH
(I think this should work)
If the constructor of a class is private then you cannot create an object for class from outside of it.
class Test{
int x, y;
private Test(){
.......
.......
}
}
We cannot create an object for above class from outside of it. So you cannot access x, y from outside of the class. Then what is the use of this class?
Here is the Answer : FACTORY method.
Add the below method in above class
public static Test getObject(){
return new Test();
}
So now you can create an object for this class from outside of it. Like the way...
Test t = Test.getObject();
Hence, a static method which returns the object of the class by executing its private constructor is called as FACTORY method
.
TCPDUMP is one of my favourite tools for analyzing network, but if you find difficult to cross-compile tcpdump for android, I'd recomend you to use some applications from the market.
These are the applications I was talking about:
Shark app works with rooted devices, so if you want to install it, be sure that you have your device already rooted.
Good luck ;)
Another approach with very few code (using Array reduce and Array includes):
arr1.length == arr2.length && arr1.reduce((a, b) => a && arr2.includes(b), true)
If you want to compare also the equality of order:
arr1.length == arr2.length && arr1.reduce((a, b, i) => a && arr2[i], true)
The length
check ensures that the set of elements in one array isn't just a subset of the other one.
The reducer is used to walk through one array and search for each item in other array. If one item isn't found the reduce function returns false
.
Then go to php folder directory, Suppose your php folder is in xampp folder on your c drive. Your command would then be:
cd c:\xampp\php
After that, check your version:
php -v
This should give the following output:
PHP 7.2.0 (cli) (built: Nov 29 2017 00:17:00) ( ZTS MSVC15 (Visual C++ 2017) x86 ) Copyright (c) 1997-2017 The PHP Group Zend Engine v3.2.0, Copyright (c) 1998-2017 Zend Technologies
I have uploaded a youtube video myself about checking the version of PHP via command prompt in Bangla: https://www.youtube.com/watch?v=zVkhD_tv9ck
SSL certificates are bound to a 'common name', which is usually a fully qualified domain name but can be a wildcard name (eg. *.domain.com) or even an IP address, but it usually isn't.
In your case, you are accessing your LDAP server by a hostname and it sounds like your two LDAP servers have different SSL certificates installed. Are you able to view (or download and view) the details of the SSL certificate? Each SSL certificate will have a unique serial numbers and fingerprint which will need to match. I assume the certificate is being rejected as these details don't match with what's in your certificate store.
Your solution will be to ensure that both LDAP servers have the same SSL certificate installed.
BTW - you can normally override DNS entries on your workstation by editing a local 'hosts' file, but I wouldn't recommend this.
Needed to do a reverse on $.each so i used Vinay idea:
//jQuery.each(collection, callback) =>
$.each($(collection).get().reverse(), callback func() {});
worked nicely, thanks
public class WeatherResponse {
private int cod;
private String base;
private Weather main;
public int getCod(){
return this.cod;
}
public void setCod(int cod){
this.cod = cod;
}
public String getBase(){
return base;
}
public void setBase(String base){
this.base = base;
}
public Weather getWeather() {
return main;
}
// default constructor, getters and setters
}
public class Weather {
private int id;
private String main;
private String description;
public String getMain(){
return main;
}
public void setMain(String main){
this.main = main;
}
public String getDescription(){
return description;
}
public void setDescription(String description){
this.description = description;
}
// default constructor, getters and setters
}
// accessing methods
// success!
Log.i("App", weatherResponse.getBase());
Log.i("App", weatherResponse.getWeather().getMain());
Log.i("App", weatherResponse.getWeather().getDescription());
An integration with Angular2 is also available through the ng2-bootstrap project : https://github.com/valor-software/ng2-bootstrap.
To install it simply put these files in your main HTML page:
<script src="https://cdnjs.cloudflare.com/ajax/libs/ng2-bootstrap/x.x.x/ng2-bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
Then you can use it into your components this way:
import {Component} from 'angular2/core';
import {Alert} from 'ng2-bootstrap/ng2-bootstrap';
@Component({
selector: 'my-app',
directives: [Alert],
template: `<alert type="info">ng2-bootstrap hello world!</alert>`
})
export class AppComponent {
}
You main Index.html file for Angular can use the body tag as the ng-view. Then all you need to do is include a script tag at the bottom of whatever page is being pulled into Index.html by Angular like so:
<script type="text/javascript">
$( function() {
$( "#mydatepickerid" ).datepicker({changeMonth: true, changeYear: true,
yearRange: '1930:'+new Date().getFullYear(), dateFormat: "yy-mm-dd"});
});
</script>
Why overcomplicate things??
You can use validDate.setTime(strDate) Have a look at the javadoc at http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html
An alternative way to accomplish what you are asking, without having problems on the mobile version of your website, (Remember that the margin attribute will brake your responsive layout on mobile version thus you have to add on your element a supplementary attribute like @media (min-width:768px){ 'your-class'{margin:0}}
to override the previous margin)
is to nest your class in your preferred div and then add on your class the margin option you want
like the following example: HTML
<div class="container">
<div class="col-md-3 col-xs-12">
<div class="events">
<img src="..." class="img-responsive" alt="...."/>
<div class="figcaption">
<h2>Event Title</h2>
<p>Event Description.</p>
</div>
</div>
</div>
<div class="col-md-3 col-xs-12">
<div class="events">
<img src="..." class="img-responsive" alt="...."/>
<div class="figcaption">
<h2>Event Title</h2>
<p>Event Description. </p>
</div>
</div>
</div>
<div class="col-md-3 col-xs-12">
<div class="events">
<img src="..." class="img-responsive" alt="...."/>
<div class="figcaption">
<h2>Event Title</h2>
<p>Event Description. </p>
</div>
</div>
</div>
</div>
And on your CSS you just add the margin option on your class which in this example is "events" like:
.events{
margin: 20px 10px;
}
By this method you will have all the wanted space between your divs making sure you do not brake anything on your website's mobile and tablet versions.
It doesn't work because you are using fill_parent as the width. The weight is used to distribute the remaining empty space or take away space when the total sum is larger than the LinearLayout. Set your widths to 0dip instead and it will work.
map(float, mylist)
should do it.
(In Python 3, map ceases to return a list object, so if you want a new list and not just something to iterate over, you either need list(map(float, mylist)
- or use SilentGhost's answer which arguably is more pythonic.)
The after_initialize callback pattern can be improved by simply doing the following
after_initialize :some_method_goes_here, :if => :new_record?
This has a non-trivial benefit if your init code needs to deal with associations, as the following code triggers a subtle n+1 if you read the initial record without including the associated.
class Account
has_one :config
after_initialize :init_config
def init_config
self.config ||= build_config
end
end
Because of an annoying design choice in Ruby before 1.9 — some_string[0]
returns the character code of the first character — the most portable way to write this is some_string[0,1]
, which tells it to get a substring at index 0 that's 1 character long.
You are using the pointer newFile
without allocating space for it.
struct stasher_file *newFile = malloc(sizeof(stasher_file));
Also you should put the struct name at the top. Where you specified stasher_file is to create an instance of that struct.
struct stasher_file {
char name[32];
int size;
int start;
int popularity;
};
Download http://download.cnet.com/Free-Desktop-Timer/3000-2350_4-75415517.html
Then add a button or something on the form and inside its event, just open this app ie:
{
Process.Start(@"C:\Program Files (x86)\Free Desktop Timer\DesktopTimer");
}
Hi you can try below methods with initialize of model.
Here you can initialize ng-model of textbox two way
- With use of ng-init
- With use of $scope in js
<!doctype html>
<html >
<head>
<title>Angular js initalize with ng-init and scope</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
</head>
<body ng-app="app" >
<h3>Initialize value with ng-init</h3>
<!-- Initlialize model values with ng-init -->
<div ng-init="user={fullname:'Bhaskar Bhatt',email:'[email protected]',address:'Ahmedabad'};">
Name : <input type="text" ng-model="user.fullname" /><br/>
Email : <input type="text" ng-model="user.email" /><br/>
Address:<input type="text" ng-model="user.address" /><br/>
</div>
<!-- initialize with js controller scope -->
<h3>Initialize with js controller</h3>
<div ng-controller="alpha">
Age:<input type="text" name="age" ng-model="user.age" /><br/>
Experience : <input type="text" name="experience" ng-model="user.exp" /><br/>
Skills : <input type="text" name="skills" ng-model="user.skills" /><br/>
</div>
</body>
<script type="text/javascript">
angular.module("app",[])
.controller("alpha",function($scope){
$scope.user={};
$scope.user.age=27;
$scope.user.exp="4+ years";
$scope.user.skills="Php,javascript,Jquery,Ajax,Mysql";
});
</script>
</html>
I might've over-engineered my own solution without realizing that Type.valueOf("enum string")
actually existed.
I guess it gives more granular control but I'm not sure it's really necessary.
public enum Type {
DEBIT,
CREDIT;
public static Map<String, Type> typeMapping = Maps.newHashMap();
static {
typeMapping.put(DEBIT.name(), DEBIT);
typeMapping.put(CREDIT.name(), CREDIT);
}
public static Type getType(String typeName) {
if (typeMapping.get(typeName) == null) {
throw new RuntimeException(String.format("There is no Type mapping with name (%s)"));
}
return typeMapping.get(typeName);
}
}
I guess you're exchanging IllegalArgumentException
for RuntimeException
(or whatever exception you wish to throw) which could potentially clean up code.
I’ve found the following library to be the most helpful when doing any kind of date math. I’m still amazed nothing like this is part of the .Net framework.
http://www.codeproject.com/Articles/168662/Time-Period-Library-for-NET
I know this has been answered, but I'd like to add my own answer:
using (var reader = new StringReader(multiLineString))
{
for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
{
// Do something with the line
}
}
It's ctrl + . when, for example, you try to type List
you need to type <
at the end and press ctrl + . for it to work.
This solution is not as powerful as others, but if you're a beginner and only know about for
loops it's still possible to find the first index of an item while avoiding the ValueError:
def find_element(p,t):
i = 0
for e in p:
if e == t:
return i
else:
i +=1
return -1
Most of the libraries commonly used in C++ can't print arrays, per se. You'll have to loop through it manually and print out each value.
Printing arrays and dumping many different kinds of objects is a feature of higher level languages.
Do you mean this?
var listOfList = new List<List<int>>() {
new List<int>() { 1, 2 },
new List<int>() { 3, 4 },
new List<int>() { 5, 6 }
};
var list = new List<int> { 9, 9, 9 };
var result = list.Concat(listOfList.SelectMany(x => x));
foreach (var x in result) Console.WriteLine(x);
Results in: 9 9 9 1 2 3 4 5 6
To have a constant date format irrespective of the computer settings, you must use 3 different input elements to capture day, month, and year respectively. However, you need to validate the user input to ensure that you have a valid date as shown bellow
<input id="txtDay" type="text" placeholder="DD" />
<input id="txtMonth" type="text" placeholder="MM" />
<input id="txtYear" type="text" placeholder="YYYY" />
<button id="but" onclick="validateDate()">Validate</button>
function validateDate() {
var date = new Date(document.getElementById("txtYear").value, document.getElementById("txtMonth").value, document.getElementById("txtDay").value);
if (date == "Invalid Date") {
alert("jnvalid date");
}
}
Since iOS 8 you can use NSCalendar.dateByAddingUnit
Example in Swift 1.x:
let today = NSDate()
let tomorrow = NSCalendar.currentCalendar()
.dateByAddingUnit(
.CalendarUnitDay,
value: 1,
toDate: today,
options: NSCalendarOptions(0)
)
Swift 2.0:
let today = NSDate()
let tomorrow = NSCalendar.currentCalendar()
.dateByAddingUnit(
.Day,
value: 1,
toDate: today,
options: []
)
Swift 3.0:
let today = Date()
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: today)
If you're not using the id
for anything other than code-behind reference (since .net mangles the ids), you could use a panel
control and reference it in your codebehind:
<asp:panel runat="server" id="classMe"></asp:panel>
classMe.cssClass = "someClass"
Although I don't know about asp.net mvc, but this is what we should do in a normal .net website. It should work for asp.net mvc also.
YourSessionClass obj=Session["key"] as YourSessionClass;
if(obj==null){
obj=new YourSessionClass();
Session["key"]=obj;
}
You would put this inside a method for easy access. HTH
This is mostly covered already, but one addition as I ran into an issue with the previous code samples.
Dim strHTML as String = System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath("~/folder/filename.html"))
Add
import {withRouter} from 'react-router-dom';
Then change your component export
export default withRouter(ComponentName)
Then you can access the route directly within the component itself (without touching anything else in your project) using:
window.location.pathname
Tested March 2020 with: "version": "5.1.2"
Use:
boolean(/*/*[@subjectIdentifier="Primary"]/*/*/*/*
[name()='AttachedXml'
and
namespace-uri()='http://xml.mycompany.com/XMLSchema'
]
)
Unless you absolutely have to convert the date to an integer, consider using a Double
instead to represent the time interval. After all, this is the type that timeIntervalSince1970
returns. All of the answers that convert to integers loose sub-millisecond precision, but this solution is much more accurate (although you will still lose some precision due to floating-point imprecision).
public extension Date {
/// The interval, in milliseconds, between the date value and
/// 00:00:00 UTC on 1 January 1970.
/// Equivalent to `self.timeIntervalSince1970 * 1000`.
var millisecondsSince1970: Double {
return self.timeIntervalSince1970 * 1000
}
/**
Creates a date value initialized relative to 00:00:00 UTC
on 1 January 1970 by a given number of **milliseconds**.
equivalent to
```
self.init(timeIntervalSince1970: TimeInterval(milliseconds) / 1000)
```
- Parameter millisecondsSince1970: A time interval in milliseconds.
*/
init(millisecondsSince1970: Double) {
self.init(timeIntervalSince1970: TimeInterval(milliseconds) / 1000)
}
}
For the JSON library to be available, you may have to install libjson-ruby
from your package manager.
To use the 'json' library:
require 'json'
To convert an object to JSON (these 3 ways are equivalent):
JSON.dump object #returns a JSON string
JSON.generate object #returns a JSON string
object.to_json #returns a JSON string
To convert JSON text to an object (these 2 ways are equivalent):
JSON.load string #returns an object
JSON.parse string #returns an object
It will be a bit more difficult for objects from your own classes. For the following class, to_json will produce something like "\"#<A:0xb76e5728>\""
.
class A
def initialize a=[1,2,3], b='hello'
@a = a
@b = b
end
end
This probably isn't desirable. To effectively serialise your object as JSON, you should create your own to_json method. To go with this, a from_json class method would be useful. You could extend your class like so:
class A
def to_json
{'a' => @a, 'b' => @b}.to_json
end
def self.from_json string
data = JSON.load string
self.new data['a'], data['b']
end
end
You could automate this by inheriting from a 'JSONable' class:
class JSONable
def to_json
hash = {}
self.instance_variables.each do |var|
hash[var] = self.instance_variable_get var
end
hash.to_json
end
def from_json! string
JSON.load(string).each do |var, val|
self.instance_variable_set var, val
end
end
end
Then you can use object.to_json
to serialise to JSON and object.from_json! string
to copy the saved state that was saved as the JSON string to the object.
At the moment (Chrome 39) I use this code to open a new tab:
window.open('http://www.stackoverflow.com', '_blank', 'toolbar=yes, location=yes, status=yes, menubar=yes, scrollbars=yes');
_x000D_
Of course this may change in future versions of Chrome.
It is a bad idea to use this if you can't control the browser your users are using. It may not work in future versions or with different settings.
If you also want the values you can use the inspect
module
import inspect
def func(a, b, c):
frame = inspect.currentframe()
args, _, _, values = inspect.getargvalues(frame)
print 'function name "%s"' % inspect.getframeinfo(frame)[2]
for i in args:
print " %s = %s" % (i, values[i])
return [(i, values[i]) for i in args]
>>> func(1, 2, 3)
function name "func"
a = 1
b = 2
c = 3
[('a', 1), ('b', 2), ('c', 3)]
For those like me who come to this page with this problem after updating Xcode but don't have an issue with the location setting, restarting my computer did the trick.
Yes, PHP_EOL
is ostensibly used to find the newline character in a cross-platform-compatible way, so it handles DOS/Unix issues.
Note that PHP_EOL represents the endline character for the current system. For instance, it will not find a Windows endline when executed on a unix-like system.
Also if you want to check WatchOS.
Swift
let watchOSVersion = WKInterfaceDevice.currentDevice().systemVersion
print("WatchOS version: \(watchOSVersion)")
Objective-C
NSString *watchOSVersion = [[WKInterfaceDevice currentDevice] systemVersion];
NSLog(@"WatchOS version: %@", watchOSVersion);
I encountered this error using MySQL in a different context (not within phpMyAdmin). GRANT and SET PASSWORD commands failed on a particular existing user, who was listed in the mysql.user table. In my case, it was fixed by running
FLUSH PRIVILEGES;
The documentation for this command says
Reloads the privileges from the grant tables in the mysql database.
The server caches information in memory as a result of GRANT and CREATE USER statements. This memory is not released by the corresponding REVOKE and DROP USER statements, so for a server that executes many instances of the statements that cause caching, there will be an increase in memory use. This cached memory can be freed with FLUSH PRIVILEGES.
Apparently the user table cache had reached an inconsistent state, causing this weird error message. More information is available here.
how about using limit 0,1
for mysql optimisation
and about your code:
$DBH = new PDO( "connection string goes here" );
$STH - $DBH -> prepare( "select figure from table1" );
$STH -> execute();
$result = $STH ->fetch(PDO::FETCH_ASSOC)
echo $result["figure"];
$DBH = null;
I recommend using this HttpURLConnection
instead HttpGet
. As HttpGet
is already deprecated in Android API level 22.
HttpURLConnection httpcon;
String url = null;
String data = null;
String result = null;
try {
//Connect
httpcon = (HttpURLConnection) ((new URL (url).openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestMethod("POST");
httpcon.connect();
//Write
OutputStream os = httpcon.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(data);
writer.close();
os.close();
//Read
BufferedReader br = new BufferedReader(new InputStreamReader(httpcon.getInputStream(),"UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
result = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I'm not sure if Windows' "shell" supports this, but on Linux:
print "\033[2J"
https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_codes
In my opinion calling cls
with os
is a bad idea generally. Imagine if I manage to change the cls or clear command on your system, and you run your script as admin or root.
As has been discussed elsewhere, the .length
property reference is failing because theHref
is undefined. However, be aware of any solution which involves comparing theHref
to undefined
, which is not a keyword in JavaScript and can be redefined.
For a full discussion of checking for undefined variables, see Detecting an undefined object property and the first answer in particular.
You can explicitly get back Identity columns using SqlServer's OUTPUT clause: Assuming you have an identity/auto-increment column called ID:
$sql='INSERT INTO [xyz].[myTable] (Field1, Field2, Field3) OUTPUT Inserted.ID VALUES (1, 2, '3')';
Note that in Perl DBI you would then execute the INSERT statement, just like it was a SELECT. And capture the output like it was a SELECT
$sth->execute($sql);
@row=$sth->fetchrow_array; #Only 1 val in 1 row returned
print "Inserted ID: ", $row[0], "\n";
Presumably this is preferable because it doesn't require another request.
I just made this little trick :
window.getRunningScript = () => {
return () => {
return new Error().stack.match(/([^ \n])*([a-z]*:\/\/\/?)*?[a-z0-9\/\\]*\.js/ig)[0]
}
}
console.log('%c Currently running script:', 'color: blue', getRunningScript()())
? Works on: Chrome, Firefox, Edge, Opera
Enjoy !
This link helped me boost npm installs. Force npm to use http over https and disable progress display.
This is not an easy one. I've come up with a Script solution. (I don't think this can be done using pure CSS)
the HTML stays the same as you posted, the CSS changes a little bit, JQuery code added.
Working Fiddle Tested on: IE10, IE9, IE8, FF, Chrome
BTW: if you have unique elements, why don't you use id's instead of classes? I think it gives a better selector performance.
Explanation of how it works:
inner-container
will span the entire space of the outer-container
(so basically, he's not needed) but I left him there, so you wont need to change you DOM.
the table-header
is relatively positioned, without a scroll (overflow: hidden
), we will handle his scroll later.
the table-body
have to span the rest of the inner-container
height, so I used a script to determine what height to fix him. (it changes dynamically when you re-size the window)
without a fixed height, the scroll wont appear, because the div will just grow large instead..
notice that this part can be done without script, if you fix the header height and use CSS3 (as shown in the end of the answer)
now it's just a matter of moving the header along with the body each time we scroll.
this is done by a function assigned to the scroll
event.
CSS (some of it was copied from your style)
*
{
padding: 0;
margin: 0;
}
body
{
height: 100%;
width: 100%;
}
table
{
border-collapse: collapse; /* make simple 1px lines borders if border defined */
}
.outer-container
{
background-color: #ccc;
position: absolute;
top:0;
left: 0;
right: 300px;
bottom: 40px;
}
.inner-container
{
height: 100%;
overflow: hidden;
}
.table-header
{
position: relative;
}
.table-body
{
overflow: auto;
}
.header-cell
{
background-color: yellow;
text-align: left;
height: 40px;
}
.body-cell
{
background-color: blue;
text-align: left;
}
.col1, .col3, .col4, .col5
{
width:120px;
min-width: 120px;
}
.col2
{
min-width: 300px;
}
JQuery
$(document).ready(function () {
setTableBody();
$(window).resize(setTableBody);
$(".table-body").scroll(function ()
{
$(".table-header").offset({ left: -1*this.scrollLeft });
});
});
function setTableBody()
{
$(".table-body").height($(".inner-container").height() - $(".table-header").height());
}
If you don't care about fixing the header height (I saw that you fixed the cell's height in your CSS), some of the Script can be skiped if you use CSS3 :Shorter Fiddle (this will not work on IE8)
Make sure the target window that you (or Facebook) is posting a message to, has completed loading. Most of the times I've gotten this error were when an iframe I was sending messages to had failed to load.
In swift you can subclass NSView and do this
class MyView:NSView {
required init?(coder: NSCoder) {
super.init(coder: coder);
self.wantsLayer = true;
self.layer?.backgroundColor = NSColor.redColor().CGColor;
}
}
You should not extend the JFrame
class unnecessarily (only if you are adding extra functionality to the JFrame
class)
JFrame:
JFrame
extends Component
and Container
.
It is a top level container used to represent the minimum requirements for a window. This includes Border
s, resizability (is the JFrame
resizeable?), title bar, controls (minimize/maximize allowed?), and event handlers for various Event
s like windowClose
, windowOpened
etc.
JPanel:
JPanel
extends Component
, Container
and JComponent
It is a generic class used to group other Component
s together.
It is useful when working with LayoutManager
s e.g. GridLayout
f.i adding components to different JPanel
s which will then be added to the JFrame
to create the gui. It will be more manageable in terms of Layout
and re-usability.
It is also useful for when painting/drawing in Swing, you would override paintComponent(..)
and of course have the full joys of double buffering.
A Swing GUI cannot exist without a top level container like (JWindow
, Window
, JFrame
Frame
or Applet
), while it may exist without JPanel
s.
The format is YYYY-MM-DD
. You cannot change it.
$('#myinput').val('2013-12-31');
sets value
Steps for MIUI 9 and Above:
Settings -> Additional Settings -> Developer options ->
Turn off "MIUI optimization" and Restart
Turn On "USB Debugging"
Turn On "Install via USB"
Set USB Configuration to Charging
Turn On "install via USB
MTP(Media Transfer Protocol) is the default mode.
Works even in MTP in some cases
I'd actually suggest using a solid open-source library as an http client. If you take a look at http client by ASF you'll find life a lot easier. It is an easy-to-use,scalable and robust client for http.
To insert entire data of table2
in table1
. Below is a query:
INSERT INTO TABLE table1 SELECT * FROM table2;
I think not. But styling body
with overflow: scroll
should do. You seem to know that, though.
Contrary to Mark Novakowski answer, which for some reason has been upvoted by many, yes, it is a valid and satisfiable request.
In fact the standard, as Wrikken pointed out, makes just such an example. In practice, Apache responds to such requests as expected (with a 206 code), and this is exactly what I use to implement progressive download, that is, only get the tail of a long log file which grows in real time with polling.
Check your index.html. If you have accidentally removed the following part, include it and it will be fine
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
The same error occurs if in DirectoryEntry.Patch is nothing after the symbols "LDAP//:". It is necessary to check the directoryEntry.Path before directorySearcher.FindOne(). Unless explicitly specified domain, and do not need to "LDAP://".
private void GetUser(string userName, string domainName)
{
DirectoryEntry dirEntry = new DirectoryEntry();
if (domainName.Length > 0)
{
dirEntry.Path = "LDAP://" + domainName;
}
DirectorySearcher dirSearcher = new DirectorySearcher(dirEntry);
dirSearcher.SearchScope = SearchScope.Subtree;
dirSearcher.Filter = string.Format("(&(objectClass=user)(|(cn={0})(sn={0}*)(givenName={0})(sAMAccountName={0}*)))", userName);
var searchResults = dirSearcher.FindAll();
//var searchResults = dirSearcher.FindOne();
if (searchResults.Count == 0)
{
MessageBox.Show("User not found");
}
else
{
foreach (SearchResult sr in searchResults)
{
var de = sr.GetDirectoryEntry();
string user = de.Properties["SAMAccountName"][0].ToString();
MessageBox.Show(user);
}
}
}
As of Java 7 (and Android API level 19):
System.lineSeparator()
Documentation: Java Platform SE 7
For older versions of Java, use:
System.getProperty("line.separator");
See https://java.sun.com/docs/books/tutorial/essential/environment/sysprop.html for other properties.
Making a class static just prevents people from trying to make an instance of it. If all your class has are static members it is a good practice to make the class itself static.
Select your range from cell A (or the whole columns by first selecting column A). Make sure that the 'lighter coloured' cell is A1 then go to conditional formatting, new rule:
Put the following formula and the choice of your formatting (notice that the 'lighter coloured' cell comes into play here, because it is being used in the formula):
=$A1<>$B1
Then press OK and that should do it.
The problem with your attempt at the psql
command line is the direction of the slashes:
newTestDB-# /i E:\db-rbl-restore-20120511_Dump-20120514.sql # incorrect
newTestDB-# \i E:/db-rbl-restore-20120511_Dump-20120514.sql # correct
To be clear, psql
commands start with a backslash, so you should have put \i
instead. What happened as a result of your typo is that psql
ignored everything until finding the first \
, which happened to be followed by db
, and \db
happens to be the psql
command for listing table spaces, hence why the output was a List of tablespaces. It was not a listing of "default tables of PostgreSQL" as you said.
Further, it seems that psql
expects the filepath
argument to delimit directories using the forward slash regardless of OS (thus on Windows this would be counter-intuitive).
It is worth noting that your attempt at "elevating permissions" had no relation to the outcome of the command you attempted to execute. Also, you did not say what caused the supposed "Permission Denied" error.
Finally, the extension on the dump file does not matter, in fact you don't even need an extension. Indeed, pgAdmin
suggests a .backup
extension when selecting a backup filename, but you can actually make it whatever you want, again, including having no extension at all. The problem is that pgAdmin
seems to only allow a "Restore" of "Custom or tar" or "Directory" dumps (at least this is the case in the MAC OS X version of the app), so just use the psql
\i
command as shown above.
var input = document.getElementById ("IdofInput");
input.placeholder = "No need to fill this field";
You can find out more about placeholder
here: http://help.dottoro.com/ljgugboo.php
I was getting this error due to something even simpler (you could even say trivial). I hadn't installed the pytest
module. So a simple apt install python-pytest
fixed it for me.
'pytest' would have been listed in setup.py as a test dependency. Make sure you install the test requirements as well.
my solution (supports leading 0s):
String pattern="^[0-9](\\d{1,2}|1?[0-9][0-9]|2?[0-4][0-9]|25?[0-5])?\\.(\\d{1,2}|1?[0-9][0-9]|2?[0-4][0-9]|25[0-5])?\\.(\\d{1,2}|1?[0-9][0-9]|2?[0-4][0-9]|25[0-5])?\\.(\\d{1,2}|1?[0-9][0-9]|2?[0-4][0-9]|25[0-5])?$";
If you need a cross-platform solution, try Boost's Program Options library.
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array( 'prev_text' >' Previous','post_type' => 'page', 'posts_per_page' => 5, 'paged' => $paged );
$wp_query = new WP_Query($args);
while ( have_posts() ) : the_post();
//get all pages
the_ID();
the_title();
//if you want specific page of content then write
if(get_the_ID=='11')//make sure to use get_the_ID instead the_ID
{
echo get_the_ID();
the_title();
the_content();
}
endwhile;
//if you want specific page of content then write in loop
if(get_the_ID=='11')//make sure to use get_the_ID instead the_ID
{
echo get_the_ID();
the_title();
the_content();
}
In Visual Studio 2017, you switch between Solution View and Folder View back and forth. I think this is a better option, because it will keep the solution cleaner. I use this to edit .gitignore, .md files, etc.
As drew_w said, you can find a good example here.
HTML
<div id="wrapper">
<div id="sidebar-wrapper">
<ul class="sidebar-nav">
<li class="sidebar-brand"><a href="#">Home</a></li>
<li><a href="#">Another link</a></li>
<li><a href="#">Next link</a></li>
<li><a href="#">Last link</a></li>
</ul>
</div>
<div id="page-content-wrapper">
<div class="page-content">
<div class="container">
<div class="row">
<div class="col-md-12">
<!-- content of page -->
</div>
</div>
</div>
</div>
</div>
</div>
CSS
#wrapper {
padding-left: 250px;
transition: all 0.4s ease 0s;
}
#sidebar-wrapper {
margin-left: -250px;
left: 250px;
width: 250px;
background: #CCC;
position: fixed;
height: 100%;
overflow-y: auto;
z-index: 1000;
transition: all 0.4s ease 0s;
}
#page-content-wrapper {
width: 100%;
}
.sidebar-nav {
position: absolute;
top: 0;
width: 250px;
list-style: none;
margin: 0;
padding: 0;
}
@media (max-width:767px) {
#wrapper {
padding-left: 0;
}
#sidebar-wrapper {
left: 0;
}
#wrapper.active {
position: relative;
left: 250px;
}
#wrapper.active #sidebar-wrapper {
left: 250px;
width: 250px;
transition: all 0.4s ease 0s;
}
}
To install OpenCV in Anaconda, start up the Anaconda command prompt and install OpenCV with
conda install -c https://conda.anaconda.org/menpo opencv3
Test that it works in your Anaconda Spyder or IPython console with
import cv2
You can also check the installed version using:
cv2.__version__
If you're running a single node cluster for some reason, you might simply need to do avoid replicas, like this:
curl -XPUT -H 'Content-Type: application/json' 'localhost:9200/_settings' -d '
{
"index" : {
"number_of_replicas" : 0
}
}'
Doing this you'll force to use es without replicas
I had the same problem when I upgraded jquery UI to 1.8.1 without upgrading the corresponding theme. Only is needed to upgrade the theme too and "auto" works again.
If you like haml, but want something even better check out http://jade-lang.com for node, I wrote haml.js as well :)
I had the same problem. When i was trying and testing on a browser on my PC machine i didn't have the "not a function" error, but when i tried on a virtual machine the error was popping. I'd solved it by adding the slick files on my web server and adding the urls of the css and js files from my web server to my html. Before that i was pulling the css and js from CDN.
The issue is that you are serializing your bean with a custom Gson
object while the application is attempting to deserialize your JSON with a Jackson ObjectMapper
(within MappingJackson2HttpMessageConverter
).
If you open up your server logs, you should see something like
Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of java.util.Date from String value '2013-34-10-10:34:31': not a valid representation (error: Failed to parse Date value '2013-34-10-10:34:31': Can not parse date "2013-34-10-10:34:31": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))
at [Source: java.io.StringReader@baea1ed; line: 1, column: 20] (through reference chain: com.spring.Bean["publicationDate"])
among other stack traces.
One solution is to set your Gson
date format to one of the above (in the stacktrace).
The alternative is to register your own MappingJackson2HttpMessageConverter
by configuring your own ObjectMapper
to have the same date format as your Gson
.
Can you include some code? I add style="display:none;"
to my table rows all the time and it effectively hides the entire row.
If you use docker in your dev you can do this in another shell: docker attach running_node_app_container_name
That will show you STDOUT and STDERR.
You can do this without any JavaScript involved
(Using accepted answer)
HTML
<table class="table table-bordered table-striped">
<tr>
<td><button class="btn" data-target="#collapseme" data-toggle="collapse" type="button">Click to expand</button></td>
</tr>
<tr>
<td class="nopadding">
<div class="collapse" id="collapseme">
<div class="content">
Show me collapsed
</div>
</div>
</td>
</tr>
</table>
CSS
.nopadding {
padding: 0 !important;
}
.content {
padding: 20px;
}
Here's a nice answer from the FAQ on the scipy.org website:
What advantages do NumPy arrays offer over (nested) Python lists?
Python’s lists are efficient general-purpose containers. They support (fairly) efficient insertion, deletion, appending, and concatenation, and Python’s list comprehensions make them easy to construct and manipulate. However, they have certain limitations: they don’t support “vectorized” operations like elementwise addition and multiplication, and the fact that they can contain objects of differing types mean that Python must store type information for every element, and must execute type dispatching code when operating on each element. This also means that very few list operations can be carried out by efficient C loops – each iteration would require type checks and other Python API bookkeeping.
String val = "hi hello prince";
String arr[] = val.split(" ");
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i]);
}
Does this work?
float flt = 145.664454;
Double dbl = 0.0;
dbl += flt;
In my case I rename a component file, an VS Code add the below line of code for me:
import React, { Component } from "./node_modules/react";
So I fixed by removing the: ./node_modules/
import React, { Component } from "react";
Cheers!
You can do this using jQuery:
This method gets a list of its children then counts the length of that list, as simple as that.
$("ul").find("*").length;
The find() method traverses DOM downwards along descendants, all the way down to the last descendant.
Note: children() method traverses a single level down the DOM tree.
More RAM.
Someone talked about RAM drives in another answer. I did this with a 80286 and Turbo C++ (shows age) and the results were phenomenal. As was the loss of data when the machine crashed.
This doesn't work in IE6, which may be an issue, but it'll work in IE7+ and Firefox, Safari etc. It'll align the 3rd column right and all of the subsequent columns left.
td + td + td { text-align: right; }
td + td + td + td { text-align: left; }
Step 1: a great tool - http://json2csharp.com/ - the results generated by it are below
Step 2: JToken.Parse(...).ToObject<RootObject>()
.
public class Meta
{
public int code { get; set; }
public string status { get; set; }
public string method_name { get; set; }
}
public class Photos
{
public int total_count { get; set; }
}
public class Storage
{
public int used { get; set; }
}
public class Stats
{
public Photos photos { get; set; }
public Storage storage { get; set; }
}
public class From
{
public string id { get; set; }
public string first_name { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public List<object> external_accounts { get; set; }
public string email { get; set; }
public string confirmed_at { get; set; }
public string username { get; set; }
public string admin { get; set; }
public Stats stats { get; set; }
}
public class ParticipateUser
{
public string id { get; set; }
public string first_name { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public List<object> external_accounts { get; set; }
public string email { get; set; }
public string confirmed_at { get; set; }
public string username { get; set; }
public string admin { get; set; }
public Stats stats { get; set; }
}
public class ChatGroup
{
public string id { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public string message { get; set; }
public List<ParticipateUser> participate_users { get; set; }
}
public class Chat
{
public string id { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public string message { get; set; }
public From from { get; set; }
public ChatGroup chat_group { get; set; }
}
public class Response
{
public List<Chat> chats { get; set; }
}
public class RootObject
{
public Meta meta { get; set; }
public Response response { get; set; }
}
In VB.NET using Function,
Dim query = From order In dc.Orders
From vendor In
dc.Vendors.Where(Function(v) v.Id = order.VendorId).DefaultIfEmpty()
From status In
dc.Status.Where(Function(s) s.Id = order.StatusId).DefaultIfEmpty()
Select Order = order, Vendor = vendor, Status = status
Capture the PID of the ngnix process in a variable (for example $NGNIX_PID) and at the end of the entrypoint file do
wait $NGNIX_PID
In that way, your container should run until ngnix is alive, when ngnix stops, the container stops as well
An HTML response from the web server normally indicates that an error page has been served instead of the response from the WCF service. My first suggestion would be to check that the user you're running the WCF client under has access to the resource.
An easier solution is to use the user:pass@host format directly in the URL.
Using the request library:
var request = require('request'),
username = "john",
password = "1234",
url = "http://" + username + ":" + password + "@www.example.com";
request(
{
url : url
},
function (error, response, body) {
// Do more stuff with 'body' here
}
);
I've written a little blogpost about this as well.
Something like:
>>> l = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847']
>>> [i.split('\t', 1)[0] for i in l]
['element1', 'element2', 'element3']
Solution for macOS
AndroidStudio.app
-> show Package Contents -> MacOS studio
-executable in a terminalsudo
! (Ctrl+A
places your cursor in front)https://www.youtube.com/watch?v=ZPnu3Nrd1u0&feature=youtu.be
The task gives you all the goodness of the task API:
Task.ContinueWith
)Note that in both cases you can make your code slightly simpler with method group conversions:
DataInThread = new Thread(ThreadProcedure);
// Or...
Task t = Task.Factory.StartNew(ThreadProcedure);
Unfortunately, the best thing I have seen is the jquery.combobox, but it doesn't really look like something I'd really want to use in my web applications. I think there are some usability issues with this control, but as a user I don't think I'd know to start typing for the dropdownlist to turn into a textbox.
I much prefer the Combo Dropdown Box, but it still has some features that I'd want and it's still in alpha. The only think I don't like about this other than its being alpha... is that once I type in the combobox, the original dropdownlist items disappear. However, maybe there is a setting for this... or maybe it could be added fairly easily.
Those are the only two options that I know of. Good luck in your search. I'd love to hear if you find one or if the second option works out for you.
You can use in
operator in conjunction with lower
method of strings.
if "mandy" in line.lower():
Member functions that do not modify the class instance should be declared as const
:
int getId() const {
return id;
}
string getName() const {
return name;
}
Anytime you see "discards qualifiers", it's talking about const
or volatile
.
We have an application that allows the user to set "parameters" in the page. What we do is set those params on the URL, using React Router (in conjunction with History) and a library that URI-encodes JavaScript objects into a format that can be used as your query string.
When the user selects an option, we can push the value of that onto the current route with:
history.push({pathname: 'path/', search: '?' + Qs.stringify(params)});
pathname
can be the current path. In your case params
would look something like:
{
selectedOption: 5
}
Then at the top level of the React tree, React Router will update the props
of that component with a prop of location.search
which is the encoded value we set earlier, so there will be something in componentWillReceiveProps
like:
params = Qs.parse(nextProps.location.search.substring(1));
this.setState({selectedOption: params.selectedOption});
Then that component and its children will re-render with the updated setting. As the information is on the URL it can be bookmarked (or emailed around - this was our use case) and a refresh will leave the app in the same state. This has been working really well for our application.
React Router: https://github.com/reactjs/react-router
History: https://github.com/ReactTraining/history
The query string library: https://github.com/ljharb/qs
The fix, for me, was to add the following to the top of the php file which was being requested.
header("Cache-Control: no-cache,no-store");
Setting locales in terminal resolved the issue for me. Open the terminal and
Check if locale settings are missing
> locale
LANG=
LC_COLLATE="C"
LC_CTYPE="UTF-8"
LC_MESSAGES="C"
LC_MONETARY="C"
LC_NUMERIC="C"
LC_TIME="C"
LC_ALL=
Edit ~/.profile
or ~/.bashrc
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
Run . ~/.profile
or . ~/.bashrc
to read from the file.
Open a new terminal window and check that the locales are properly set
> locale
LANG="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_CTYPE="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_ALL="en_US.UTF-8"
System read-only variable %CD%
keeps the path of the caller of the batch, not the batch file location.
You can get the name of the batch script itself as typed by the user with %0
(e.g. scripts\mybatch.bat
). Parameter extensions can be applied to this so %~dp0
will return the Drive and Path to the batch script (e.g. W:\scripts\
) and %~f0
will return the full pathname (e.g. W:\scripts\mybatch.cmd
).
You can refer to other files in the same folder as the batch script by using this syntax:
CALL %0\..\SecondBatch.cmd
This can even be used in a subroutine, Echo %0
will give the call label but, echo "%~nx0"
will give you the filename of the batch script.
When the %0
variable is expanded, the result is enclosed in quotation marks.
Yours: Lowest possible is min, highest possible is max+min-1
Google: Lowest possible is min, highest possible is max-1
I had the same problem and solved it by changing the value for the param max_execution_time
in php.ini
, like this:
max_execution_time = 360 ; Maximum execution time of each script, in seconds (I CHANGED THIS VALUE)
max_input_time = 120 ; Maximum amount of time each script may spend parsing request data
;max_input_nesting_level = 64 ; Maximum input variable nesting level
memory_limit = 128M ; Maximum amount of memory a script may consume (128MB by default)
I hope this could help you.
I honestly doubt it, for a number of reasons, but the most important one is that there are some instructions that are allowed in 32-bit mode, but not in 64-bit mode. Specifically, the REX prefix that is used to encode some instructions and registers in 64-bit mode is a byte of the form 0x4f:0x40, but in 32 bit mode the same byte is either INC or DEC with a fixed operand.
Because of this, any 64-bit instruction that is prefixed by REX will be interpreted as either INC or DEC, and won't give the VMM the chance to emulate the 64-bit instruction (for instance by signaling an undefined opcode exception).
The only way it might be done is to use a trap exception to return to the VMM after each and every instruction so that it can see if it needs special 64-bit handling. I simply can't see that happening.
neither try any above ways nor sudo apt autoremove python3
because it will remove all gnome based applications from your system including gnome-terminal. In case if you have done that mistake and left with kernal only than trysudo apt install gnome
on kernal.
try to change your default python version instead removing it. you can do this through bashrc file or export path command.
I routinely use INSERT IGNORE
, and it sounds like exactly the kind of behavior you're looking for as well. As long as you know that rows which would cause index conflicts will not be inserted and you plan your program accordingly, it shouldn't cause any trouble.
According the google docs
this happened because the url
on which you are using the Google Maps API, it not registered
in list of allowed referrers
EDIT :
From Google Docs
All subdomains of a specified domain are also authorized.
If http://example.com is authorized, then http://www.example.com is also authorized. The reverse is not true: if http://www.example.com is authorized, http://example.com is not necessarily authorized
So,Please configure http://testdomain.com
domain, then your http://www.testdomain.com
will start work.
You can animate it after the fadeIn completes using the callback as shown below:
$("#Friends").fadeIn('slow',function(){
$(this).animate({'top': '-=30px'},'slow');
});
I tried lot of ways and then I decided to write my own. So here it is:
bool IsBetween (float x, float b1, float b2)
{
return ( ((x >= (b1 - 0.1f)) &&
(x <= (b2 + 0.1f))) ||
((x >= (b2 - 0.1f)) &&
(x <= (b1 + 0.1f))));
}
bool IsSegmentsColliding( POINTFLOAT lineA,
POINTFLOAT lineB,
POINTFLOAT line2A,
POINTFLOAT line2B)
{
float deltaX1 = lineB.x - lineA.x;
float deltaX2 = line2B.x - line2A.x;
float deltaY1 = lineB.y - lineA.y;
float deltaY2 = line2B.y - line2A.y;
if (abs(deltaX1) < 0.01f &&
abs(deltaX2) < 0.01f) // Both are vertical lines
return false;
if (abs((deltaY1 / deltaX1) -
(deltaY2 / deltaX2)) < 0.001f) // Two parallel line
return false;
float xCol = ( ( (deltaX1 * deltaX2) *
(line2A.y - lineA.y)) -
(line2A.x * deltaY2 * deltaX1) +
(lineA.x * deltaY1 * deltaX2)) /
((deltaY1 * deltaX2) - (deltaY2 * deltaX1));
float yCol = 0;
if (deltaX1 < 0.01f) // L1 is a vertical line
yCol = ((xCol * deltaY2) +
(line2A.y * deltaX2) -
(line2A.x * deltaY2)) / deltaX2;
else // L1 is acceptable
yCol = ((xCol * deltaY1) +
(lineA.y * deltaX1) -
(lineA.x * deltaY1)) / deltaX1;
bool isCol = IsBetween(xCol, lineA.x, lineB.x) &&
IsBetween(yCol, lineA.y, lineB.y) &&
IsBetween(xCol, line2A.x, line2B.x) &&
IsBetween(yCol, line2A.y, line2B.y);
return isCol;
}
Based on these two formulas: (I simplified them from equation of lines and other formulas)
I had the same situation and I found a way around with a bit of engineering as follows - -
You have to have your method in parent class without any parameter and use - -
Class<? extends Person> cl = this.getClass(); // inside parent class
Now, with 'cl' you can access all child class fields with their name and initialized values by using - -
cl.getDeclaredFields(); cl.getField("myfield"); // and many more
In this situation your 'this' pointer will reference your child class object if you are calling parent method through your child class object.
Another thing you might need to use is Object obj = cl.newInstance();
Let me know if still you got stucked somewhere.
For me, fny answers really got it all. since fetch is not throwing error, we need to throw/handle the error ourselves. Posting my solution with async/await. I think it's more strait forward and readable
Solution 1: Not throwing an error, handle the error ourselves
async _fetch(request) {
const fetchResult = await fetch(request); //Making the req
const result = await fetchResult.json(); // parsing the response
if (fetchResult.ok) {
return result; // return success object
}
const responseError = {
type: 'Error',
message: result.message || 'Something went wrong',
data: result.data || '',
code: result.code || '',
};
const error = new Error();
error.info = responseError;
return (error);
}
Here if we getting an error, we are building an error object, plain JS object and returning it, the con is that we need to handle it outside. How to use:
const userSaved = await apiCall(data); // calling fetch
if (userSaved instanceof Error) {
debug.log('Failed saving user', userSaved); // handle error
return;
}
debug.log('Success saving user', userSaved); // handle success
Solution 2: Throwing an error, using try/catch
async _fetch(request) {
const fetchResult = await fetch(request);
const result = await fetchResult.json();
if (fetchResult.ok) {
return result;
}
const responseError = {
type: 'Error',
message: result.message || 'Something went wrong',
data: result.data || '',
code: result.code || '',
};
let error = new Error();
error = { ...error, ...responseError };
throw (error);
}
Here we are throwing and error that we created, since Error ctor approve only string, Im creating the plain Error js object, and the use will be:
try {
const userSaved = await apiCall(data); // calling fetch
debug.log('Success saving user', userSaved); // handle success
} catch (e) {
debug.log('Failed saving user', userSaved); // handle error
}
Solution 3: Using customer error
async _fetch(request) {
const fetchResult = await fetch(request);
const result = await fetchResult.json();
if (fetchResult.ok) {
return result;
}
throw new ClassError(result.message, result.data, result.code);
}
And:
class ClassError extends Error {
constructor(message = 'Something went wrong', data = '', code = '') {
super();
this.message = message;
this.data = data;
this.code = code;
}
}
Hope it helped.
You can use the Web API FontFace constructor (also Typescript) without need of CSS:
export async function loadFont(fontFamily: string, url: string): Promise<void> {
const font = new FontFace(fontFamily, `local(${fontFamily}), url(${url})`);
// wait for font to be loaded
await font.load();
// add font to document
document.fonts.add(font);
// enable font with CSS class
document.body.classList.add("fonts-loaded");
}
import ComicSans from "./assets/fonts/ComicSans.ttf";
loadFont("Comic Sans ", ComicSans).catch((e) => {
console.log(e);
});
Declare a file font.ts
with your modules (TS only):
declare module "*.ttf";
declare module "*.woff";
declare module "*.woff2";
If TS cannot find FontFace type as its still officially WIP, add this declaration to your project. It will work in your browser, except for IE.
If you simply call interrupt()
, the thread will not automatically be closed. Instead, the Thread might even continue living, if isInterrupted()
is implemented accordingly. The only way to guaranteedly close a thread, as asked for by OP, is
Thread.currentThread().stop();
Method is deprecated, however.
Calling return
only returns from the current method. This only terminates the thread if you're at its top level.
Nevertheless, you should work with interrupt()
and build your code around it.
you need to decode the bytes
of you want a string:
b = b'1234'
print(b.decode('utf-8')) # '1234'
if you use docker-compose, maybe it can work:
iptables -I INPUT ! -i eth0 -p tcp --dport 8001 -j ACCEPT
the eth0
is your network interface that connect internet, and 8081
the host server port
the best way for iptables rule is iptables TRACE
sort
sorts inplace so returns nothing:
In [54]:
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].unique()
a.sort()
a
Out[54]:
array([1, 2, 3, 6, 8], dtype=int64)
So you have to call print a
again after the call to sort
.
Eg.:
In [55]:
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].unique()
a.sort()
print(a)
[1 2 3 6 8]
Alternative to sp_defaultdb (which will be removed in a future version of Microsoft SQL Server) could be ALTER LOGIN
:
ALTER LOGIN [my_user_name] WITH DEFAULT_DATABASE = [new_default_database]
Note: unlike the sp_defaultdb
solution user and database names are provided without quotes. Brackets are needed if name had special chars (most common example will be domain user which is domain\username
and won't work without brackets).
For Xampp 7.3.9
PHP.ini
line 913:
;extension=imap
You should remove the semicolon.
If the browser uses this attribute, it is only as an help for the user, so he won't upload a multi-megabyte file just to see it rejected by the server...
Same for the <input type="hidden" name="MAX_FILE_SIZE" value="100000">
tag: if the browser uses it, it won't send the file but an error resulting in UPLOAD_ERR_FORM_SIZE
(2) error in PHP (not sure how it is handled in other languages).
Note these are helps for the user. Of course, the server must always check the type and size of the file on its end: it is easy to tamper with these values on the client side.
Use max-width on modal-dialog for angular 5
.mod-class .modal-dialog {
max-width: 1000px;
}
and use windowClass as others recommended, TS eg:
this.modalService.open(content, { windowClass: 'mod-class' }).result.then(
(result) => {
// this.closeResult = `Closed with: ${result}`;
}, (reason) => {
// this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
});
Also, I had to put the css code in global styles > styles.css.
In my case since I had a jump host or Bastion host on the way, and because the signatures on these bastion nodes had changed since they were imported into known_hosts file, I just needed to delete those entries/lines from the following file:
/Users/a.abdi-kelishami/.ssh/known_hosts
From above file, delete those lines referring to the bastion hosts.
"A call stack is composed of stack frames..." — Wikipedia
A stack frame is a thing that you put on the stack. They are data structures that contain information about subroutines to call.
The struct module mimics C structures. It takes more CPU cycles for a processor to read a 16-bit word on an odd address or a 32-bit dword on an address not divisible by 4, so structures add "pad bytes" to make structure members fall on natural boundaries. Consider:
struct { 11
char a; 012345678901
short b; ------------
char c; axbbcxxxdddd
int d;
};
This structure will occupy 12 bytes of memory (x being pad bytes).
Python works similarly (see the struct documentation):
>>> import struct
>>> struct.pack('BHBL',1,2,3,4)
'\x01\x00\x02\x00\x03\x00\x00\x00\x04\x00\x00\x00'
>>> struct.calcsize('BHBL')
12
Compilers usually have a way of eliminating padding. In Python, any of =<>! will eliminate padding:
>>> struct.calcsize('=BHBL')
8
>>> struct.pack('=BHBL',1,2,3,4)
'\x01\x02\x00\x03\x04\x00\x00\x00'
Beware of letting struct handle padding. In C, these structures:
struct A { struct B {
short a; int a;
char b; char b;
}; };
are typically 4 and 8 bytes, respectively. The padding occurs at the end of the structure in case the structures are used in an array. This keeps the 'a' members aligned on correct boundaries for structures later in the array. Python's struct module does not pad at the end:
>>> struct.pack('LB',1,2)
'\x01\x00\x00\x00\x02'
>>> struct.pack('LBLB',1,2,3,4)
'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04'
try this to close the connection:
socket.close();
and if you want to open it again:
socket.connect();
Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.
So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.
Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.
Works for primitives and immutable classes like String
, Wrapper classes Character, Byte.
int i=0,j=2
String s1,s2
s1 = s2 = "java rocks"
For mutable classes
Reference r1 = Reference r2 = Reference r3 = new Object();`
Three references + one object are created. All references point to the same object and your program will misbehave.
You could implement a JavaScript block which contains a function with your needs.
<div style="position: absolute; left: 10px; top: 40px;">
<img src="logg.png" width="114" height="38" onclick="DoSomething();" />
</div>
You should not be setting the class of your view controller to be a subclass of UIView
in Interface Builder. That is most definitely at least part of your problem. Leave that as either UIViewController
, some subclass of it, or some other custom class you have.
As for loading only a view from a xib, I was under the assumption that you had to have some sort of view controller (even if it doesn't extend UIViewController
, which may be too heavyweight for your needs) set as the File's Owner in Interface Builder if you want to use it to define your interface. I did a little research to confirm this as well. This is because otherwise there would be no way to access any of the interface elements in the UIView
, nor would there be a way to have your own methods in code be triggered by events.
If you use a UIViewController
as your File's Owner for your views, you can just use initWithNibName:bundle:
to load it and get the view controller object back. In IB, make sure you set the view
outlet to the view with your interface in the xib. If you use some other type of object as your File's Owner, you'll need to use NSBundle
's loadNibNamed:owner:options:
method to load the nib, passing an instance of File's Owner to the method. All its properties will be set properly according to the outlets you define in IB.
Following solution worked for me
First you need to add this registry key
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\SideBySide\PreferExternalManifest (DWORD) to 1
Next, a manifest file with the same name as the executable must be present in the same folder as the executable. The file is named eclipse.exe.manifest and consists of:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0" xmlns:asmv3="urn:schemas-microsoft-com:asm.v3">
<description>eclipse</description>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges>
<requestedExecutionLevel xmlns:ms_asmv3="urn:schemas-microsoft-com:asm.v3"
level="asInvoker"
ms_asmv3:uiAccess="false">
</requestedExecutionLevel>
</requestedPrivileges>
</security>
</trustInfo>
<asmv3:application>
<asmv3:windowsSettings xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">
<ms_windowsSettings:dpiAware xmlns:ms_windowsSettings="http://schemas.microsoft.com/SMI/2005/WindowsSettings">false</ms_windowsSettings:dpiAware>
</asmv3:windowsSettings>
</asmv3:application>
</assembly>
you can find more details here
Creating static library worked for me, compiling using g++ -static
. It bundles the dependent libraries along with the build.
One can simply retrieve view object as mentioned below
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = DataBindingUtil.inflate(inflater, R.layout.layout_file, container, false).getRoot();
return view;
}
I've downloaded these packages:
I then unpacked them and added the directories to LD_LIBRARY_PATH
in my ~/.bashrc
. Just make sure to add proper dirs to the path.
You will have to save the relationship on the server side. The value is the only part that is transmitted when the form is posted. You could do something nasty like...
<option value="2|Dog">Dog</option>
Then split the result apart if you really wanted to, but that is an ugly hack and a waste of bandwidth assuming the numbers are truly unique and have a one to one relationship with the text.
The best way would be to create an array, and loop over the array to create the HTML. Once the form is posted you can use the value to look up the text in that same array.
Can the screenshot or icon be transformed (scaled, rotated, skewed ...)? There are quite a few methods on top of my head that could possibly help you:
Most of these are already implemented in OpenCV - see for example the cvMatchTemplate method (uses histogram matching): http://dasl.mem.drexel.edu/~noahKuntz/openCVTut6.html. The salient point/area detectors are also available - see OpenCV Feature Detection.
The command line flags -N
or --LINE-NUMBERS
causes a line number to be displayed at the beginning of each line in the display.
You can also toggle line numbers without quitting less
by typing -N<return>
. It it possible to toggle any of less
's command line options in this way.
If it is not necessary turn off 'Enable 32-bit Applications' from your respective application pool of your website.
This worked for me on my local machine
The error means that your are trying to look up JNDI name, that is not attached to any EJB component - the component with that name does not exist.
As far as dir structure is concerned: you have to create a JAR file with EJB components. As I understand you want to play with EJB 2.X components (at least the linked example suggests that) so the structure of the JAR file should be:
/com/mypackage/MyEJB.class /com/mypackage/MyEJBInterface.class /com/mypackage/etc... etc... java classes /META-INF/ejb-jar.xml /META-INF/jboss.xml
The JAR file is more or less ZIP file with file extension changed from ZIP to JAR.
BTW. If you use JBoss 5, you can work with EJB 3.0, which are much more easier to configure. The simplest component is
@Stateless(mappedName="MyComponentName")
@Remote(MyEJBInterface.class)
public class MyEJB implements MyEJBInterface{
public void bussinesMethod(){
}
}
No ejb-jar.xml, jboss.xml is needed, just EJB JAR with MyEJB and MyEJBInterface compiled classes.
Now in your client code you need to lookup "MyComponentName".
app:cardBackgroundColor="#488747"
use this in your card view and you can change a color of your card view
The time() function displays the seconds between now and the unix epoch , 01 01 1970 (00:00:00 GMT). The strtotime() transforms a normal date format into a time() format. So the representation of that date into seconds will be : 1388516401
Source: http://www.php.net/time
You can use following regular expression construct
Punctuation: One of !"#$%&'()*+,-./:;<=>?@[]^_`{|}~
inputString.replaceAll("\\p{Punct}", "");
Try this:
From this question.
Although some of them are correct, I've found quite confusing the previous responses. At the same time, the OP asked for a solution without setting a custom header or using beforeSend
, so I've being looking for a clearer explanation. I hope my conclusions provide some light to others.
The code
jQuery.ajax({
....
accepts: "application/json; charset=utf-8",
....
});
doesn't work because accepts
must be a PlainObject
(not a String
) according to the jQuery doc (http://api.jquery.com/jquery.ajax/). Specifically, jQuery expect zero or more key-value pairs relating each dataType
with the accepted MIME type for them. So what I've finally using is:
jQuery.ajax({
....
dataType: 'json',
accepts: {
json: 'application/json'
},
....
});
Normally I would agree with Yaakov Ellis but in this special case there is another viable solution:
Use two tables:
Table: Item
Columns: ItemID, Title, Content
Indexes: ItemID
Table: Tag
Columns: ItemID, Title
Indexes: ItemId, Title
This has some major advantages:
First it makes development much simpler: in the three-table solution for insert and update of item
you have to lookup the Tag
table to see if there are already entries. Then you have to join them with new ones. This is no trivial task.
Then it makes queries simpler (and perhaps faster). There are three major database queries which you will do: Output all Tags
for one Item
, draw a Tag-Cloud and select all items for one Tag Title.
All Tags for one Item:
3-Table:
SELECT Tag.Title
FROM Tag
JOIN ItemTag ON Tag.TagID = ItemTag.TagID
WHERE ItemTag.ItemID = :id
2-Table:
SELECT Tag.Title
FROM Tag
WHERE Tag.ItemID = :id
Tag-Cloud:
3-Table:
SELECT Tag.Title, count(*)
FROM Tag
JOIN ItemTag ON Tag.TagID = ItemTag.TagID
GROUP BY Tag.Title
2-Table:
SELECT Tag.Title, count(*)
FROM Tag
GROUP BY Tag.Title
Items for one Tag:
3-Table:
SELECT Item.*
FROM Item
JOIN ItemTag ON Item.ItemID = ItemTag.ItemID
JOIN Tag ON ItemTag.TagID = Tag.TagID
WHERE Tag.Title = :title
2-Table:
SELECT Item.*
FROM Item
JOIN Tag ON Item.ItemID = Tag.ItemID
WHERE Tag.Title = :title
But there are some drawbacks, too: It could take more space in the database (which could lead to more disk operations which is slower) and it's not normalized which could lead to inconsistencies.
The size argument is not that strong because the very nature of tags is that they are normally pretty small so the size increase is not a large one. One could argue that the query for the tag title is much faster in a small table which contains each tag only once and this certainly is true. But taking in regard the savings for not having to join and the fact that you can build a good index on them could easily compensate for this. This of course depends heavily on the size of the database you are using.
The inconsistency argument is a little moot too. Tags are free text fields and there is no expected operation like 'rename all tags "foo" to "bar"'.
So tldr: I would go for the two-table solution. (In fact I'm going to. I found this article to see if there are valid arguments against it.)
You could try Jsonium tool http://jsonium.org- nice free tool specialized on requests with JSON in bodies and responses