Change <?php echo $proxy ?>
to ' . $proxy . '
.
You use <?php
when you're outputting HTML by leaving PHP mode with ?>
. When you using echo
, you have to use concatenation, or wrap your string in double quotes and use interpolation.
I solved "NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver" on my ASUS laptop with GTX 950m and Ubuntu 18.04 by disabling Secure Boot Control from BIOS.
You should note that div tag behaves like nothing and just let you to put something in it. It means that if you insert a paragraph with 100 lines of text within a div tag, it shows all the text but its height won't change to contain all the text.
So you have to use a CSS & HTML trick to handle this issue. This trick is very simple. you must use an empty div tag with class="clear" and then you will have to add this class to your CSS. Also note that your have #wrap in your CSS file but you don't have any tag with this id. In summary you have to change you code to something like below:
HTML Code:
<!-- Change "id" from "container" to "wrap" -->
<div id="wrap">
<div id="header">
</div>
<div id="navigation">
<a href="/" class="navigation">home</a>
<a href="about.php" class="navigation">about</a>
<a href="fanlisting.php" class="navigation">fanlisting</a>
<a href="reasons.php" class="navigation">100 reasons</a>
<a href="letter.php" class="navigation">letter</a>
</div>
<div id="content" >
<h1>Update Information</h1>
<iframe name="frame" id="frame" src="http://website.org/update.php" allowtransparency="true" frameborder="0"></iframe>
<!-- Add this line -->
<div class="clear"></div>
</div>
<div id="footer">
</div>
<!-- Add this line -->
<div class="clear"></div>
</div>
And also add this line to your CSS file:
.clear{ display: block; clear: both;}
use this code it is working
// index.jsp or login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="login" method="post">
Username : <input type="text" name="username"><br>
Password : <input type="password" name="pass"><br>
<input type="submit"><br>
</form>
</body>
</html>
// authentication servlet class
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class auth extends HttpServlet {
private static final long serialVersionUID = 1L;
public auth() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String username = request.getParameter("username");
String pass = request.getParameter("pass");
String sql = "select * from reg where username='" + username + "'";
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/Exam",
"root", "");
Statement s = conn.createStatement();
java.sql.ResultSet rs = s.executeQuery(sql);
String un = null;
String pw = null;
String name = null;
/* Need to put some condition in case the above query does not return any row, else code will throw Null Pointer exception */
PrintWriter prwr1 = response.getWriter();
if(!rs.isBeforeFirst()){
prwr1.write("<h1> No Such User in Database<h1>");
} else {
/* Conditions to be executed after at least one row is returned by query execution */
while (rs.next()) {
un = rs.getString("username");
pw = rs.getString("password");
name = rs.getString("name");
}
PrintWriter pww = response.getWriter();
if (un.equalsIgnoreCase(username) && pw.equals(pass)) {
// use this or create request dispatcher
response.setContentType("text/html");
pww.write("<h1>Welcome, " + name + "</h1>");
} else {
pww.write("wrong username or password\n");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Check that doPost()
method of servlet is called from the jsp form and remove conn.commit
.
Try This Code: It may help you
<html>
<head>
<style>
body
{
background:url('images/top-left.jpg') no-repeat center center fixed;
background-size: cover;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<form action="LoginCheck.jsp"method="post">
</br>Username:<input type="text" name="username">
</br>Password:<input type="password" name="password">
</br>
<input type="submit" value="Submit">
</form>
</center>
</body>
</html>
One more possible solution: I have a staging server that serves the site and the Cloudfront assets over HTTP. I had my origin set to "Match Viewer" instead of "HTTP Only". I also use the HTTPS Everywhere extension, which redirected all the http://*.cloudfront.net
URLs to the https://*
version. Since the staging server isn't available over SSL and Cloudfront was matching the viewer, it couldn't find the assets at https://example.com
and cached a bunch of 502s instead.
Are there properties that aren't 'transitional'?
Answer: Yes.
If the property is not listed here it is not 'transitional'.
Reference: Animatable CSS Properties
replace:
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['tel'];
with:
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['tel'];
if (isset($_POST['newsletter'])) {
$checkBoxValue = "yes";
} else {
$checkBoxValue = "no";
}
then replace this line of code:
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n Email: $email_address \n Tel \n $message\n Newsletter \n $newsletter"
with:
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $name \n Email: $email_address \n Tel \n $message\n Newsletter \n $newsletter";
I found the similar problem and found the solution and i have blogged about how to upload the file using JSP , In that example i have used the absolute path. Note that if you want to route to some other URL based location you can put a ESB like WSO2 ESB
First of all create on file and then convert your xml data in array and retrieve that data in json format for ajax success response.
Try as below:
$(document).ready(function () {
$.ajax({
type: "POST",
url: "sample.php",
success: function (response) {
var obj = $.parseJSON(response);
for(var i=0;i<obj.length;i++){
// here you can add html through loop
}
}
});
});
sample.php
$xml = "YOUR XML FILE PATH";
$json = json_encode((array)simplexml_load_string($xml)),1);
echo $json;
<br>
<%String id = request.getParameter("track_id");%>
<%if (id.length() == 0) {%>
<b><h1>Please Enter Tracking ID</h1></b>
<% } else {%>
<div class="container">
<table border="1" class="table" >
<thead>
<tr class="warning" >
<td ><h4>Track ID</h4></td>
<td><h4>Source</h4></td>
<td><h4>Destination</h4></td>
<td><h4>Current Status</h4></td>
</tr>
</thead>
<%
try {
connection = DriverManager.getConnection(connectionUrl + database, userid, password);
statement = connection.createStatement();
String sql = "select * from track where track_id="+ id;
resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
%>
<tr class="info">
<td><%=resultSet.getString("track_id")%></td>
<td><%=resultSet.getString("source")%></td>
<td><%=resultSet.getString("destination")%></td>
<td><%=resultSet.getString("status")%></td>
</tr>
<%
}
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
</table>
<%}%>
</body>
I use:
object-fit: cover;
-o-object-fit: cover;
to place images in a container with a fixed height and width, this also works great for my sliders. It will however cut of parts of the image depending on it's.
Another possible answer for Windows 10:
The command httpd -k restart
does not work on my machine somehow.
Try to use the Windows 10 Service to restart the relative service.
If you have a checkbox with an id checkbox_id.You can set its state with JS with prop('checked', false)
or prop('checked', true)
$('#checkbox_id').prop('checked', false);
I modified Sanoj Dushmantha's answer to use sessionStorage instead of localStorage. However, despite the documentation, browsers will still store this data even after the browser is closed. To fix this issue, I am removing the scroll position after it is reset.
<script>
document.addEventListener("DOMContentLoaded", function (event) {
var scrollpos = sessionStorage.getItem('scrollpos');
if (scrollpos) {
window.scrollTo(0, scrollpos);
sessionStorage.removeItem('scrollpos');
}
});
window.addEventListener("beforeunload", function (e) {
sessionStorage.setItem('scrollpos', window.scrollY);
});
</script>
There's no need to manually put class files on Tomcat. Just make sure your package declaration for Member
is correctly defined as
package pageNumber;
since, that's the only application package you're importing in your JSP.
<%@ page import="pageNumber.*, java.util.*, java.io.*" %>
JQuery 10.1.2 has a nice show and hide functions that encapsulate the behavior you are talking about. This would save you having to write a new function or keep track of css classes.
$("new").show();
$("new").hide();
Before data bind change gridview databinding method, assign GridView.EditIndex
to -1. It solved the same issue for me :
gvTypes.EditIndex = -1;
gvTypes.DataBind();
gvTypes
is my GridView ID.
The only thing you have to do is to add in the cshtml file, in the head, the following line:
@Styles.Render("~/Content/Main.css")
The entire head will look somethink like that:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>HTML Page</title>
@Styles.Render("~/Content/main.css")
</head>
Hope it helps!!
I guess problem is in width attributes in table and td remove 'px' for example
<table border="0" cellpadding="0" cellspacing="0" width="580px" style="background-color: #0290ba;">
Should be
<table border="0" cellpadding="0" cellspacing="0" width="580" style="background-color: #0290ba;">
While you should fix your site so it works without Compatibility View, try putting the X-UA-Compatible
meta tag as the very first thing after the opening <head>
, before the title
The reason that you get the 404 File Not Found
error, is that your path to CSS given as a value to the href
attribute is missing context path.
An HTTP request URL contains the following parts:
http://[host]:[port][request-path]?[query-string]
The request path is further composed of the following elements:
Context path: A concatenation of a forward slash (/) with the context
root of the servlet's web application. Example: http://host[:port]/context-root[/url-pattern]
Servlet path: The path section that corresponds to the component alias that activated this request. This path starts with a forward slash (/).
Path info: The part of the request path that is not part of the context path or the servlet path.
Read more here.
There are several solutions to your problem, here are some of them:
<c:url>
tag from JSTLIn my Java web applications I usually used <c:url>
tag from JSTL when defining the path to CSS/JavaScript/image and other static resources. By doing so you can be sure that those resources are referenced always relative to the application context (context path).
If you say, that your CSS is located inside WebContent folder, then this should work:
<link type="text/css" rel="stylesheet" href="<c:url value="/globalCSS.css" />" />
The reason why it works is explained in the "JavaServer Pages™ Standard Tag Library" version 1.2 specification chapter 7.5 (emphasis mine):
7.5 <c:url>
Builds a URL with the proper rewriting rules applied.
...
The URL must be either an absolute URL starting with a scheme (e.g. "http:// server/context/page.jsp") or a relative URL as defined by JSP 1.2 in JSP.2.2.1 "Relative URL Specification". As a consequence, an implementation must prepend the context path to a URL that starts with a slash (e.g. "/page2.jsp") so that such URLs can be properly interpreted by a client browser.
NOTE
Don't forget to use Taglib directive in your JSP to be able to reference JSTL tags. Also see an example JSP page here.
An alternative solution is using Expression Language (EL) to add application context:
<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/globalCSS.css" />
Here we have retrieved the context path from the request object. And to access the request object we have used the pageContext implicit object.
<c:set>
tag from JSTLDISCLAIMER
The idea of this solution was taken from here.
To make accessing the context path more compact than in the solution ?2, you can first use the JSTL <c:set>
tag, that sets the value of an EL variable or the property of an EL variable in any of the JSP scopes (page, request, session, or application) for later access.
<c:set var="root" value="${pageContext.request.contextPath}"/>
...
<link type="text/css" rel="stylesheet" href="${root}/globalCSS.css" />
IMPORTANT NOTE
By default, in order to set the variable in such manner, the JSP that contains this set tag must be accessed at least once (including in case of setting the value in the application scope using scope attribute, like <c:set var="foo" value="bar" scope="application" />
), before using this new variable. For instance, you can have several JSP files where you need this variable. So you must ether a) both set the new variable holding context path in the application scope AND access this JSP first, before using this variable in other JSP files, or b) set this context path holding variable in EVERY JSP file, where you need to access to it.
The more effective way to make accessing the context path more compact is to set a variable that will hold the context path and store it in the application scope using a Listener. This solution is similar to solution ?3, but the benefit is that now the variable holding context path is set right at the start of the web application and is available application wide, no need for additional steps.
We need a class that implements ServletContextListener interface. Here is an example of such class:
package com.example.listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class AppContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
ServletContext sc = event.getServletContext();
sc.setAttribute("ctx", sc.getContextPath());
}
@Override
public void contextDestroyed(ServletContextEvent event) {}
}
Now in a JSP we can access this global variable using EL:
<link type="text/css" rel="stylesheet" href="${ctx}/globalCSS.css" />
NOTE
@WebListener annotation is available since Servlet version 3.0. If you use a servlet container or application server that supports older Servlet specifications, remove the @WebServlet annotation and instead configure the listener in the deployment descriptor (web.xml). Here is an example of web.xml file for the container that supports maximum Servlet version 2.5 (other configurations are omitted for the sake of brevity):
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
...
<listener>
<listener-class>com.example.listener.AppContextListener</listener-class>
</listener>
...
</webapp>
As suggested by user @gavenkoa you can also use scriptlets like this:
<%= request.getContextPath() %>
For such a small thing it is probably OK, just note that generally the use of scriptlets in JSP is discouraged.
I personally prefer either the first solution (used it in my previous projects most of the time) or the second, as they are most clear, intuitive and unambiguous (IMHO). But you choose whatever suits you most.
You can deploy your web app as the default application (i.e. in the default root context), so it can be accessed without specifying context path. For more info read the "Update" section here.
test.html
is will be helpful for how to use VLC WebAPI.
test.html
is located in the directory where VLC was installed.
e.g. C:\Program Files (x86)\VideoLAN\VLC\sdk\activex\test.html
The following code is a quote from the test.html
.
HTML:
<object classid="clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921" width="640" height="360" id="vlc" events="True">
<param name="MRL" value="" />
<param name="ShowDisplay" value="True" />
<param name="AutoLoop" value="False" />
<param name="AutoPlay" value="False" />
<param name="Volume" value="50" />
<param name="toolbar" value="true" />
<param name="StartTime" value="0" />
<EMBED pluginspage="http://www.videolan.org"
type="application/x-vlc-plugin"
version="VideoLAN.VLCPlugin.2"
width="640"
height="360"
toolbar="true"
loop="false"
text="Waiting for video"
name="vlc">
</EMBED>
</object>
JavaScript:
You can get vlc object from getVLC()
.
It works on IE 10 and Chrome.
function getVLC(name)
{
if (window.document[name])
{
return window.document[name];
}
if (navigator.appName.indexOf("Microsoft Internet")==-1)
{
if (document.embeds && document.embeds[name])
return document.embeds[name];
}
else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
{
return document.getElementById(name);
}
}
var vlc = getVLC("vlc");
// do something.
// e.g. vlc.playlist.play();
Uncaught ReferenceError: google is not defined error will be gone when removed the async defer from the map API script tag.
I had the same requirement and I have done this in following way.You also can try out this..
Use loadData method
web.loadData("<p style='text-align:center'><img class='aligncenter size-full wp-image-1607' title='' src="+movImage+" alt='' width='240px' height='180px' /></p><p><center><U><H2>"+movName+"("+movYear+")</H2></U></center></p><p><strong>Director : </strong>"+movDirector+"</p><p><strong>Producer : </strong>"+movProducer+"</p><p><strong>Character : </strong>"+movActedAs+"</p><p><strong>Summary : </strong>"+movAnecdotes+"</p><p><strong>Synopsis : </strong>"+movSynopsis+"</p>\n","text/html", "UTF-8");
movDirector movProducer like all are my string variable.
In short i retain custom styling for my url.
Remove the first:
$(document).ready(function() {
$('#example').dataTable();
} );
You're getting errors because you're attempting to read post variables that haven't been set, they only get set on form submission. Wrap your php code at the bottom in an
if ($_SERVER['REQUEST_METHOD'] === 'POST') { ... }
Also, your code is ripe for SQL injection. At the very least use mysql_real_escape_string
on the post vars before using them in SQL queries. mysql_real_escape_string
is not good enough for a production site, but should score you extra points in class.
I had problem with caching my css files. Setting headers in PHP didn't help me (perhaps because the headers would need to be set in the stylesheet file instead of the page linking to it?).
I found the solution on this page: https://css-tricks.com/can-we-prevent-css-caching/
The solution:
Append timestamp as the query part of the URI for the linked file.
(Can be used for css, js, images etc.)
For development:
<link rel="stylesheet" href="style.css?<?php echo date('Y-m-d_H:i:s'); ?>">
For production (where caching is mostly a good thing):
<link rel="stylesheet" type="text/css" href="style.css?version=3.2">
(and rewrite manually when it is required)
Or combination of these two:
<?php
define( "DEBUGGING", true ); // or false in production enviroment
?>
<!-- ... -->
<link rel="stylesheet" type="text/css" href="style.css?version=3.2<?php echo (DEBUGGING) ? date('_Y-m-d_H:i:s') : ""; ?>">
EDIT:
Or prettier combination of those two:
<?php
// Init
define( "DEBUGGING", true ); // or false in production enviroment
// Functions
function get_cache_prevent_string( $always = false ) {
return (DEBUGGING || $always) ? date('_Y-m-d_H:i:s') : "";
}
?>
<!-- ... -->
<link rel="stylesheet" type="text/css" href="style.css?version=3.2<?php echo get_cache_prevent_string(); ?>">
The Go trough this link state that the first argument of Output()
is the file path, second is the saving mode - you need to set it to 'F'
.
$upload_dir = public_path();
$filename = $upload_dir.'/testing7.pdf';
$mpdf = new \Mpdf\Mpdf();
//$test = $mpdf->Image($pro_image, 0, 0, 50, 50);
$html ='<h1> Project Heading </h1>';
$mail = ' <p> Project Heading </p> ';
$mpdf->autoScriptToLang = true;
$mpdf->autoLangToFont = true;
$mpdf->WriteHTML($mail);
$mpdf->Output($filename,'F');
$mpdf->debug = true;
Example :
$mpdf->Output($filename,'F');
Example #2
$mpdf = new \Mpdf\Mpdf();
$mpdf->WriteHTML('Hello World');
// Saves file on the server as 'filename.pdf'
$mpdf->Output('filename.pdf', \Mpdf\Output\Destination::FILE);
Try adding ob_start();
at the top of the code i.e. before the include
statement.
Now I see what you are doing. You cannot send output to the screen then change the headers. If you are trying to create an XML file of map marker and download them to display, they should be in separate files.
Take this
<?php
require("database.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'type="' . $row['type'] . '" ';
echo '/>';
}
// End XML file
echo '</markers>';
?>
and place it in phpsqlajax_genxml.php
so your javascript can download the XML file. You are trying to do too many things in the same file.
Try putting
Display:inline;
In the CSS.
As I can see, you are comparing the message with the empty string using ==.
Its very hard to write the full code, but I can tell the flow of code - first, create db class & method inide that which will return the connection. second, create a servelet(ex-login.java) & import that db class onto that servlet. third, create instance of imported db class with the help of new operator & call the connection method of that db class. fourth, creaet prepared statement & execute statement & put this code in try catch block for exception handling.Use if-else condition in the try block to navigate your login page based on success or failure.
I hope, it will help you. If any problem, then please revert.
Nikhil Pahariya
$('html,body').animate({
scrollTop: $('#answer-<%= @answer.id %>').offset().top - 50
}, 700);
to get the smart break (break-word) work well on different browsers, what worked for me was the following set of rules:
#elm {
word-break:break-word; /* webkit/blink browsers */
word-wrap:break-word; /* ie */
}
-moz-document url-prefix() {/* catch ff */
#elm {
word-break: break-all; /* in ff- with no break-word we'll settle for break-all */
}
}
For others who may run across this - it can also occur if someone carelessly leaves trailing spaces from a php include file. Example:
<?php
require_once('mylib.php');
session_start();
?>
In the case above, if the mylib.php has blank spaces after its closing ?> tag, this will cause an error. This obviously can get annoying if you've included/required many files. Luckily the error tells you which file is offending.
HTH
My text marquee for more text, and position absolute enabled
http://jsfiddle.net/zrW5q/2075/
(function($) {
$.fn.textWidth = function() {
var calc = document.createElement('span');
$(calc).text($(this).text());
$(calc).css({
position: 'absolute',
visibility: 'hidden',
height: 'auto',
width: 'auto',
'white-space': 'nowrap'
});
$('body').append(calc);
var width = $(calc).width();
$(calc).remove();
return width;
};
$.fn.marquee = function(args) {
var that = $(this);
var textWidth = that.textWidth(),
offset = that.width(),
width = offset,
css = {
'text-indent': that.css('text-indent'),
'overflow': that.css('overflow'),
'white-space': that.css('white-space')
},
marqueeCss = {
'text-indent': width,
'overflow': 'hidden',
'white-space': 'nowrap'
},
args = $.extend(true, {
count: -1,
speed: 1e1,
leftToRight: false
}, args),
i = 0,
stop = textWidth * -1,
dfd = $.Deferred();
function go() {
if (that.css('overflow') != "hidden") {
that.css('text-indent', width + 'px');
return false;
}
if (!that.length) return dfd.reject();
if (width <= stop) {
i++;
if (i == args.count) {
that.css(css);
return dfd.resolve();
}
if (args.leftToRight) {
width = textWidth * -1;
} else {
width = offset;
}
}
that.css('text-indent', width + 'px');
if (args.leftToRight) {
width++;
} else {
width--;
}
setTimeout(go, args.speed);
};
if (args.leftToRight) {
width = textWidth * -1;
width++;
stop = offset;
} else {
width--;
}
that.css(marqueeCss);
go();
return dfd.promise();
};
// $('h1').marquee();
$("h1").marquee();
$("h1").mouseover(function () {
$(this).removeAttr("style");
}).mouseout(function () {
$(this).marquee();
});
})(jQuery);
Actually, I solved the problem. I run it by eclipse jetty plugin.
I didn't have the JDK lib in my eclipse, that's why the message keep showing that I need the full JDK installed, that's the main reason.
I installed two versions of jetty plugin, wich is jetty7 and jetty8. I think they conflict with each other or something, so I removed the jetty7, and it works!
In ASP.NET, you can catch the exception and do something about it, such as displaying a friendly message or redirect to another page... Also there is a possibility that you can handle the validation by yourself...
Display friendly message:
protected override void OnError(EventArgs e)
{
base.OnError(e);
var ex = Server.GetLastError().GetBaseException();
if (ex is System.Web.HttpRequestValidationException)
{
Response.Clear();
Response.Write("Invalid characters."); // Response.Write(HttpUtility.HtmlEncode(ex.Message));
Response.StatusCode = 200;
Response.End();
}
}
First give the link of logout.php
page in that logout button.In that page make the code which is given below:
Here is the code:
<?php
session_start();
session_destroy();
?>
When the session has started, the session for the last/current user has been started, so don't need to declare the username. It will be deleted automatically by the session_destroy method.
And if you would like to use an existing context, rather than a new context which would be loaded from xml configuration by org.springframework.web.context.ContextLoaderListener, then see -> https://stackoverflow.com/a/40694787/3004747
The problem is that the function returns UTF-8 (it can check using mb_detect_encoding), but do not convert, and these characters takes as UTF-8. ?herefore, it's necessary to do the reverse-convert to initial encoding (Windows-1251 or CP1251) using iconv. But since by the fgetcsv returns an array, I suggest to write a custom function: [Sorry for my english]
function customfgetcsv(&$handle, $length, $separator = ';'){
if (($buffer = fgets($handle, $length)) !== false) {
return explode($separator, iconv("CP1251", "UTF-8", $buffer));
}
return false;
}
Here is the latest answer using a well optimized and nice csv plugin: (The code may not work on stackoverflow here but will work in your project as i have tested it myself)
Using jquery and jquery.csv library (Very well optimized and perfectly escapes everything) https://github.com/typeiii/jquery-csv
// Create an array of objects
const data = [
{ name: "Item 1", color: "Green", size: "X-Large" },
{ name: "Item 2", color: "Green", size: "X-Large" },
{ name: "Item 3", color: "Green", size: "X-Large" }
];
// Convert to csv
const csv = $.csv.fromObjects(data);
// Download file as csv function
const downloadBlobAsFile = function(csv, filename){
var downloadLink = document.createElement("a");
var blob = new Blob([csv], { type: 'text/csv' });
var url = URL.createObjectURL(blob);
downloadLink.href = url;
downloadLink.download = filename;
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
// Download csv file
downloadBlobAsFile(csv, 'filename.csv');
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.tutorialjinni.com/jquery-csv/1.0.11/jquery.csv.min.js"></script>
_x000D_
ok, here is my final solution with 100% native javascript:
<meta id="viewport" name="viewport">
<script type="text/javascript">
//mobile viewport hack
(function(){
function apply_viewport(){
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
var ww = window.screen.width;
var mw = 800; // min width of site
var ratio = ww / mw; //calculate ratio
var viewport_meta_tag = document.getElementById('viewport');
if( ww < mw){ //smaller than minimum size
viewport_meta_tag.setAttribute('content', 'initial-scale=' + ratio + ', maximum-scale=' + ratio + ', minimum-scale=' + ratio + ', user-scalable=no, width=' + mw);
}
else { //regular size
viewport_meta_tag.setAttribute('content', 'initial-scale=1.0, maximum-scale=1, minimum-scale=1.0, user-scalable=yes, width=' + ww);
}
}
}
//ok, i need to update viewport scale if screen dimentions changed
window.addEventListener('resize', function(){
apply_viewport();
});
apply_viewport();
}());
</script>
The error in question may also be caused by disabled JarScanner in tomcat/conf/context.xml
.
See also Upgrade from Tomcat 8.0.39 to 8.0.41 results in 'failed to scan' errors.
<JarScanner scanManifest="false"/>
allows to avoid both problems.
You can achieve that by using positioning.
Try
position: absolute;
to get the 100% height.
If you just wanna use CSS and wanna avoid page break then use
.print{
page-break-after: avoid;
}
Take a look at paged media
You can use scripting equivalents for pageBreakBefore and pageBreakAfter,dynamically assign their values. For example, instead of forcing custom page breaks on your visitors, you can create a script to make this optional. Here I'll create a checkbox that toggles between slicing the page at the headers (h2) and at the printer's own discretion (default):
<form name="myform">
<input type="checkbox" name="mybox" onClick="breakeveryheader()">
</form>
<script type="text/javascript">
function breakeveryheader(){
var thestyle=(document.forms.myform.mybox.checked)? "always" : "auto"
for (i=0; i<document.getElementsByTagName("H2").length; i++)
document.getElementsByTagName("H2")[i].style.pageBreakBefore=thestyle
}
Click here for an example that uses this. You can substitute H2 inside the script with another tag such a P or DIV.
You need to give your submit <input>
a name or it won't be available using $_POST['submit']
:
<p><input type="submit" value="Submit" name="submit" /></p>
Late to the party, but I think this is actually the most elegant. Use the WORD JOINER Unicode character ⁠ on either side of your hyphen, or em dash, or any character.
So, like so:
⁠—⁠
This will join the symbol on both ends to its neighbors (without adding a space) and prevent line breaking.
Oh ok - now I get it. You can ignore this one - the XML for this is just not correct - the packages-element is indeed not declared (there is no reference to a schema or whatever). I think this is a known minor bug that won't do a thing because only NuGet will use this.
See this similar question also.
Let's expand defer()
from Dario to be more reusable.
function defer(toWaitFor, method) {
if (window[toWaitFor]) {
method();
} else {
setTimeout(function () { defer(toWaitFor, method) }, 50);
}
}
Which is then run:
function waitFor() {
defer('jQuery', () => {console.log('jq done')});
defer('utag', () => {console.log('utag done')});
}
You can add ViewStateMode="Disabled"
asp:UpdatePanel ID="UpdatePanel1" runat="server" ViewStateMode="Disabled"
<a href="1.html"><input type="text" class="button_active" value="1"></a>
<a href="2.html"><input type="text" class="button" value="2"></a>
<a href="3.html"><input type="text" class="button" value="3"></a>
Try that. Unless you truly need to stick with the type as submit, then what I provided should work. If you are going to stick with submit, then everything mentioned above is correct, it makes no sense.
If you have a form action and an input type="submit"
inside form tags, it's going to submit the old fashioned way and basically refresh the page. When doing AJAX type transactions this isn't the desired effect you are after.
Remove the action. Or remove the form altogether, though in cases it does come in handy to serialize to cut your workload. If the form tags remain, move the button outside the form tags, or alternatively make it a link with an onclick or click handler as opposed to an input button. Jquery UI Buttons works great in this case because you can mimic an input button with an a tag element.
There is an article here that describes your problem
http://www.hyperarts.com/blog/facebook-fan-pages-content-for-fans-only-static-fbml/
<fb:visible-to-connection>
Fans will see this content.
<fb:else>
Non-fans will see this content.
</fb:else>
</fb:visible-to-connection>
iframe
:In supported browsers, you can use viewport-percentage lengths such as height: 100vh
.
Where 100vh
represents the height of the viewport, and likewise 100vw
represents the width.
body {_x000D_
margin: 0; /* Reset default margin */_x000D_
}_x000D_
iframe {_x000D_
display: block; /* iframes are inline by default */_x000D_
background: #000;_x000D_
border: none; /* Reset default border */_x000D_
height: 100vh; /* Viewport-relative units */_x000D_
width: 100vw;_x000D_
}
_x000D_
<iframe></iframe>
_x000D_
This approach is fairly straight-forward. Just set the positioning of the fixed
element and add a height
/width
of 100%
.
iframe {_x000D_
position: fixed;_x000D_
background: #000;_x000D_
border: none;_x000D_
top: 0; right: 0;_x000D_
bottom: 0; left: 0;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
}
_x000D_
<iframe></iframe>
_x000D_
For this last method, just set the height
of the body
/html
/iframe
elements to 100%
.
html, body {_x000D_
height: 100%;_x000D_
margin: 0; /* Reset default margin on the body element */_x000D_
}_x000D_
iframe {_x000D_
display: block; /* iframes are inline by default */_x000D_
background: #000;_x000D_
border: none; /* Reset default border */_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
}
_x000D_
<iframe></iframe>
_x000D_
You should definitely check out the MSDN on what Outlook will support in regards to css and html. The link is here: http://msdn.microsoft.com/en-us/library/aa338201(v=office.12).aspx. If you do not have at least office 2007 you really need to upgrade as there are major differences between 2007 and previous editions. Also try saving the resulting email to file and examine it with firefox you will see what is being changed by outlook and possibly have a more specific question to ask. You can use Word to view the email as a sort of preview as well (but you won't get info on what styles are/are not being applied.
When you give up the inline blocks
.post-container {
border: 5px solid #333;
overflow:auto;
}
.post-thumb {
float: left;
display:block;
background:#ccc;
width:200px;
height:200px;
}
.post-content{
display:block;
overflow:hidden;
}
Hey, we just did a global find-replace, changing Required=" to jRequired=". Then you just change it in the jquery code as well (jquery_helper.js -> Function ValidateControls). Now our validation continues as before and Chrome leaves us alone! :)
After reading this and troubleshooting the same issues, I agree that it is related to headings (h1 for sure, havent played with any others), also browser styles adding margins and paddings with clever rules that are hard to find and over-ride.
I have adapted a technique used to apply the box-sizing property properly to margins and paddings. the original article for box-sizing is located at CSS-Tricks :
html {
margin: 0;
padding: 0;
}
*, *:before, *:after {
margin: inherit;
padding: inherit;
}
So far it is exactly the trick for not using complex resets and makes applying a design much easier for myself anyways. Hope it helps.
Give the textbox an id of "txtValue" and change the input button declaration to the following:
<input type="button" value="submit" onclick="verifyorder(document.getElementById('txtValue').value)" />
Make sure that your <td>
is not display: block;
Floating will do this, but much easier to just: display: inline;
Just use two forms.
In the first form action attribute will have name of the second jdp page and your 1st button. In the second form there will be 2nd button with action attribute thats giving the name of your 3rd jsp page.
It will be like this :
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form name="main1" method="get" action="2nd.jsp">
<input type="submit" name="ter" value="LOGOUT" >
</form>
<DIV ALIGN="left"><form name="main0" action="3rd.jsp" method="get">
<input type="submit" value="FEEDBACK">
</form></DIV>
</body>
</html>
You can set the headers in PHP by using:
<?php
//set headers to NOT cache a page
header("Cache-Control: no-cache, must-revalidate"); //HTTP 1.1
header("Pragma: no-cache"); //HTTP 1.0
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
//or, if you DO want a file to cache, use:
header("Cache-Control: max-age=2592000"); //30days (60sec * 60min * 24hours * 30days)
?>
Note that the exact headers used will depend on your needs (and if you need to support HTTP 1.0 and/or HTTP 1.1)
<html>
<head>
<title>Row Click</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function test(){
alert('test');
}
$(document).ready(function(){
var row='<tr onclick="test()"><td >Value 4</td><td>Value 5</td><td>Value 6</td></tr>';
$("#myTable").append(row);
});
</script>
</head>
<table id="myTable" >
<th>Column 1</th><th>Column 2</th><th>Column 3</th>
<tr onclick="test()">
<td >Value 1</td>
<td>Value 2</td>
<td>Value 3</td>
</tr>
</table>
</html>
Maybe this can be helpful... It's plain html - no javascript:
<p>Click on link bellow to change iframe content:</p>_x000D_
<a href="http://www.bing.com" target="search_iframe">Bing</a> -_x000D_
<a href="http://en.wikipedia.org" target="search_iframe">Wikipedia</a> -_x000D_
<a href="http://google.com" target="search_iframe">Google</a> (not allowed in inframe)_x000D_
_x000D_
<iframe src="http://en.wikipedia.org" width="100%" height="100%" name="search_iframe"></iframe>
_x000D_
By the way some sites do not allow you to open them in iframe (security reasons - clickjacking)
For me, it was nothing more than re-importing the certificate with "Allow private key to be exported" checked.
I guess it is necessary, but it does make me nervous as it is a third party app accessing this certificate.
Here is the code that everyone was asking for -- its at the very beginning of development so there isn't much in it yet, which may be helpful...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- TemplateBeginEditable name="doctitle" -->
<title></title>
<!-- TemplateEndEditable -->
<!-- TemplateBeginEditable name="head" --><!-- TemplateEndEditable -->
<link href="../Styles/KB_styles1.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="mainContainer">
<div class="header"> </div>
<div class="mainContent"> </div>
<div class="footer"> </div>
</div>
</body>
</html>
Here is the css:
@charset "utf-8";
/* CSS Document */
body{
margin-top: 0px; margin-bottom: 0px; margin-left: 0px; margin-right: 0px;
padding: 0;
color: black; font-size: 10pt; font-family: "Trebuchet MS", sans-serif;
background-color: #E2E2E2;}
html{padding: 0; margin: 0;}
/* ---Section Dividers -----------------------------------------------*/
div.mainContainer{
height: auto; width: 68em;
background-color: #FFFFFF;
margin: 0 auto; padding: 0;}
div.header{padding: 0; margin-bottom: 1em;}
div.leftSidebar{
float: left;
width: 22%; height: 40em;
margin: 0;}
div.mainContent{margin-left: 25%;}
div.footer{
clear: both;
padding-bottom: 0em; margin: 0;}
/* Hide from IE5-mac. Only IE-win sees this. \*/
* html div.leftSidebar { margin-right: 5px; }
* html div.mainContent {height: 1%; margin-left: 0;}
/* End hide from IE5/mac */
You could use the CSS3 box-sizing
property to include the external padding and border:
input[type="text"] {
width: 100%;
box-sizing: border-box;
-webkit-box-sizing:border-box;
-moz-box-sizing: border-box;
}
Put the query arguments in hidden input fields:
<form action="http://spufalcons.com/index.aspx">
<input type="hidden" name="tab" value="gymnastics" />
<input type="hidden" name="path" value="gym" />
<input type="submit" value="SPU Gymnastics"/>
</form>
Instead of using overflow:hidden
, which is a kind of hack, why not simply setting a fixed height, e.g. height:500px
, to the parent division?
Although all of the answers fix the issue but they come with trade-offs/adjustments/compromises like
floats
, You have to float elements border-top
, This pushes the parent at least 1px downwards which should then be adjusted with introducing -1px
margin to the parent element itself. This can create problems when parent already has margin-top
in relative units.padding-top
, same effect as using border-top
overflow: hidden
, Can't be used when parent should display overflowing content, like a drop down menuoverflow: auto
, Introduces scrollbars for parent element that has (intentionally) overflowing content (like shadows or tool tip's triangle)The issue can be resolved by using CSS3 pseudo elements as follows
.parent::before {
clear: both;
content: "";
display: table;
margin-top: -1px;
height: 0;
}
The first problem is that when you call append on a jQuery set with more than one element, a clone of the element to append is created for each and thus the attached event observer is lost.
An alternative way to do it would be to create the link for each element:
function handler() { alert('hello'); }
$('.add_to_this').append(function() {
return $('<a>Click here</a>').click(handler);
})
Another potential problem might be that the event observer is attached before the element has been added to the DOM. I'm not sure if this has anything to say, but I think the behavior might be considered undetermined. A more solid approach would probably be:
function handler() { alert('hello'); }
$('.add_to_this').each(function() {
var link = $('<a>Click here</a>');
$(this).append(link);
link.click(handler);
});
The following is OK in HTML4, but not in XHTML. Check your editor.
<input type=button value="Submit" />
I don't know if it's good practice, but I used to use this:
($a=<F>);
In my case runat="server"
was missing in the asp:content tag. I know it's stupid, but someone might have removed from the code in the build I got.
It worked for me. Someone may face the same thing. Hence shared.
A full fledged jQuery plugin is available, check out the demo page: http://powerkiki.github.com/ie_expand_select_width/
disclaimer: I coded that thing, patches welcome
The examples contained in this blog post do the trick.
This solved the problem for me!
Without the need for an external div. Just apply it to your given text box.
box-sizing: border-box;
With this property "The width and height properties (and min/max properties) includes content, padding and border, but not the margin"
See description of property at w3schools.
Hope this helps someone!
the bottom cell will grow as you enter more text ... setting the table width will help too
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<table id="content" style="min-height:525px; height:525px; width:100%; border:0px; margin:0; padding:0; border-collapse:collapse;">
<tr><td style="height:10px; background-color:#900;">Upper</td></tr>
<tr><td style="min-height:515px; height:515px; background-color:#909;">lower<br/>
</td></tr>
</table>
</body>
</html>
<script type="text/javascript">
/* <![CDATA[ */
document.write('<input type="text" id="cardNumber" name="cardNumber" autocom'+'plete="off"/>');
/* ]]> */
</script>
As long as you fix the width of the table itself and set the table-layout property, this is pretty simple :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style type="text/css">
td { width: 30px; overflow: hidden; }
table { width : 90px; table-layout: fixed; }
</style>
</head>
<body>
<table border="2">
<tr>
<td>word</td>
<td>two words</td>
<td>onereallylongword</td>
</tr>
</table>
</body>
</html>
I've tested this in IE6 and 7 and it seems to work fine.
Consider this algorithm. When your script loads (if there are multiple identical scripts), look through document.scripts, find the first script with the correct "src" attribute, and save it and mark it as 'visited' with a data-attribute or unique className.
When the next script loads, scan through document.scripts again, passing over any script already marked as visited. Take the first unvisited instance of that script.
This assumes that identical scripts will likely execute in the order in which they are loaded, from head to body, from top to bottom, from synchronous to asynchronous.
(function () {
var scripts = document.scripts;
// Scan for this data-* attribute
var dataAttr = 'data-your-attribute-here';
var i = 0;
var script;
while (i < scripts.length) {
script = scripts[i];
if (/your_script_here\.js/i.test(script.src)
&& !script.hasAttribute(dataAttr)) {
// A good match will break the loop before
// script is set to null.
break;
}
// If we exit the loop through a while condition failure,
// a check for null will reveal there are no matches.
script = null;
++i;
}
/**
* This specific your_script_here.js script tag.
* @type {Element|Node}
*/
var yourScriptVariable = null;
// Mark the script an pass it on.
if (script) {
script.setAttribute(dataAttr, '');
yourScriptVariable = script;
}
})();
This will scan through all the script for the first matching script that isn't marked with the special attribute.
Then mark that node, if found, with a data-attribute so subsequent scans won't choose it. This is similar to graph traversal BFS and DFS algorithms where nodes may be marked as 'visited' to prevent revisitng.
I believe it's simply for the sake of clarity, we do not want to clutter the language with too many different symbols. Also a tuple
comprehension is never necessary, a list can just be used instead with negligible speed differences, unlike a dict comprehension as opposed to a list comprehension.
Quick workaround: try switching to a different network
I experienced this problem while on a hotspot (3/4G connection). Switching to a different connection (WiFi) resolved it, but it's just a workaround - I didn't get the chance to get to the bottom of the issue so the other answers might be more interesting to determine the underlying issue
As the error message states, jQuery does not include a :unchecked
selector.
Instead, you need to invert the :checked
selector:
$("input:checkbox:not(:checked)")
/([1-9][0-9]*)|0/
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(response.GetResponseStream());
string rootNode = XmlDoc.ChildNodes[0].Name;
If the servers are clustered and there is a clustered DTC you have to disable security on the clustered DTC not the local DTC.
Assuming you are on Python 3, you can use this syntax
inputs = list(map(str,input().split()))
if you want to access individual element you can do it like that
m, n = map(str,input().split())
As @Clarke said, you can use java.io.FilenameFilter
to filter the file by specific condition.
As a complementary, I'd like to show how to use java.io.FilenameFilter
to search file in current directory and its subdirectory.
The common methods getTargetFiles and printFiles are used to search files and print them.
public class SearchFiles {
//It's used in dfs
private Map<String, Boolean> map = new HashMap<String, Boolean>();
private File root;
public SearchFiles(File root){
this.root = root;
}
/**
* List eligible files on current path
* @param directory
* The directory to be searched
* @return
* Eligible files
*/
private String[] getTargetFiles(File directory){
if(directory == null){
return null;
}
String[] files = directory.list(new FilenameFilter(){
@Override
public boolean accept(File dir, String name) {
// TODO Auto-generated method stub
return name.startsWith("Temp") && name.endsWith(".txt");
}
});
return files;
}
/**
* Print all eligible files
*/
private void printFiles(String[] targets){
for(String target: targets){
System.out.println(target);
}
}
}
I will demo how to use recursive, bfs and dfs to get the job done.
Recursive:
/**
* How many files in the parent directory and its subdirectory <br>
* depends on how many files in each subdirectory and their subdirectory
*/
private void recursive(File path){
printFiles(getTargetFiles(path));
for(File file: path.listFiles()){
if(file.isDirectory()){
recursive(file);
}
}
if(path.isDirectory()){
printFiles(getTargetFiles(path));
}
}
public static void main(String args[]){
SearchFiles searcher = new SearchFiles(new File("C:\\example"));
searcher.recursive(searcher.root);
}
Breadth First Search:
/**
* Search the node's neighbors firstly before moving to the next level neighbors
*/
private void bfs(){
if(root == null){
return;
}
Queue<File> queue = new LinkedList<File>();
queue.add(root);
while(!queue.isEmpty()){
File node = queue.remove();
printFiles(getTargetFiles(node));
File[] childs = node.listFiles(new FileFilter(){
@Override
public boolean accept(File pathname) {
// TODO Auto-generated method stub
if(pathname.isDirectory())
return true;
return false;
}
});
if(childs != null){
for(File child: childs){
queue.add(child);
}
}
}
}
public static void main(String args[]){
SearchFiles searcher = new SearchFiles(new File("C:\\example"));
searcher.bfs();
}
Depth First Search:
/**
* Search as far as possible along each branch before backtracking
*/
private void dfs(){
if(root == null){
return;
}
Stack<File> stack = new Stack<File>();
stack.push(root);
map.put(root.getAbsolutePath(), true);
while(!stack.isEmpty()){
File node = stack.peek();
File child = getUnvisitedChild(node);
if(child != null){
stack.push(child);
printFiles(getTargetFiles(child));
map.put(child.getAbsolutePath(), true);
}else{
stack.pop();
}
}
}
/**
* Get unvisited node of the node
*
*/
private File getUnvisitedChild(File node){
File[] childs = node.listFiles(new FileFilter(){
@Override
public boolean accept(File pathname) {
// TODO Auto-generated method stub
if(pathname.isDirectory())
return true;
return false;
}
});
if(childs == null){
return null;
}
for(File child: childs){
if(map.containsKey(child.getAbsolutePath()) == false){
map.put(child.getAbsolutePath(), false);
}
if(map.get(child.getAbsolutePath()) == false){
return child;
}
}
return null;
}
public static void main(String args[]){
SearchFiles searcher = new SearchFiles(new File("C:\\example"));
searcher.dfs();
}
You need to use the css-property font-face to declare your font. Have a look at this fancy site: http://www.font-face.com/
Example:
@font-face {
font-family: MyHelvetica;
src: local("Helvetica Neue Bold"),
local("HelveticaNeue-Bold"),
url(MgOpenModernaBold.ttf);
font-weight: bold;
}
See also: MDN @font-face
Just telling you about one other possibility: I like using friend definitions for that:
namespace Math
{
class Matrix
{
public:
[...]
friend std::ostream& operator<< (std::ostream& stream, const Matrix& matrix) {
[...]
}
};
}
The function will be automatically targeted into the surrounding namespace Math
(even though its definition appears within the scope of that class) but will not be visible unless you call operator<< with a Matrix object which will make argument dependent lookup find that operator definition. That can sometimes help with ambiguous calls, since it's invisible for argument types other than Matrix. When writing its definition, you can also refer directly to names defined in Matrix and to Matrix itself, without qualifying the name with some possibly long prefix and providing template parameters like Math::Matrix<TypeA, N>
.
My version for a directive that uses jqplot to plot the data once it becomes available:
app.directive('lineChart', function() {
$.jqplot.config.enablePlugins = true;
return function(scope, element, attrs) {
scope.$watch(attrs.lineChart, function(newValue, oldValue) {
if (newValue) {
// alert(scope.$eval(attrs.lineChart));
var plot = $.jqplot(element[0].id, scope.$eval(attrs.lineChart), scope.$eval(attrs.options));
}
});
}
});
Please use the following style. margin:auto
normally used to center align the content. display:table
is needed for span
element
<span style="margin:auto; display:table; border:1px solid red;">
This is some text in a div element!
</span>
Go to MINGW32 terminal put this Command : git branch --set-upstream-to=origin/(branch Name)
request.user.get_username()
or request.user.username
, former is preferred.
Since the User model can be swapped out, you should use this method instead of referencing the username attribute directly.
P.S. For templates, use {{ user.get_username }}
var obj = {name: 'Krishna', gender: 'male'};
angular.forEach(obj, function(value, key) {
console.log(key + ': ' + value);
});
yields the attributes of obj
with their respective values:
name: Krishna
gender: male
I recently came across Python 3 interpreter at CompileOnline.
using Java NIO's ByteBuffer is very simple:
byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array();
for (byte b : bytes) {
System.out.format("0x%x ", b);
}
output:
0x65 0x10 0xf3 0x29
To tie together what others have already stated or hinted at, the rules by which JAXB XJC decides whether or not to put the @XmlRootElement
annotation on a generated class are non trivial (see this article).
@XmlRootElement
exists because the JAXB runtime requires certain information in order to marshal/unmarshal a given object, specifically the XML element name and namespace. You can't just pass any old object to the Marshaller. @XmlRootElement
provides this information.
The annotation is just a convenience, however - JAXB does not require it. The alternative to is to use JAXBElement
wrapper objects, which provide the same information as @XmlRootElement
, but in the form of an object, rather than an annotation.
However, JAXBElement
objects are awkward to construct, since you need to know the XML element name and namespace, which business logic usually doesn't.
Thankfully, when XJC generates a class model, it also generates a class called ObjectFactory
. This is partly there for backwards compatibility with JAXB v1, but it's also there as a place for XJC to put generated factory methods which create JAXBElement
wrappers around your own objects. It handles the XML name and namespace for you, so you don't need to worry about it. You just need to look through the ObjectFactory
methods (and for large schema, there can be hundreds of them) to find the one you need.
This answer is correct for old versions of iOS, but is now obsolete. You should use Micky Duncan's answer, which covers custom containers.
Don't do this! The intent of the UIViewController
is to drive the entire screen. It just isn't appropriate for this, and it doesn't really add anything you need.
All you need is an object that owns your custom view. Just use a subclass of UIView
itself, so it can be added to your window hierarchy and the memory management is fully automatic.
Point the subview NIB's owner a custom subclass of UIView
. Add a contentView
outlet to this custom subclass, and point it at the view within the nib. In the custom subclass do something like this:
- (id)initWithFrame: (CGRect)inFrame;
{
if ( (self = [super initWithFrame: inFrame]) ) {
[[NSBundle mainBundle] loadNibNamed: @"NibNameHere"
owner: self
options: nil];
contentView.size = inFrame.size;
// do extra loading here
[self addSubview: contentView];
}
return self;
}
- (void)dealloc;
{
self.contentView = nil;
// additional release here
[super dealloc];
}
(I'm assuming here you're using initWithFrame:
to construct the subview.)
A simple fix for this is to install the Google Cast extension. If you don't have a Chromecast, or don't want to use the extension, no problem; just don't use the extension.
In my case delete your gradle file and then again import your file again it will work
A simple way would be:
var newDt= dt.AsEnumerable()
.GroupBy(x => x.Field<int>("ColumnName"))
.Select(y => y.First())
.CopyToDataTable();
I'm using node modules copy-to module to create a single file to require all the files in our NodeJS-based system.
The code for our utility file looks like this:
/**
* Module dependencies.
*/
var copy = require('copy-to');
copy(require('./module1'))
.and(require('./module2'))
.and(require('./module3'))
.to(module.exports);
In all of the files, most functions are written as exports, like so:
exports.function1 = function () { // function contents };
exports.function2 = function () { // function contents };
exports.function3 = function () { // function contents };
So, then to use any function from a file, you just call:
var utility = require('./utility');
var response = utility.function2(); // or whatever the name of the function is
301 redirects are cached indefinitely (at least by some browsers).
This means, if you set up a 301, visit that page, you not only get redirected, but that redirection gets cached.
When you visit that page again, your Browser* doesn't even bother to request that URL, it just goes to the cached redirection target.
The only way to undo a 301 for a visitor with that redirection in Cache, is re-redirecting back to the original URL**. In that case, the Browser will notice the loop, and finally really request the entered URL.
Obviously, that's not an option if you decided to 301 to facebook or any other resource you're not fully under control.
Unfortunately, many Hosting Providers offer a feature in their Admin Interface simply called "Redirection", which does a 301 redirect. If you're using this to temporarily redirect your domain to facebook as a coming soon page, you're basically screwed.
*at least Chrome and Firefox, according to How long do browsers cache HTTP 301s?. Just tried it with Chrome 45. Edit: Safari 7.0.6 on Mac also caches, a browser restart didn't help (Link says that on Safari 5 on Windows it does help.)
**I tried javascript window.location = ''
, because it would be the solution which could be applied in most cases - it doesn't work. It results in an undetected infinite Loop. However, php header('Location: new.url')
does break the loop
Bottom Line: only use 301s if you're absolutely sure you're never going to use that URL again. Usually never on the root dir (example.com/)
A solution is to use background-position to mimic the gradient transition. This solution was used in Twitter Bootstrap a few months ago.
Update
http://codersblock.blogspot.fr/2013/12/gradient-animation-trick.html?showComment=1390287622614
Here is a quick example:
Link state
.btn {
font-family: "Helvetica Neue", Arial, sans-serif;
font-size: 12px;
font-weight: 300;
position: relative;
display: inline-block;
text-decoration: none;
color: #fff;
padding: 20px 40px;
background-image: -moz-linear-gradient(top, #50abdf, #1f78aa);
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#50abdf), to(#1f78aa));
background-image: -webkit-linear-gradient(top, #50abdf, #1f78aa);
background-image: -o-linear-gradient(top, #50abdf, #1f78aa);
background-image: linear-gradient(to bottom, #50abdf, #1f78aa);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff50abdf', endColorstr='#ff1f78aa', GradientType=0);
background-repeat: repeat-y;
background-size: 100% 90px;
background-position: 0 -30px;
-webkit-transition: all 0.2s linear;
-moz-transition: all 0.2s linear;
-o-transition: all 0.2s linear;
transition: all 0.2s linear;
}
Hover state
.btn:hover {
background-position: 0 0;
}
On IIS Manager--> Http view--> double click on Default and write the name of your desired startup page, Thats it
Try this rule before your other rules:
RewriteRule ^(admin|user)($|/) - [L]
This will end the rewriting process.
If you frequently use a large number of exceptions, you can pre-define a tuple, so you don't have to re-type them many times.
#This example code is a technique I use in a library that connects with websites to gather data
ConnectErrs = (URLError, SSLError, SocketTimeoutError, BadStatusLine, ConnectionResetError)
def connect(url, data):
#do connection and return some data
return(received_data)
def some_function(var_a, var_b, ...):
try: o = connect(url, data)
except ConnectErrs as e:
#do the recovery stuff
blah #do normal stuff you would do if no exception occurred
NOTES:
If you, also, need to catch other exceptions than those in the pre-defined tuple, you will need to define another except block.
If you just cannot tolerate a global variable, define it in main() and pass it around where needed...
By using itemStateChanged(ItemListener)
you can track selecting and deselecting checkbox (and do whatever you want based on it):
myCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED) {//checkbox has been selected
//do something...
} else {//checkbox has been deselected
//do something...
};
}
});
Java Swing itemStateChanged docu should help too. By using isSelected()
method you can just test if actual is checkbox selected:
if(myCheckBox.isSelected()){_do_something_if_selected_}
SqlPubWiz.exe (for me, it's in C:\Program Files (x86)\Microsoft SQL Server\90\Tools\Publishing\1.2>)
Run it with no arguments for a wizard. Give it arguments to run on commandline.
SqlPubWiz.exe script -C "<ConnectionString>" <OutputFile>
Let me show you how to dev the tool.you can do so:
I dev a tool solve the problem.it is well design and quick more. get the code from my github.
enjoy it from here,I have deploy it on webserver.
I try the top 2 answer's suggestion.one web is can not open.one is slower than my tool.hope you will enjoy my tool.
If you have a string and you know the index you want to put the two variables in the string you can use:
string temp = temp.Substring(0,index) + textbox1.Text + ":" + textbox2.Text +temp.Substring(index);
But if it is a simple line you can use it this way:
string temp = string.Format("your text goes here {0} rest of the text goes here : {1} , textBox1.Text , textBox2.Text ) ;"
Try This:
View v = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView img = (ImageView) v.findViewById(R.id.my_image);
return v;
To make a text default in a select box use the $form->select()
method. Here is how you do it.
$options = array('m'=>'Male','f'=>'Female','n'=>'neutral');
$form->select('Model.name',$options,'f');
The above code will select Female
in the list box by default.
Keep baking...
This is bug in firebase api version 11.8.0, So if you reduce API version you will not face this issue.
1) Go to (Open) Command Prompt (Press Window + R then type cmd Run this).
2) Run following commands
For all listening ports
Apply port filter
Finally with the PID we can run the following command to kill the process
3) Copy PID from result set
Ex: taskkill /F /PID 189
Done !!! you can start your service now.
Someone already has the answer.
$('video') will return an array of video items. It is totally a valid seletor!
so
$("video").each(function () { this.pause() });
will work.
Try this: import headers as mentioned.. gives seconds and milliseconds only. If you need to explain the code read this link.
#include <windows.h>
#include <stdio.h>
void main()
{
SYSTEMTIME st;
SYSTEMTIME lt;
GetSystemTime(&st);
// GetLocalTime(<);
printf("The system time is: %02d:%03d\n", st.wSecond, st.wMilliseconds);
// printf("The local time is: %02d:%03d\n", lt.wSecond, lt.wMilliseconds);
}
This ...
horse = Horse.find(:first,:offset=>rand(Horse.count))
unless @suggested_horses.exists?(horse.id)
@suggested_horses<< horse
end
Should probably be this ...
horse = Horse.find(:first,:offset=>rand(Horse.count))
unless @suggested_horses.include?(horse)
@suggested_horses<< horse
end
Hope the following piece of code works for you:
def item = hudson.model.Hudson.instance.getItem('MyJob')
def value = item.lastBuild.getEnvironment(null).get('foo')
So the solution to the original problem is that you don't need both the "@see" and the "{@link...}" references on the same line. The "@link" tag is self-sufficient and, as noted, you can put it anywhere in the javadoc block. So you can mix the two approaches:
/**
* some javadoc stuff
* {@link com.my.package.Class#method()}
* more stuff
* @see com.my.package.AnotherClass
*/
As an extend to @Eugene's answer another version which will work to push code from local repo to master/develop branch .
Switch to branch ‘master’:
$ git checkout master
Merge from local repo to master:
$ git merge --no-ff FEATURE/<branch_Name>
Push to master:
$ git push
For Windows/WSL/Cygwin etc users:
Make sure that your line endings are standard Unix line feeds, i.e. \n
(LF) only.
Using Windows line endings \r\n
(CRLF) line endings will break the command line break.
This is because having \
at the end of a line with Windows line ending translates to
\
\r
\n
.
As Mark correctly explains above:
The line-continuation will fail if you have whitespace after the backslash and before the newline.
This includes not just space () or tabs (
\t
) but also the carriage return (\r
).
The answers above, are now antiquated due to new pipeline syntax. Below prints out the environment variables.
script {
sh 'env > env.txt'
String[] envs = readFile('env.txt').split("\r?\n")
for(String vars: envs){
println(vars)
}
}
// HTML
<input type="file" onchange="getFileName(this)">
// JS
function getFileName(input) {
console.log(input.files[0].name) // With extension
console.log(input.files[0].name.replace(/\.[^/.]+$/, '')) // Without extension
}
You can download manually by parsing the XMLs that you see in Android SDK Manager log.
Currently the XMLs are addon_list and repository. These xmls can change over a course of time.
It has the location of the SDKs, you can browse to the link and download directly via browser. These files has to be placed under proper folder, example the files of google APIs has to be placed under add-ons
, if you don't know where the files has to go.
Here is something to help you.
The blogpost from my blog to Install Android SDKs offline --> Offline Installation of Android SDK's
You have multiple columns named the same thing in your inner query, so the error is raised in the outer query. If you get rid of the outer query, it should run, although still be confusing:
SELECT DISTINCT
coaches.id,
people.*,
users.*,
coaches.*
FROM "COACHES"
INNER JOIN people ON people.id = coaches.person_id
INNER JOIN users ON coaches.person_id = users.person_id
LEFT OUTER JOIN organizations_users ON organizations_users.user_id = users.id
WHERE
rownum <= 25
It would be much better (for readability and performance both) to specify exactly what fields you need from each of the tables instead of selecting them all anyways. Then if you really need two fields called the same thing from different tables, use column aliases to differentiate between them.
psql
below 9.2 does not accept this URL-like syntax for options.
The use of SSL can be driven by the sslmode=value
option on the command line or the PGSSLMODE environment variable, but the default being prefer
, SSL connections will be tried first automatically without specifying anything.
Example with a conninfo string (updated for psql 8.4)
psql "sslmode=require host=localhost dbname=test"
Read the manual page for more options.
My guess is that the system-status
element is declared after the variable declaration is run. Thus, at the time the variable is declared, it is actually being set to null?
You should declare it only, then assign its value from an onLoad
handler instead, because then you will be sure that it has properly initialized (loaded) the element in question.
You could also try putting the script at the bottom of the page (or at least somewhere after the system-status
element is declared) but it's not guaranteed to always work.
If you don't want the event to be continuous (if you want the user to have to release the key each time), change onkeydown
to onkeyup
window.onkeydown = function (e) {
var code = e.keyCode ? e.keyCode : e.which;
if (code === 38) { //up key
alert('up');
} else if (code === 40) { //down key
alert('down');
}
};
Here's an example that worked for me. I had a list of about 500 specific files in a text file, contained in about 100 different folders, that I was supposed to copy over to a backup location in case those files were needed later. The text file contained full path and file name, one per line. In my case, I wanted to strip off the Drive letter and first sub-folder name from each file name. I wanted to copy all these files to a similar folder structure under another root destination folder I specified. I hope other users find this helpful.
# Copy list of files (full path + file name) in a txt file to a new destination, creating folder structure for each file before copy
$rootDestFolder = "F:\DestinationFolderName"
$sourceFiles = Get-Content C:\temp\filelist.txt
foreach($sourceFile in $sourceFiles){
$filesplit = $sourceFile.split("\")
$splitcount = $filesplit.count
# This example strips the drive letter & first folder ( ex: E:\Subfolder\ ) but appends the rest of the path to the rootDestFolder
$destFile = $rootDestFolder + "\" + $($($sourceFile.split("\")[2..$splitcount]) -join "\")
# Output List of source and dest
Write-Host ""
Write-Host "===$sourceFile===" -ForegroundColor Green
Write-Host "+++$destFile+++"
# Create path and file, if they do not already exist
$destPath = Split-Path $destFile
If(!(Test-Path $destPath)) { New-Item $destPath -Type Directory }
If(!(Test-Path $destFile)) { Copy-Item $sourceFile $destFile }
}
Genealogical data is cyclic and does not fit into an acyclic graph, so if you have assertions against cycles you should remove them.
The way to handle this in a view without creating a custom view is to treat the cyclic parent as a "ghost" parent. In other words, when a person is both a father and a grandfather to the same person, then the grandfather node is shown normally, but the father node is rendered as a "ghost" node that has a simple label like ("see grandfather") and points to the grandfather.
In order to do calculations you may need to improve your logic to handle cyclic graphs so that a node is not visited more than once if there is a cycle.
As everyone else says, LoadLibrary is the hard way to do it, and is hardly ever necessary.
The DLL should have come with a .lib file for linking, and one or more header files to #include into your sources. The header files will define the classes and function prototypes that you can use from the DLL. You will need this even if you use LoadLibrary.
To link with the library, you might have to add the .lib file to the project configuration under Linker/Input/Additional Dependencies.
select count(1) into existence
from sales where sales_type = 'Accessories' and rownum=1;
Oracle plan says that it costs 1 if seles_type column is indexed.
This will work although when embedding PHP in HTML it is better practice to use the following form:
<table>
<?php foreach($array as $key=>$value): ?>
<tr>
<td><?= $key; ?></td>
</tr>
<?php endforeach; ?>
</table>
You can find the doc for the alternative syntax on PHP.net
Timedelta objects have read-only instance attributes .days
, .seconds
, and .microseconds
.
On some mobiles like mine (MIUI Redmi 3) you can just add specific Application on list where application doesnt stop when you terminate applactions in Task Manager (It will stop but it will start again)
Just go to Settings>PermissionsAutostart
Use mouseover instead hover.
$('#target').on('click mouseover', function () {
// Do something for both
});
The above solutions work fine for most cases. However, if you also need to remove all traces of that file (ie sensitive data such as passwords), you will also want to remove it from your entire commit history, as the file could still be retrieved from there.
Here is a solution that removes all traces of the file from your entire commit history, as though it never existed, yet keeps the file in place on your system.
https://help.github.com/articles/remove-sensitive-data/
You can actually skip to step 3 if you are in your local git repository, and don't need to perform a dry run. In my case, I only needed steps 3 and 6, as I had already created my .gitignore file, and was in the repository I wanted to work on.
To see your changes, you may need to go to the GitHub root of your repository and refresh the page. Then navigate through the links to get to an old commit that once had the file, to see that it has now been removed. For me, simply refreshing the old commit page did not show the change.
It looked intimidating at first, but really, was easy and worked like a charm ! :-)
What about creating an additional wrapper class?
package com.naveen.research.sql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public abstract class PreparedStatementWrapper implements AutoCloseable {
protected PreparedStatement stat;
public PreparedStatementWrapper(Connection con, String query, Object ... params) throws SQLException {
this.stat = con.prepareStatement(query);
this.prepareStatement(params);
}
protected abstract void prepareStatement(Object ... params) throws SQLException;
public ResultSet executeQuery() throws SQLException {
return this.stat.executeQuery();
}
public int executeUpdate() throws SQLException {
return this.stat.executeUpdate();
}
@Override
public void close() {
try {
this.stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Then in the calling class you can implement prepareStatement method as:
try (Connection con = DriverManager.getConnection(JDBC_URL, prop);
PreparedStatementWrapper stat = new PreparedStatementWrapper(con, query,
new Object[] { 123L, "TEST" }) {
@Override
protected void prepareStatement(Object... params) throws SQLException {
stat.setLong(1, Long.class.cast(params[0]));
stat.setString(2, String.valueOf(params[1]));
}
};
ResultSet rs = stat.executeQuery();) {
while (rs.next())
System.out.println(String.format("%s, %s", rs.getString(2), rs.getString(1)));
} catch (SQLException e) {
e.printStackTrace();
}
It looks like you want:
public static string GetRandomBits()
Without static
, you would need an object before you can call the GetRandomBits()
method. However, since the implementation of GetRandomBits()
does not depend on the state of any Program
object, it's best to declare it static
.
I found this. Simpler than the accepted answer, and works with .NET v2
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Connect using a timeout (5 seconds)
IAsyncResult result = socket.BeginConnect( sIP, iPort, null, null );
bool success = result.AsyncWaitHandle.WaitOne( 5000, true );
if ( socket.Connected )
{
socket.EndConnect( result );
}
else
{
// NOTE, MUST CLOSE THE SOCKET
socket.Close();
throw new ApplicationException("Failed to connect server.");
}
//...
The easy way to detect whether the user has pressed enter is to use key number the enter key number is =13 to check the value of key in your device
$("input").keypress(function (e) {
if (e.which == 32 || (65 <= e.which && e.which <= 65 + 25)
|| (97 <= e.which && e.which <= 97 + 25)) {
var c = String.fromCharCode(e.which);
$("p").append($("<span/>"))
.children(":last")
.append(document.createTextNode(c));
} else if (e.which == 8) {
// backspace in IE only be on keydown
$("p").children(":last").remove();
}
$("div").text(e.which);
});
by pressing the enter key you will get result as 13 . using the key value you can call a function or do whatever you wish
$(document).keypress(function(e) {
if(e.which == 13) {
console.log("User entered Enter key");
// the code you want to run
}
});
if you want to target a button once enter key is pressed you can use the code
$(document).bind('keypress', function(e){
if(e.which === 13) { // return
$('#butonname').trigger('click');
}
});
Hope it help
Use the defaults parameter.
>>> from collections import namedtuple
>>> fields = ('val', 'left', 'right')
>>> Node = namedtuple('Node', fields, defaults=(None,) * len(fields))
>>> Node()
Node(val=None, left=None, right=None)
Or better yet, use the new dataclasses library, which is much nicer than namedtuple.
>>> from dataclasses import dataclass
>>> from typing import Any
>>> @dataclass
... class Node:
... val: Any = None
... left: 'Node' = None
... right: 'Node' = None
>>> Node()
Node(val=None, left=None, right=None)
Set Node.__new__.__defaults__
to the default values.
>>> from collections import namedtuple
>>> Node = namedtuple('Node', 'val left right')
>>> Node.__new__.__defaults__ = (None,) * len(Node._fields)
>>> Node()
Node(val=None, left=None, right=None)
Set Node.__new__.func_defaults
to the default values.
>>> from collections import namedtuple
>>> Node = namedtuple('Node', 'val left right')
>>> Node.__new__.func_defaults = (None,) * len(Node._fields)
>>> Node()
Node(val=None, left=None, right=None)
In all versions of Python, if you set fewer default values than exist in the namedtuple, the defaults are applied to the rightmost parameters. This allows you to keep some arguments as required arguments.
>>> Node.__new__.__defaults__ = (1,2)
>>> Node()
Traceback (most recent call last):
...
TypeError: __new__() missing 1 required positional argument: 'val'
>>> Node(3)
Node(val=3, left=1, right=2)
Here's a wrapper for you, which even lets you (optionally) set the default values to something other than None
. This does not support required arguments.
import collections
def namedtuple_with_defaults(typename, field_names, default_values=()):
T = collections.namedtuple(typename, field_names)
T.__new__.__defaults__ = (None,) * len(T._fields)
if isinstance(default_values, collections.Mapping):
prototype = T(**default_values)
else:
prototype = T(*default_values)
T.__new__.__defaults__ = tuple(prototype)
return T
Example:
>>> Node = namedtuple_with_defaults('Node', 'val left right')
>>> Node()
Node(val=None, left=None, right=None)
>>> Node = namedtuple_with_defaults('Node', 'val left right', [1, 2, 3])
>>> Node()
Node(val=1, left=2, right=3)
>>> Node = namedtuple_with_defaults('Node', 'val left right', {'right':7})
>>> Node()
Node(val=None, left=None, right=7)
>>> Node(4)
Node(val=4, left=None, right=7)
BIT should only allow 0 and 1 (and NULL, if the field is not defined as NOT NULL). TINYINT(1) allows any value that can be stored in a single byte, -128..127 or 0..255 depending on whether or not it's unsigned (the 1 shows that you intend to only use a single digit, but it does not prevent you from storing a larger value).
For versions older than 5.0.3, BIT is interpreted as TINYINT(1), so there's no difference there.
BIT has a "this is a boolean" semantic, and some apps will consider TINYINT(1) the same way (due to the way MySQL used to treat it), so apps may format the column as a check box if they check the type and decide upon a format based on that.
I will show you some examples:
const string &dontDoThis(const string &s)
{
string local = s;
return local;
}
You can't return local
by reference, because local
is destroyed at the end of the body of dontDoThis
.
const string &shorterString(const string &s1, const string &s2)
{
return (s1.size() < s2.size()) ? s1 : s2;
}
Here, you can return by reference both s1
and s2
because they were defined before shorterString
was called.
char &get_val(string &str, string::size_type ix)
{
return str[ix];
}
usage code as below:
string s("123456");
cout << s << endl;
char &ch = get_val(s, 0);
ch = 'A';
cout << s << endl; // A23456
get_val
can return elements of s
by reference because s
still exists after the call.
class Student
{
public:
string m_name;
int age;
string &getName();
};
string &Student::getName()
{
// you can return by reference
return m_name;
}
string& Test(Student &student)
{
// we can return `m_name` by reference here because `student` still exists after the call
return stu.m_name;
}
usage example:
Student student;
student.m_name = 'jack';
string name = student.getName();
// or
string name2 = Test(student);
class String
{
private:
char *str_;
public:
String &operator=(const String &str);
};
String &String::operator=(const String &str)
{
if (this == &str)
{
return *this;
}
delete [] str_;
int length = strlen(str.str_);
str_ = new char[length + 1];
strcpy(str_, str.str_);
return *this;
}
You could then use the operator=
above like this:
String a;
String b;
String c = b = a;
If you want a nicer representation of any PHP variable (than just plain text), I suggest you try nice_r(); it prints out values plus relevant useful information (eg: properties and methods for objects). Disclaimer: I wrote this myself.
I'd use a static constructor on the class that sets the value of a static readonly array.
public class SomeClass
{
public readonly MyStruct[] myArray;
public static SomeClass()
{
myArray = { {"foo", "bar"},
{"boo", "far"}};
}
}
You can use getContent() method on Request object.
$request->getContent() //json as a string.
Use CSS grid and set all the grid items to be in the same cell.
.layered {
display: grid;
}
.layered > * {
grid-column-start: 1;
grid-row-start: 1;
}
Adding the layered class to an element causes all it's children to be layered on top of each other.
if the layers are not the same size you can set the justify-items
and align-items
properties to set the horizontal and vertical alignment respectively.
.layered {
display: grid;
/* Set horizontal alignment of items in, case they have a different width. */
/* justify-items: start | end | center | stretch (default); */
justify-items: start;
/* Set vertical alignment of items, in case they have a different height. */
/* align-items: start | end | center | stretch (default); */
align-items: start;
}
.layered > * {
grid-column-start: 1;
grid-row-start: 1;
}
/* for demonstration purposes only */
.layered > * {
outline: 1px solid red;
background-color: rgba(255, 255, 255, 0.4)
}
_x000D_
<div class="layered">
<img src="https://via.placeholder.com/250x100?text=first" />
<p>
2
</p>
<div>
<p>
Third layer
</p>
<p>
Third layer continued
</p>
<p>
Third layer continued
</p>
<p>
Third layer continued
</p>
</div>
</div>
_x000D_
With jQuery, you can shallow copy with extend:
var copiedObject = jQuery.extend({}, originalObject)
subsequent changes to the copiedObject
will not affect the originalObject
, and vice versa.
Or to make a deep copy:
var copiedObject = jQuery.extend(true, {}, originalObject)
Use the second parameter of json_decode
to make it return an array:
$result = json_decode($data, true);
so Laravel actually returns a collection when just using Model::all();
you don't want a collection you want an array so you can type set it.
(array)Model::all();
then you can use array_filter to return the results
$models = (array)Model::all()
$models = array_filter($models);
if(empty($models))
{
do something
}
this will also allow you to do things like count()
.
Try to use jquery-transport-xdr jQuery plugin for CORS requests in IE8/9.
You need to have favicon.ico
in the same folder or dictionary as your script because python only searches in the current dictionary or you could put in the full pathname. For example, this works:
from tkinter import *
root = Tk()
root.iconbitmap(r'c:\Python32\DLLs\py.ico')
root.mainloop()
But this blows up with your same error:
from tkinter import *
root = Tk()
root.iconbitmap('py.ico')
root.mainloop()
There are a few npm libraries for cancellable promises.
p-cancelable https://github.com/sindresorhus/p-cancelable
cancelable-promise https://github.com/alkemics/CancelablePromise
The 2020 answer: it probably doesn't matter
The best answer here was from 2012, so I decided to test for myself. On Chrome for Android, the JS and CSS resources are downloaded in parallel and I could not detect a difference in page rendering speed.
I included a more detailed writeup on my blog
The working command I'm using to execute custom SQL statements is:
results = ActiveRecord::Base.connection.execute("foo")
with "foo" being the sql statement( i.e. "SELECT * FROM table").
This command will return a set of values as a hash and put them into the results variable.
So on my rails application_controller.rb I added this:
def execute_statement(sql)
results = ActiveRecord::Base.connection.execute(sql)
if results.present?
return results
else
return nil
end
end
Using execute_statement will return the records found and if there is none, it will return nil.
This way I can just call it anywhere on the rails application like for example:
records = execute_statement("select * from table")
"execute_statement" can also call NuoDB procedures, functions, and also Database Views.
This is the reason why you should whenever possible use strict equality ===
or strict inequality !==
"100" == 100
true
because this only checks value, not the data type
"100" === 100
false
this checks value and data type
I had this problem running rake db:create
. This page clued me into the DNS issue. I checked my VPN connection and found it was disconnected for some reason. I reconnected and now rake worked without a hitch.
In addition to @Aleksandr Tukallo's answer, you could also obtain the output and error message (if occurs). Compressing a folder using tar
is explained pretty well on the following answer.
import traceback
import subprocess
try:
cmd = ['tar', 'czfj', output_filename, file_to_archive]
output = subprocess.check_output(cmd).decode("utf-8").strip()
print(output)
except Exception:
print(f"E: {traceback.format_exc()}")
It sounds to me like your column isn't a date column but a text column (varchar/nvarchar etc). You should store it in the database as a date, not a string.
If you have to store it as a string for some reason, store it in a sortable format e.g. yyyy/MM/dd.
As najmeddine shows, you could convert the column on every access, but I would try very hard not to do that. It will make the database do a lot more work - it won't be able to keep appropriate indexes etc. Whenever possible, store the data in a type appropriate to the data itself.
The escape character in batch scripts is ^
. But for double-quoted strings, double up the quotes:
"string with an embedded "" character"
You have to initialise the object (create the object itself) in order to be able to call its methods otherwise you would get a NullPointerException
.
WordList words = new WordList();
You can use the selectInstances
method in Eclipse Collections. This will involved creating a new collection however so will not be as efficient as the accepted solution which uses casting.
List<CharSequence> parent =
Arrays.asList("1","2","3", new StringBuffer("4"));
List<String> strings =
Lists.adapt(parent).selectInstancesOf(String.class);
Assert.assertEquals(Arrays.asList("1","2","3"), strings);
I included StringBuffer
in the example to show that selectInstances
not only downcasts the type, but will also filter if the collection contains mixed types.
Note: I am a committer for Eclipse Collections.
If you look for POSIX compliant solution:
cd DirsRoot && find . -type f -print -o -name . -o -prune
-maxdepth is not POSIX compliant option.
Found this question today but I noticed that it does not have the case where there are None
's in the list. So, the complete solution would be:
from functools import reduce
a = [None, 1, 2, 3, None, 4]
print(reduce(lambda x, y: (x if x else 1) * (y if y else 1), a))
In the case of addition, we have:
print(reduce(lambda x, y: (x if x else 0) + (y if y else 0), a))
Here is an extension function that uses a generic and behaves like the PHP function array_slice. Negative offset and length are allowed.
public static class Extensions
{
public static T[] Slice<T>(this T[] arr, int offset, int length)
{
int start, end;
// Determine start index, handling negative offset.
if (offset < 0)
start = arr.Length + offset;
else
start = offset;
// Clamp start index to the bounds of the input array.
if (start < 0)
start = 0;
else if (start > arr.Length)
start = arr.Length;
// Determine end index, handling negative length.
if (length < 0)
end = arr.Length + length;
else
end = start + length;
// Clamp end index to the bounds of the input array.
if (end < 0)
end = 0;
if (end > arr.Length)
end = arr.Length;
// Get the array slice.
int len = end - start;
T[] result = new T[len];
for (int i = 0; i < len; i++)
{
result[i] = arr[start + i];
}
return result;
}
}
You'll have to loop over the set of columns and check each one. You should be able to get a list of all columns with a DESCRIBE table command.
Pseudo-code:
foreach $column ($cols) {
query("SELECT count(*) FROM table WHERE $column IS NOT NULL")
if($result is zero) {
# $column contains only null values"
push @onlyNullColumns, $column;
} else {
# $column contains non-null values
}
}
return @onlyNullColumns;
I know this seems a little counterintuitive but SQL does not provide a native method of selecting columns, only rows.
For Visible:
document.getElementById("test").style.visibility="visible";
For Invisible:
document.getElementById("test").style.visibility="hidden";
Update December 2019 ionic - 4.7.1
<manifest xmlns:tools=“http://schemas.android.com/tools”>
<application android:usesCleartextTraffic=“true” tools:targetApi=“28”>
Please add above content in android manifest .xml file
Previous Versions of ionic
Make sure you have the following in your config.xml
in Ionic Project:
<edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application" xmlns:android="http://schemas.android.com/apk/res/android">
<application android:networkSecurityConfig="@xml/network_security_config" />
<application android:usesCleartextTraffic="true" />
</edit-config>
Run ionic Cordova build android. It creates Android folder under Platforms
Open Android Studio and open the Android folder present in our project project-platforms-android. Leave it for few minutes so that it builds the gradle
After gradle build
is finished we get some errors for including minSdVersion
in manifest.xml
.
Now what we do is just remove <uses-sdk android:minSdkVersion="19" />
from manifest.xml
.
Make sure its removed from both the locations:
AndroidManifest.xml
.AndroidManifest.xml
.Now try to build the gradle again and now it builds successfully
Make sure you have the following in Application tag in App → manifest → Androidmanifest.xml
:
<application
android:networkSecurityConfig="@xml/network_security_config" android:usesCleartextTraffic="true" >
Open network_security_config
(app → res → xml → network_security_config.xml
).
Add the following code:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">xxx.yyyy.com</domain>
</domain-config>
</network-security-config>
Here xxx.yyyy.com
is the link of your HTTP API. Make sure you don't include any Http before the URL.
Note: Now build the app using Android Studio (Build -- Build Bundle's/APK -- Build APK) and now you can use that App and it works fine in Android Pie. If you try to build app using ionic Cordova build android it overrides all these settings so make sure you use Android Studio to build the Project.
If you have any older versions of app installed, Uninstall them and give a try or else you will be left with some error:
App not Installed
And with HTML5 we have native DOM Mutation Observers.
You can write that for example:
private Date TruncarFecha(Date fechaParametro) throws ParseException {
String fecha="";
DateFormat outputFormatter = new SimpleDateFormat("MM/dd/yyyy");
fecha =outputFormatter.format(fechaParametro);
return outputFormatter.parse(fecha);
}
public class EmployeeApiController : ApiController
{
private readonly IEmployee _employeeRepositary;
public EmployeeApiController()
{
_employeeRepositary = new EmployeeRepositary();
}
public async Task<HttpResponseMessage> Create(EmployeeModel Employee)
{
var returnStatus = await _employeeRepositary.Create(Employee);
return Request.CreateResponse(HttpStatusCode.OK, returnStatus);
}
}
Persistance
public async Task<ResponseStatusViewModel> Create(EmployeeModel Employee)
{
var responseStatusViewModel = new ResponseStatusViewModel();
var connection = new SqlConnection(EmployeeConfig.EmployeeConnectionString);
var command = new SqlCommand("usp_CreateEmployee", connection);
command.CommandType = CommandType.StoredProcedure;
var pEmployeeName = new SqlParameter("@EmployeeName", SqlDbType.VarChar, 50);
pEmployeeName.Value = Employee.EmployeeName;
command.Parameters.Add(pEmployeeName);
try
{
await connection.OpenAsync();
await command.ExecuteNonQueryAsync();
command.Dispose();
connection.Dispose();
}
catch (Exception ex)
{
throw ex;
}
return responseStatusViewModel;
}
Repository
Task<ResponseStatusViewModel> Create(EmployeeModel Employee);
public class EmployeeConfig
{
public static string EmployeeConnectionString;
private const string EmployeeConnectionStringKey = "EmployeeConnectionString";
public static void InitializeConfig()
{
EmployeeConnectionString = GetConnectionStringValue(EmployeeConnectionStringKey);
}
private static string GetConnectionStringValue(string connectionStringName)
{
return Convert.ToString(ConfigurationManager.ConnectionStrings[connectionStringName]);
}
}
0 in the start here specifies that the base is 8 (not 10), which is pretty easy to see:
>>> int('010101', 0)
4161
If you don't start with a 0, then python assumes the number is base 10.
>>> int('10101', 0)
10101
I found your question looking for a solution to the same problem; and what other answers fail to point is a way to use a variable to change the name of the table for every execution of your procedure in a permanent form, not temporary.
So far what I do is concatenate the entire SQL code with the variables to use. Like this:
declare @table_name as varchar(30)
select @table_name = CONVERT(varchar(30), getdate(), 112)
set @table_name = 'DAILY_SNAPSHOT_' + @table_name
EXEC('
SELECT var1, var2, var3
INTO '+@table_name+'
FROM my_view
WHERE string = ''Strings must use double apostrophe''
');
I hope it helps, but it could be cumbersome if the code is too large, so if you've found a better way, please share!
There is a very elegant solution to this problem, just configure your site via web.config:
<system.webServer>
<httpErrors errorMode="DetailedLocalOnly" existingResponse="PassThrough"/>
</system.webServer>
Adding to zippoxer
's answer, I use this function:
String.prototype.format = function () {
var a = this, b;
for (b in arguments) {
a = a.replace(/%[a-z]/, arguments[b]);
}
return a; // Make chainable
};
var s = 'Hello %s The magic number is %d.';
s.format('world!', 12); // Hello World! The magic number is 12.
I also have a non-prototype version which I use more often for its Java-like syntax:
function format() {
var a, b, c;
a = arguments[0];
b = [];
for(c = 1; c < arguments.length; c++){
b.push(arguments[c]);
}
for (c in b) {
a = a.replace(/%[a-z]/, b[c]);
}
return a;
}
format('%d ducks, 55 %s', 12, 'cats'); // 12 ducks, 55 cats
All the cool new stuff in ES 2015 makes this a lot easier:
function format(fmt, ...args){
return fmt
.split("%%")
.reduce((aggregate, chunk, i) =>
aggregate + chunk + (args[i] || ""), "");
}
format("Hello %%! I ate %% apples today.", "World", 44);
// "Hello World, I ate 44 apples today."
I figured that since this, like the older ones, doesn't actually parse the letters, it might as well just use a single token %%
. This has the benefit of being obvious and not making it difficult to use a single %
. However, if you need %%
for some reason, you would need to replace it with itself:
format("I love percentage signs! %%", "%%");
// "I love percentage signs! %%"
@Drewid's answer didn't work in my Firefox 25 if the flash plugin is just disabled but installed.
@invertedSpear's comment in that answer worked in firefox but not in any IE version.
So combined both their code and got this. Tested in Google Chrome 31, Firefox 25, IE 8-10. Thanks Drewid and invertedSpear :)
var hasFlash = false;
try {
var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
if (fo) {
hasFlash = true;
}
} catch (e) {
if (navigator.mimeTypes
&& navigator.mimeTypes['application/x-shockwave-flash'] != undefined
&& navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin) {
hasFlash = true;
}
}
If you want True False
use:
"%s %s" % (True, False)
because str(True)
is 'True'
and str(False)
is 'False'
.
or if you want 1 0
use:
"%i %i" % (True, False)
because int(True)
is 1
and int(False)
is 0
.
For checking the Last Modified
header, you can use httpie
(docs).
pip install httpie --user
$ http -h https://martin-thoma.com/author/martin-thoma/ | grep 'Last-Modified\|Date'
Date: Fri, 06 Jan 2017 10:06:43 GMT
Last-Modified: Fri, 06 Jan 2017 07:42:34 GMT
The Date
is important as this reports the server time, not your local time. Also, not every server sends Last-Modified
(e.g. superuser seems not to do it).
You should all know this is inline scripting and is not a good practice at all...with that said you should definitively use javascript or jQuery for this type of thing:
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Online Student Portal</title>
</head>
<body>
<form action="">
<input type="button" id="myButton" value="Add"/>
</form>
</body>
</html>
JQuery
var button_my_button = "#myButton";
$(button_my_button).click(function(){
window.location.href='Students.html';
});
Javascript
//get a reference to the element
var myBtn = document.getElementById('myButton');
//add event listener
myBtn.addEventListener('click', function(event) {
window.location.href='Students.html';
});
See comments why avoid inline scripting and also why inline scripting is bad
Copied from Web Applications:
=QUERY(Responses!B1:I, "Select B where G contains '"&$B1&"'")
They are indeed fools. If you look at RFC 3986 Appendix A, you will see that "space" is simply not mentioned anywhere in the grammar for defining a URL. Since it's not mentioned anywhere in the grammar, the only way to encode a space is with percent-encoding (%20
).
In fact, the RFC even states that spaces are delimiters and should be ignored:
In some cases, extra whitespace (spaces, line-breaks, tabs, etc.) may have to be added to break a long URI across lines. The whitespace should be ignored when the URI is extracted.
and
For robustness, software that accepts user-typed URI should attempt to recognize and strip both delimiters and embedded whitespace.
Curiously, the use of +
as an encoding for space isn't mentioned in the RFC, although it is reserved as a sub-delimeter. I suspect that its use is either just convention or covered by a different RFC (possibly HTTP).
I don't know why but for me text-align:center;
only works with:
text-align: grid;
OR
display: inline-grid;
I checked and no one style is overriding.
My structure:
<ul>
<li>
<a>ElementToCenter</a>
</li>
</ul>
Finally managed to solve all the issues, so I'll answer my own question. These are the settings/files I've used to manage to get my particular problem(s) solved;
The client's keystore is a PKCS#12 format file containing
To generate it I used OpenSSL's pkcs12
command, for example;
openssl pkcs12 -export -in client.crt -inkey client.key -out client.p12 -name "Whatever"
Tip: make sure you get the latest OpenSSL, not version 0.9.8h because that seems to suffer from a bug which doesn't allow you to properly generate PKCS#12 files.
This PKCS#12 file will be used by the Java client to present the client certificate to the server when the server has explicitly requested the client to authenticate. See the Wikipedia article on TLS for an overview of how the protocol for client certificate authentication actually works (also explains why we need the client's private key here).
The client's truststore is a straight forward JKS format file containing the root or intermediate CA certificates. These CA certificates will determine which endpoints you will be allowed to communicate with, in this case it will allow your client to connect to whichever server presents a certificate which was signed by one of the truststore's CA's.
To generate it you can use the standard Java keytool, for example;
keytool -genkey -dname "cn=CLIENT" -alias truststorekey -keyalg RSA -keystore ./client-truststore.jks -keypass whatever -storepass whatever
keytool -import -keystore ./client-truststore.jks -file myca.crt -alias myca
Using this truststore, your client will try to do a complete SSL handshake with all servers who present a certificate signed by the CA identified by myca.crt
.
The files above are strictly for the client only. When you want to set-up a server as well, the server needs its own key- and truststore files. A great walk-through for setting up a fully working example for both a Java client and server (using Tomcat) can be found on this website.
Issues/Remarks/Tips
-Djavax.net.debug=ssl
but is more structured and (arguably) easier to interpret if you're uncomfortable with the Java SSL debug output.It's perfectly possible to use the Apache httpclient library. If you want to use httpclient, just replace the destination URL with the HTTPS equivalent and add the following JVM arguments (which are the same for any other client, regardless of the library you want to use to send/receive data over HTTP/HTTPS):
-Djavax.net.debug=ssl
-Djavax.net.ssl.keyStoreType=pkcs12
-Djavax.net.ssl.keyStore=client.p12
-Djavax.net.ssl.keyStorePassword=whatever
-Djavax.net.ssl.trustStoreType=jks
-Djavax.net.ssl.trustStore=client-truststore.jks
-Djavax.net.ssl.trustStorePassword=whatever
I found a easy way to get that.
Example: Unix command(this way you don't need 2 commands.),
$ mysql -u root -p -e 'SHOW VARIABLES LIKE "%version%";'
Sample outputs:
+-------------------------+-------------------------+
| Variable_name | Value |
+-------------------------+-------------------------+
| innodb_version | 5.5.49 |
| protocol_version | 10 |
| slave_type_conversions | |
| version | 5.5.49-0ubuntu0.14.04.1 |
| version_comment | (Ubuntu) |
| version_compile_machine | x86_64 |
| version_compile_os | debian-linux-gnu |
+-------------------------+-------------------------+
In above case mysql version is 5.5.49.
Please find this useful reference.
Zend framework
public function verifyTablesExists($tablesName)
{
$db = $this->getDefaultAdapter();
$config_db = $db->getConfig();
$sql = "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '{$config_db['dbname']}' AND table_name = '{$tablesName}'";
$result = $db->fetchRow($sql);
return $result;
}
The accepted answer has some holes in it. The beauty of the SparseArray is that it allows gaps in the indeces. So, we could have two maps like so, in a SparseArray...
(0,true)
(250,true)
Notice the size here would be 2. If we iterate over size, we will only get values for the values mapped to index 0 and index 1. So the mapping with a key of 250 is not accessed.
for(int i = 0; i < sparseArray.size(); i++) {
int key = sparseArray.keyAt(i);
// get the object by the key.
Object obj = sparseArray.get(key);
}
The best way to do this is to iterate over the size of your data set, then check those indeces with a get() on the array. Here is an example with an adapter where I am allowing batch delete of items.
for (int index = 0; index < mAdapter.getItemCount(); index++) {
if (toDelete.get(index) == true) {
long idOfItemToDelete = (allItems.get(index).getId());
mDbManager.markItemForDeletion(idOfItemToDelete);
}
}
I think ideally the SparseArray family would have a getKeys() method, but alas it does not.
If you want env variables to be replaced in your source files while keeping all of the non env variables as they are, you can use the following command:
envsubst "$(printf '${%s} ' $(env | sed 's/=.*//'))" < source.txt > destination.txt
The syntax for replacing only specific variables is explained here. The command above is using a sub-shell to list all defined variables and then passing it to the envsubst
So if there's a defined env variable called $NAME
, and your source.txt
file looks like this:
Hello $NAME
Your balance is 123 ($USD)
The destination.txt
will be:
Hello Arik
Your balance is 123 ($USD)
Notice that the $NAME
is replaced and the $USD
is left untouched
Trailing backtick character, i.e.,
&"C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe" `
-verb:sync `
-source:contentPath="c:\workspace\xxx\master\Build\_PublishedWebsites\xxx.Web" `
-dest:contentPath="c:\websites\xxx\wwwroot,computerName=192.168.1.1,username=administrator,password=xxx"
White space matters. The required format is Space`Enter.
For Windows Smart device (compact frame work ) (MC75-Motorola devices)
mytabControl.SelectedIndex = 1
The LDF is the transaction log. It keeps a record of everything done to the database for rollback purposes.
You do not want to delete, but you can shrink it with the dbcc shrinkfile
command. You can also right-click on the database in SQL Server Management Studio and go to Tasks > Shrink.
The answer to this question in 2020 is IT DOESN'T WORK AT ALL NOW.
This will produce a string 96 characters in length, from the Base64 range (uppers, lowers, numbers, + and /). Adding 3 "NEWID()" will increase the length by 32, with no Base64 padding (=).
SELECT
CAST(
CONVERT(NVARCHAR(MAX),
CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
,2)
AS XML).value('xs:base64Binary(xs:hexBinary(.))', 'VARCHAR(MAX)') AS StringValue
If you are applying this to a set, make sure to introduce something from that set so that the NEWID() is recomputed, otherwise you'll get the same value each time:
SELECT
U.UserName
, LEFT(PseudoRandom.StringValue, LEN(U.Pwd)) AS FauxPwd
FROM Users U
CROSS APPLY (
SELECT
CAST(
CONVERT(NVARCHAR(MAX),
CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), NEWID())
+CONVERT(VARBINARY(8), U.UserID) -- Causes a recomute of all NEWID() calls
,2)
AS XML).value('xs:base64Binary(xs:hexBinary(.))', 'VARCHAR(MAX)') AS StringValue
) PseudoRandom
For a SOAP 1.2 Webservice, I normally use
curl --header "content-type: application/soap+xml" --data @filetopost.xml http://domain/path
Your best bet is to add logging.level.org.springframework.web.client.RestTemplate=DEBUG
to the application.properties
file.
Other solutions like setting log4j.logger.httpclient.wire
will not always work because they assume you use log4j
and Apache HttpClient
, which is not always true.
Note, however, that this syntax will work only on latest versions of Spring Boot.
Use the length
property of the [String]
type:
if ($dbUserName.length -gt 8) {
Write-Output "Please enter more than 8 characters."
$dbUserName = Read-Host "Re-enter database username"
}
Please note that you have to use -gt
instead of >
in your if
condition. PowerShell uses the following comparison operators to compare values and test conditions:
Here I did it using a rather simple form:
from selenium import webdriver
browser = webdriver.Firefox()
browser.get("url")
searchTxt=''
while not searchTxt:
try:
searchTxt=browser.find_element_by_name('NAME OF ELEMENT')
searchTxt.send_keys("USERNAME")
except:continue
You need to make sure the frame is fully loaded the best way to do it is to use onload:
<iframe id="nesgt" src="" onload="custom()"></iframe>
function custom(){
document.getElementById("nesgt").contentWindow.document;
}
this function will run automatically when the iframe is fully loaded.
it could be done with setTimeout but we can't get the exact time of the frame load.
hope this helps someone.
Actually we can do it. we can set the file value default by using webbrowser control in c# using FormToMultipartPostData Library.We have to download and include this Library in our project. Webbrowser enables the user to navigate Web pages inside form. Once the web page loaded , the script inside the webBrowser1_DocumentCompleted will be executed. So,
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
FormToMultipartPostData postData =
new FormToMultipartPostData(webBrowser1, form);
postData.SetFile("fileField", @"C:\windows\win.ini");
postData.Submit();
}
Refer the below link for downloading and complete reference.
https://www.codeproject.com/Articles/28917/Setting-a-file-to-upload-inside-the-WebBrowser-com
I wrote the following code to convert an image from sdcard to a Base64 encoded string to send as a JSON object.And it works great:
String filepath = "/sdcard/temp.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
fis = new FileInputStream(imagefile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);
byte[] b = baos.toByteArray();
encImage = Base64.encodeToString(b, Base64.DEFAULT);
This is as close as I can get to the natural feel of Python's "in" operator. You have to define your own type. Then you can extend the functionality of that type by adding a method like "has" which behaves like you'd hope.
package main
import "fmt"
type StrSlice []string
func (list StrSlice) Has(a string) bool {
for _, b := range list {
if b == a {
return true
}
}
return false
}
func main() {
var testList = StrSlice{"The", "big", "dog", "has", "fleas"}
if testList.Has("dog") {
fmt.Println("Yay!")
}
}
I have a utility library where I define a few common things like this for several types of slices, like those containing integers or my own other structs.
Yes, it runs in linear time, but that's not the point. The point is to ask and learn what common language constructs Go has and doesn't have. It's a good exercise. Whether this answer is silly or useful is up to the reader.
As of 1.10.5, simply include
'orderable: false'
in columnDefs and target your column with
'targets: [0,1]'
Table should like like:
var table = $('#data-tables').DataTable({
columnDefs: [{
targets: [0],
orderable: false
}]
});
You should check to make sure the value is not None before trying to perform any calculations on it:
my_value = None
if my_value is not None:
print int(my_value) / 2
Note: my_value
was intentionally set to None to prove the code works and that the check is being performed.
That is exactly what you do with an advanced filter. If it's a one shot, you don't even need a macro, it is available in the Data menu.
Sheets("Sheet1").Range("A1:D17").AdvancedFilter Action:=xlFilterCopy, _
CriteriaRange:=Sheets("Sheet1").Range("G1:G2"), CopyToRange:=Range("A1:D1") _
, Unique:=False
Arrays.sort(numArray);
int middle = ((numArray.length) / 2);
if(numArray.length % 2 == 0){
int medianA = numArray[middle];
int medianB = numArray[middle-1];
median = (medianA + medianB) / 2;
} else{
median = numArray[middle + 1];
}
EDIT: I initially had medianB
setting to middle+1
in the even length arrays, this was wrong due to arrays starting count at 0. I have updated it to use middle-1
which is correct and should work properly for an array with an even length.
First, let's see why this is happening.
The reason is that, surprisingly, when a box has position: absolute
its containing box is the parent's padding box (that is, the box around its padding). This is surprising because usually (that is, when using static or relative positioning) the containing box is the parent's content box.
Here is the relevant part of the CSS specification:
In the case that the ancestor is an inline element, the containing block is the bounding box around the padding boxes of the first and the last inline boxes generated for that element.... Otherwise, the containing block is formed by the padding edge of the ancestor.
The simplest approach—as suggested in Winter's answer—is to use padding: inherit
on the absolutely positioned div
. It only works, though, if you don't want the absolutely positioned div
to have any additional padding of its own. I think the most general-purpose solutions (in that both elements can have their own independent padding) are:
Add an extra relatively positioned div
(with no padding) around the absolutely positioned div
. That new div
will respect the padding of its parent, and the absolutely positioned div
will then fill it.
The downside, of course, is that you're messing with the HTML simply for presentational purposes.
Repeat the padding (or add to it) on the absolutely positioned element.
The downside here is that you have to repeat the values in your CSS, which is brittle if you're writing the CSS directly. However, if you're using a pre-processing tool like SASS
or LESS
you can avoid that problem by using a variable. This is the method I personally use.
using Eloquent
$data = array(
array('user_id'=>'Coder 1', 'subject_id'=> 4096),
array('user_id'=>'Coder 2', 'subject_id'=> 2048),
//...
);
Model::insert($data);
UPDATE TX_Master_PCBA
SET TIMESTAMP2 = '2013-12-12 15:40:31.593',
G_FIELD='0000'
WHERE TIMESTAMP2 IN
(
SELECT TOP 1 TIMESTAMP2
FROM TX_Master_PCBA WHERE SERIAL_NO='0500030309'
ORDER BY TIMESTAMP2 DESC -- You need to decide what column you want to sort on
)
This can be done. For example with Firefox
CSS
#hlinks {
-moz-binding: url(stackexchange.xml#hlinks);
}
stackexchange.xml
<bindings xmlns="http://www.mozilla.org/xbl"
xmlns:html="http://www.w3.org/1999/xhtml">
<binding id="hlinks">
<content>
<children/>
<html:a href="/privileges">privileges</html:a>
<html:span class="lsep"> | </html:span>
<html:a href="/users/logout">log out</html:a>
</content>
</binding>
</bindings>
A status code of 0 in an NSHTTPURLResponse
object generally means there was no response, and can occur for various reasons. The server will never return a status of 0 as this is not a valid HTTP status code.
In your case, you are appearing to get a status code of 0 because the request is timing out and 0 is just the default value for the property. The timeout itself could be for various reasons, such as the server simply not responding in time, being blocked by a firewall, or your entire network connection being down. Usually in the case of the latter though the phone is smart enough to know it doesn't have a network connection and will fail immediately. However, it will still fail with an apparent status code of 0.
Note that in cases where the status code is 0, the real error is captured in the returned NSError
object, not the NSHTTPURLResponse
.
HTTP status 408
is pretty uncommon in my experience. I've never encountered one myself. But it is apparently used in cases where the client needs to maintain an active socket connection to the server, and the server is waiting on the client to send more data over the open socket, but it doesn't in a given amount of time and the server ends the connection with a 408
status code, essentially telling the client "you took too long".
Ya its possible to do without support of javascript..
We can use html5 auto focus attribute
For Example:
<input type="text" name="name" autofocus="autofocus" id="xax" />
If use it (autofocus="autofocus") in text field means that text field get focused when page gets loaded..
For more details:
http://www.hscripts.com/tutorials/html5/autofocus-attribute.html
There is no need to explicitly check $?
. Just do:
ps aux | grep some_proces[s] > /tmp/test.txt && echo 1 || echo 0
Note that this relies on echo not failing, which is certainly not guaranteed. A more reliable way to write this is:
if ps aux | grep some_proces[s] > /tmp/test.txt; then echo 1; else echo 0; fi
I am not sure I understand what you want, but based on what I understood
the x scale seems to be the same, it is the y scale that is not the same, and that is because you specified scales ="free"
you can specify scales = "free_x" to only allow x to be free (in this case it is the same as pred has the same range by definition)
p <- ggplot(plot, aes(x = pred, y = value)) + geom_point(size = 2.5) + theme_bw()
p <- p + facet_wrap(~variable, scales = "free_x")
worked for me, see the picture
I think you were making it too difficult - I do seem to remember one time defining the limits based on a formula with min and max and if faceted I think it used only those values, but I can't find the code
Check the following: https://www.visualstudio.com/vs/compare/ Visual studio community is free version for students and other academics, individual developers, open-source projects, and small non-enterprise teams (see "Usage" section at bottom of linked page). While VSUltimate is for companies. You also get more things with paid versions!
final keyword in the method input parameter is not needed. Java creates a copy of the reference to the object, so putting final on it doesn't make the object final but just the reference, which doesn't make sense
Using the arrow function, and sorting by the second string field
var a = [[12, 'CCC'], [58, 'AAA'], [57, 'DDD'], [28, 'CCC'],[18, 'BBB']];_x000D_
a.sort((a, b) => a[1].localeCompare(b[1]));_x000D_
console.log(a)
_x000D_
In Kotlin:
myButton.setOnClickListener { doSomething((it as Button).text) }
Note: This gets the button text as a CharSequence
, which more places in code can likely use. If you really want a String from there, then you can use .toString()
.
JSON-js - JSON in JavaScript.
To convert an object to a string, use JSON.stringify
:
var json_text = JSON.stringify(your_object, null, 2);
To convert a JSON string to object, use JSON.parse
:
var your_object = JSON.parse(json_text);
It was recently recommended by John Resig:
...PLEASE start migrating your JSON-using applications over to Crockford's json2.js. It is fully compatible with the ECMAScript 5 specification and gracefully degrades if a native (faster!) implementation exists.
In fact, I just landed a change in jQuery yesterday that utilizes the JSON.parse method if it exists, now that it has been completely specified.
I tend to trust what he says on JavaScript matters :)
All modern browsers (and many older ones which aren't ancient) support the JSON object natively. The current version of Crockford's JSON library will only define JSON.stringify
and JSON.parse
if they're not already defined, leaving any browser native implementation intact.
As an alternative to using UsedRange or providing an explicit range address, the AutoFilter.Range property can also specify the affected range.
ActiveSheet.AutoFilter.Range.Offset(1,0).Rows.SpecialCells(xlCellTypeVisible).Delete(xlShiftUp)
As used here, Offset causes the first row after the AutoFilter range to also be deleted. In order to avoid that, I would try using .Resize() after .Offset().
Newer versions of pip
(8 or later) can directly use the --prefix
option:
pip install --prefix=$PREFIX_PATH package_name
where $PREFIX_PATH
is the installation prefix where lib, bin and other top-level folders are placed.
Even if it is really discouraged to use merge cells in Excel (use Center Across Selection
for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).
Hence, you can get the value of merged cells in range B4:B11
in several ways:
Range("B4").Value
Range("B4:B11").Cells(1).Value
Range("B4:B11").Cells(1,1).Value
You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty
.
Also note that Range("B4:B11").Value
won't work (raises an execution error number 13 if you try to Debug.Print
it) because it returns an array.
For Chart.js 2.0 and up, the Chart object data has changed. For those who are using Chart.js 2.0+, below is an example of using HTML5 Canvas fillText()
method to display data value inside of the pie slice. The code works for doughnut chart, too, with the only difference being type: 'pie'
versus type: 'doughnut'
when creating the chart.
Script:
Javascript
var data = {
datasets: [{
data: [
11,
16,
7,
3,
14
],
backgroundColor: [
"#FF6384",
"#4BC0C0",
"#FFCE56",
"#E7E9ED",
"#36A2EB"
],
label: 'My dataset' // for legend
}],
labels: [
"Red",
"Green",
"Yellow",
"Grey",
"Blue"
]
};
var pieOptions = {
events: false,
animation: {
duration: 500,
easing: "easeOutQuart",
onComplete: function () {
var ctx = this.chart.ctx;
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function (dataset) {
for (var i = 0; i < dataset.data.length; i++) {
var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model,
total = dataset._meta[Object.keys(dataset._meta)[0]].total,
mid_radius = model.innerRadius + (model.outerRadius - model.innerRadius)/2,
start_angle = model.startAngle,
end_angle = model.endAngle,
mid_angle = start_angle + (end_angle - start_angle)/2;
var x = mid_radius * Math.cos(mid_angle);
var y = mid_radius * Math.sin(mid_angle);
ctx.fillStyle = '#fff';
if (i == 3){ // Darker text color for lighter background
ctx.fillStyle = '#444';
}
var percent = String(Math.round(dataset.data[i]/total*100)) + "%";
//Don't Display If Legend is hide or value is 0
if(dataset.data[i] != 0 && dataset._meta[0].data[i].hidden != true) {
ctx.fillText(dataset.data[i], model.x + x, model.y + y);
// Display percent in another line, line break doesn't work for fillText
ctx.fillText(percent, model.x + x, model.y + y + 15);
}
}
});
}
}
};
var pieChartCanvas = $("#pieChart");
var pieChart = new Chart(pieChartCanvas, {
type: 'pie', // or doughnut
data: data,
options: pieOptions
});
HTML
<canvas id="pieChart" width=200 height=200></canvas>
Xampp has the php application under: C:\xampp\php file directory ... if you input C:\xampp\php\php in CMD it should enter the php application.
To read the user input and store it in a variable, for later use, you can use SQL*Plus command ACCEPT
.
Accept <your variable> <variable type if needed [number|char|date]> prompt 'message'
example
accept x number prompt 'Please enter something: '
And then you can use the x
variable in a PL/SQL block as follows:
declare
a number;
begin
a := &x;
end;
/
Working with a string example:
accept x char prompt 'Please enter something: '
declare
a varchar2(10);
begin
a := '&x'; -- for a substitution variable of char data type
end; -- to be treated as a character string it needs
/ -- to be enclosed with single quotation marks
listA.Except(listB)
will give you all of the items in listA that are not in listB
Is this code snippet work for you?
if (!count($_SESSION)>0) {
session_start();
}
Scope tag is always use to limit the transitive dependencies and availability of the jar at class path level.If we don't provide any scope then the default scope will work i.e. Compile .
You can try this: https://github.com/momodi/Json4Scala
It's simple, and has only one scala file with less than 300 lines code.
There are samples:
test("base") {
assert(Json.parse("123").asInt == 123)
assert(Json.parse("-123").asInt == -123)
assert(Json.parse("111111111111111").asLong == 111111111111111l)
assert(Json.parse("true").asBoolean == true)
assert(Json.parse("false").asBoolean == false)
assert(Json.parse("123.123").asDouble == 123.123)
assert(Json.parse("\"aaa\"").asString == "aaa")
assert(Json.parse("\"aaa\"").write() == "\"aaa\"")
val json = Json.Value(Map("a" -> Array(1,2,3), "b" -> Array(4, 5, 6)))
assert(json("a")(0).asInt == 1)
assert(json("b")(1).asInt == 5)
}
test("parse base") {
val str =
"""
{"int":-123, "long": 111111111111111, "string":"asdf", "bool_true": true, "foo":"foo", "bool_false": false}
"""
val json = Json.parse(str)
assert(json.asMap("int").asInt == -123)
assert(json.asMap("long").asLong == 111111111111111l)
assert(json.asMap("string").asString == "asdf")
assert(json.asMap("bool_true").asBoolean == true)
assert(json.asMap("bool_false").asBoolean == false)
println(json.write())
assert(json.write().length > 0)
}
test("parse obj") {
val str =
"""
{"asdf":[1,2,4,{"bbb":"ttt"},432]}
"""
val json = Json.parse(str)
assert(json.asMap("asdf").asArray(0).asInt == 1)
assert(json.asMap("asdf").asArray(3).asMap("bbb").asString == "ttt")
}
test("parse array") {
val str =
"""
[1,2,3,4,{"a":[1,2,3]}]
"""
val json = Json.parse(str)
assert(json.asArray(0).asInt == 1)
assert(json(4)("a")(2).asInt == 3)
assert(json(4)("a")(2).isInt)
assert(json(4)("a").isArray)
assert(json(4)("a").isMap == false)
}
test("real") {
val str = "{\"styles\":[214776380871671808,214783111085424640,214851869216866304,214829406537908224],\"group\":100,\"name\":\"AO4614??????????? ???? ????@\",\"shopgrade\":8,\"price\":0.59,\"shop_id\":60095469,\"C3\":50018869,\"C2\":50024099,\"C1\":50008090,\"imguri\":\"http://img.geilicdn.com/taobao10000177139_425x360.jpg\",\"cag\":50006523,\"soldout\":0,\"C4\":50006523}"
val json = Json.parse(str)
println(json.write())
assert(json.asMap.size > 0)
}
There are a number of steps you have to go through to create an installer and it varies for each Operating System. For Example:
.pkg
, there are instructions on how to do that here: https://coolaj86.com/articles/how-to-create-an-osx-pkg-installer.html.deb
, there are instruction on how to do that here: https://coolaj86.com/articles/how-to-create-a-debian-installer.html.exe
or .msi
, there are instruction on how do that using the innosetup installer here: https://coolaj86.com/articles/how-to-create-an-innosetup-installer.htmlRemove the comma
receipt int(10),
And also AUTO INCREMENT
should be a KEY
double
datatype also requires the precision of decimal places so right syntax is double(10,2)
pmg's answer is very convincing. If you would like to know how static declarations work at object level then this below info could be interesting to you. I reused the same program written by pmg and compiler it into a .so(shared object) file
Following contents are after dumping the .so file into something human readable
0000000000000675 f1: address of f1 function
000000000000068c f2: address of f2(staticc) function
note the difference in the function address , it means something . For a function that's declared with different address , it can very well signify that f2 lives very far away or in a different segment of the object file.
Linkers use something called PLT(Procedure linkage table) and GOT(Global offsets table) to understand symbols that they have access to link to .
For now think that GOT and PLT magically bind all the addresses and a dynamic section holds information of all these functions that are visible by linker.
After dumping the dynamic section of the .so file we get a bunch of entries but only interested in f1 and f2 function.
The dynamic section holds entry only for f1 function at address 0000000000000675 and not for f2 !
Num: Value Size Type Bind Vis Ndx Name
9: 0000000000000675 23 FUNC GLOBAL DEFAULT 11 f1
And thats it !. From this its clear that the linker will be unsuccessful in finding the f2 function since its not in the dynamic section of the .so file.
Try this out - https://github.com/satyapaul/jpath/blob/master/JSONDataReader.java
It's a very simple implementation on similar line of xpath for xml. It's names as jpath.
For IE8 support, the "content" property cannot be empty.
To get around this I've done the following :
.ul li:after {
content:"icon";
text-indent:-999em;
display:block;
width:32px;
height:32px;
background:url(../img/icons/spritesheet.png) 0 -620px no-repeat;
margin:5% 0 0 45%;
}
Note : This works with image sprites too
As Ben said, you are POSTing your request ( HttpMethod.Post specified in your code )
The querystring (get) parameters included in your url probably will not do anything.
Try this:
string url = "http://myserver/method";
string content = "param1=1¶m2=2";
HttpClientHandler handler = new HttpClientHandler();
HttpClient httpClient = new HttpClient(handler);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
HttpResponseMessage response = await httpClient.SendAsync(request,content);
HTH,
bovako
Another common source of error for
Error: getaddrinfo ENOTFOUND
at errnoException (dns.js:37:11)
at Object.onanswer [as oncomplete] (dns.js:124:16)
is writing the protocol (https, https, ...) when setting the host
property in options
// DON'T WRITE THE `http://`
var options = {
host: 'http://yoururl.com',
path: '/path/to/resource'
};
Even though there are multiple answers, there is an issue using this approach. It selects all the text that matches, not only the whole words like variables.
As per "Sublime Text: Select all instances of a variable and edit variable name" and the answer in "Sublime Text: Select all instances of a variable and edit variable name", we have to start with a empty selection. That is, start using the shortcut Alt+F3 which would help selecting only the whole words.
Be wary of "slurping" files. That's when you read the entire file into memory at once.
The problem is that it doesn't scale well. You could be developing code with a reasonably sized file, then put it into production and suddenly find you're trying to read files measuring in gigabytes, and your host is freezing up as it tries to read and allocate memory.
Line-by-line I/O is very fast, and almost always as effective as slurping. It's surprisingly fast actually.
I like to use:
IO.foreach("testfile") {|x| print "GOT ", x }
or
File.foreach('testfile') {|x| print "GOT", x }
File inherits from IO, and foreach
is in IO, so you can use either.
I have some benchmarks showing the impact of trying to read big files via read
vs. line-by-line I/O at "Why is "slurping" a file not a good practice?".
You can add a sequence of numbers very easily with
data$ID <- seq.int(nrow(data))
If you are already using library(tidyverse)
, you can use
data <- tibble::rowid_to_column(data, "ID")
A UDF will only return a value it won't allow you to change the properties of a cell/sheet/workbook. Move your code to a Worksheet_Change event or similar to change properties.
Eg
Private Sub worksheet_change(ByVal target As Range)
target.Font.Bold = True
End Sub
I was working with a list of toasts (alert messages), List<Alert>
from C# and needed it as JavaScript array for Toastr in a partial view (.cshtml
file). The JavaScript code below is what worked for me:
var toasts = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(alerts));
toasts.forEach(function (entry) {
var command = entry.AlertStyle;
var message = entry.Message;
if (command === "danger") { command = "error"; }
toastr[command](message);
});
The windows handle limit for your application is 10,000 handles. You're getting the error because your program is creating too many handles. You'll need to find the memory leak. As other users have suggested, use a Memory Profiler. I use the .Net Memory Profiler as well. Also, make sure you're calling the dispose method on controls if you're removing them from a form before the form closes (otherwise the controls won't dispose). You'll also have to make sure that there are no events registered with the control. I myself have the same issue, and despite what I already know, I still have some memory leaks that continue to elude me..
Since I have to store various types of content in my blob field/column, I am suppose to update my code like this:
echo "data: $mime" $result['$data']";
where:
mime
can be an image of any kind, text, word document, text document, PDF document, etc... content datatype is blob
in database.
This type of situation is implementation dependent and consequently it will require a vendor specific mechanism in order to trap. With Microsoft this will involve SEH, and *nix will involve a signal
In general though catching an Access Violation exception is a very bad idea. There is almost no way to recover from an AV exception and attempting to do so will just lead to harder to find bugs in your program.
At a guess, you used Code::Blocks to create a Console Application project. Such a project does not link in the GDI stuff, because console applications are generally not intended to do graphics, and TextOut
is a graphics function. If you want to use the features of the GDI, you should create a Win32 Gui Project, which will be set up to link in the GDI for you.
You can get table/view details through below query.
For table :sp_help table_name For View :sp_help view_name
Notepad++ provides 2 types of features:
Based on what you write, it seems what you want is auto-completion on function only + suggestion on arguments.
To do that, you just need to change a setting.
Settings
> Preferences...
> Auto-completion
Enable Auto-completion on each input
Function completion
and not Word completion
Function parameter hint on input
(if you have this option)On version 6.5.5 of Notepad++, I have this setting
Some documentation about auto-completion is available in Notepad++ Wiki.
You can combine the two functions; coerce to characters thence to numerics:
> fac <- factor(c("1","2","1","2"))
> as.numeric(as.character(fac))
[1] 1 2 1 2
You don't need to control your checkBoxes with jQuery. You can do it with some simple JavaScript.
This JS snippet should work fine:
document.TheFormHere.test.Value = true;
If you are using yum try:
sudo yum install mysql-devel
In vanilla/pure javascript you can check as following -
var field = document.querySelector("input[name='fieldName']");
if(field.readOnly){
alert("foo");
}
For Windows : Using batch program.
Write this code in a text file and save it.
REM Delete eval folder with licence key and options.xml which contains a reference to it
for %%I in ("WebStorm", "IntelliJ", "CLion", "Rider", "GoLand", "PhpStorm") do (
for /d %%a in ("%USERPROFILE%\.%%I*") do (
rd /s /q "%%a/config/eval"
del /q "%%a\config\options\other.xml"
)
)
REM Delete registry key and jetbrains folder (not sure if needet but however)
rmdir /s /q "%APPDATA%\JetBrains"
reg delete "HKEY_CURRENT_USER\Software\JavaSoft" /f
Now rename the file fileName.txt
to fileName.bat
Close phpstorm if running. Disconnect internet. Then run the file. Open phpstorm again. If nothing goes wrong you will see the magic.
worst case : If phpstorm still shows "License Expired", at first uninstall and then apply the above technique.
Just use indexer
var valueAtIndex1 = myValues[1];
I tried the above answer - using page.html#ID_name
it gave me a 404 page doesn't exist error.
Then instead of using .html
, I simply put a slash /
before the #
and that worked fine. So my example on the sending page between the link tags looks like:
<a href= "http://my website.com/target-page/#El_Chorro">El Chorro</a>
Just use /
instead of .html
.
In JavaScript you can get the current date and time using the Date object;
var now = new Date();
This will get the local client machine time
Example for jquery LINK
If you are using jQuery DatePicker you can apply it on any textfield like this:
$( "#datepicker" ).datepicker({dateFormat:"yy/mm/dd"}).datepicker("setDate",new Date());
Use:
SELECT *
FROM YOUR_TABLE
WHERE creation_date <= TRUNC(SYSDATE) - 30
SYSDATE returns the date & time; TRUNC resets the date to being as of midnight so you can omit it if you want the creation_date
that is 30 days previous including the current time.
Depending on your needs, you could also look at using ADD_MONTHS:
SELECT *
FROM YOUR_TABLE
WHERE creation_date <= ADD_MONTHS(TRUNC(SYSDATE), -1)
I don't think you can tell with the std::string class. However, if you really need this information, you could always derive a class from std::string and give the derived class the ability to tell if it had been changed since construction (or some other arbitrary time). Or better yet, just write a new class that wraps std::string since deriving from std::string may not be a good idea given the lack of a base class virtual destructor. That's probably more work, but more work tends to be needed for an optimal solution.
Of course, you can always just assume if it contains something other than "" then it has been "set", this won't detect it manually getting set to "" though.
Simply call test2
from test1
like:
EXEC test2 @newId, @prod, @desc;
Make sure to get @id
using SCOPE_IDENTITY(), which gets the last identity value inserted into an identity column in the same scope:
SELECT @newId = SCOPE_IDENTITY()
The JD-eclipse plugin 0.1.3 can only decompile .class files that are visible from the classpath/Build Path.
If your class resides in a .jar, you may simply add this jar to the Build Path as another library. From the Package Explorer browse your new library and open the class in the Class File Editor.
If you want to decompile any class on the file system, it has to reside in the appropriate folder hierachy, and the root folder has to be included in the build path. Here is an example:
Note: If someDir is a subfolder of your project, you might be able to skip step 2 (link folder) and add it directly to the Build Path. But that does not work, if it is the compiler output folder of the Eclipse project.
P.S. I wish I could just double click any .class file in any project subfolder without the need to have it in the classpath...
a.button a:hover
means "a link that's being hovered over that is a child of a link with the class button
".
Go instead for a.button:hover
.
You're right that the SD Card directory is /sdcard
but you shouldn't be hard coding it. Instead, make a call to Environment.getExternalStorageDirectory()
to get the directory:
File sdDir = Environment.getExternalStorageDirectory();
If you haven't done so already, you will need to give your app the correct permission to write to the SD Card by adding the line below to your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
A handy timestamp format:
%date:~3,2%/%date:~0,2%/%date:~6,2%-%time:~0,8%
Since Google updates sometimes the name of fixed object properties, the best practice is to use GMaps V3 methods to get coordinates event.overlay.getPath().getArray() and to get lat latlng.lat() and lng latlng.lng().
So, I just wanted to improve this answer a bit exemplifying with polygon and POSTGIS insert case scenario:
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(event) {
var str_input ='POLYGON((';
if (event.type == google.maps.drawing.OverlayType.POLYGON) {
console.log('polygon path array', event.overlay.getPath().getArray());
$.each(event.overlay.getPath().getArray(), function(key, latlng){
var lat = latlng.lat();
var lon = latlng.lng();
console.log(lat, lon);
str_input += lat +' '+ lon +',';
});
}
str_input = str_input.substr(0,str_input.length-1) + '))';
console.log('the str_input will be:', str_input);
// YOU CAN THEN USE THE str_inputs AS IN THIS EXAMPLE OF POSTGIS POLYGON INSERT
// INSERT INTO your_table (the_geom, name) VALUES (ST_GeomFromText(str_input, 4326), 'Test')
});
Here's a method that doesn't use ArrayList. The user specifies the size and you can add a do-while loop for recursion.
import java.util.Scanner;
public class Dynamic {
public static Scanner value;
public static void main(String[]args){
value=new Scanner(System.in);
System.out.println("Enter the number of tests to calculate average\n");
int limit=value.nextInt();
int index=0;
int [] marks=new int[limit];
float sum,ave;
sum=0;
while(index<limit)
{
int test=index+1;
System.out.println("Enter the marks on test " +test);
marks[index]=value.nextInt();
sum+=marks[index];
index++;
}
ave=sum/limit;
System.out.println("The average is: " + ave);
}
}
Try this one.
#/bin/bash
testpid="abc,def,ghij"
count=`echo $testpid | grep -o ',' | wc -l` # this is not a good way
count=`expr $count + 1`
while [ $count -gt 0 ] ; do
echo $testpid | cut -d ',' -f $i
count=`expr $count - 1 `
done
or you can set pointer-events:none
to your a
element and pointer-event:all
to your a:before
element, and then add hover CSS to a element
a{
pointer-events:none;
}
a:before{
pointer-events:all
}
a:hover:before{
background:blue;
}
Here's one application that works for me. In our case...I wanted the Sales team to use SVN for certain docs (Price sheets and such)...but a bit over there head.
I setup an Auto SVN like this: - Created a REPO in my SVN server. - Checked out repo into a DB folder call AutoSVN. - I run EasySVN on my PC, which auto commits and updates the REPO.
With he 'Auto', there are no log comments, but not critical for these particular docs.
The Sales guys use the DB folder...and simply maintain the file name of those docs that need version control such as price sheets.
Python uses duck typing, so it doesn't need special syntax to handle multiple types.
If you're from a C++ background, you'll remember that, as long as the operations used in the template function/class are defined on some type T
(at the syntax level), you can use that type T
in the template.
So, basically, it works the same way:
You'll note however, that unless you write explicit type checking (which is usually discouraged), you won't be able to enforce that a binary tree contains only elements of the chosen type.
Step 1: Restart VS Code as an adminstrator
(click the windows key, search for "Visual Studio Code", right click, and you'll see the administrator option)
Step 2: In your VS code powershell terminal run Set-ExecutionPolicy Unrestricted
column(1)
is your friend.
$ column -t <<< '"option-y" yank-pop
> "option-z" execute-last-named-cmd
> "option-|" vi-goto-column
> "option-~" _bash_complete-word
> "option-control-?" backward-kill-word
> "control-_" undo
> "control-?" backward-delete-char
> '
"option-y" yank-pop
"option-z" execute-last-named-cmd
"option-|" vi-goto-column
"option-~" _bash_complete-word
"option-control-?" backward-kill-word
"control-_" undo
"control-?" backward-delete-char
for (var i in a) {
console.log(a[i],i)
}
Since C++11 it can be done inside a class with constexpr
.
class stat {
public:
// init inside class
static constexpr double inlineStaticVar = 22;
};
The variable can now be accessed with:
stat::inlineStaticVar
If Android decides to recreate your Fragment later, it's going to call the no-argument constructor of your fragment. So overloading the constructor is not a solution.
With that being said, the way to pass stuff to your Fragment so that they are available after a Fragment is recreated by Android is to pass a bundle to the setArguments
method.
So, for example, if we wanted to pass an integer to the fragment we would use something like:
public static MyFragment newInstance(int someInt) {
MyFragment myFragment = new MyFragment();
Bundle args = new Bundle();
args.putInt("someInt", someInt);
myFragment.setArguments(args);
return myFragment;
}
And later in the Fragment onCreate()
you can access that integer by using:
getArguments().getInt("someInt", 0);
This Bundle will be available even if the Fragment is somehow recreated by Android.
Also note: setArguments
can only be called before the Fragment is attached to the Activity.
This approach is also documented in the android developer reference: https://developer.android.com/reference/android/app/Fragment.html