In OpenCV header "types_c.h" there are a set of defines which generate these, the format is CV_bits{U|S|F}C<number_of_channels>
So for example CV_8UC3
means 8 bit unsigned chars, 3 colour channels - each of these names map onto an arbitrary integer with the macros in that file.
Edit: See "types_c.h" for example:
#define CV_8UC3 CV_MAKETYPE(CV_8U,3)
#define CV_MAKETYPE(depth,cn) (CV_MAT_DEPTH(depth) + (((cn)-1) << CV_CN_SHIFT))
eg.
depth = CV_8U = 0
cn = 3
CV_CN_SHIFT = 3
CV_MAT_DEPTH(0) = 0
(((cn)-1) << CV_CN_SHIFT) = (3-1) << 3 = 2<<3 = 16
So CV_8UC3 = 16
but you aren't supposed to use this number, just check type() == CV_8UC3
if you need to know what type an internal OpenCV array is.
Remember OpenCV will convert the jpeg into BGR (or grey scale if you pass '0' to imread
) - so it doesn't tell you anything about the original file.
Updated
How to implement page refresh in Angular 2+ note this is done within your component:
location.reload();
I tried the other solutions here, they work but I'm lazy so this is my solution
by right clicking it no longer registers mouse event since a context menu pops up, so you can move the mouse away safely
A nice approach would be to start up your processes and services running them in the background and use the wait [n ...]
command at the end of your script. In bash, the wait command forces the current process to:
Wait for each specified process and return its termination status. If n is not given, all currently active child processes are waited for, and the return status is zero.
I got this idea from Sébastien Pujadas' start script for his elk build.
Taking from the original question, your start-all.sh would look something like this...
#!/usr/bin/env bash
/etc/init.d/hadoop-hdfs-namenode start &
/etc/init.d/hadoop-hdfs-datanode start &
/etc/init.d/hadoop-hdfs-secondarynamenode start &
/etc/init.d/hadoop-0.20-mapreduce-tasktracker start &
sudo -u hdfs hadoop fs -chmod 777 /
/etc/init.d/hadoop-0.20-mapreduce-jobtracker start &
wait
You just missed an initialization step I think.
You can see what fonts you have available with the command windowsFonts()
. For example mine looks like this when I started looking at this:
> windowsFonts()
$serif
[1] "TT Times New Roman"
$sans
[1] "TT Arial"
$mono
[1] "TT Courier New"
After intalling the package extraFont and running font_import
like this (it took like 5 minutes):
library(extrafont)
font_import()
loadfonts(device = "win")
I had many more available - arguable too many, certainly too many to list here.
Then I tried your code:
library(ggplot2)
library(extrafont)
loadfonts(device = "win")
a <- ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
ggtitle("Fuel Efficiency of 32 Cars") +
xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
theme(text=element_text(size=16, family="Comic Sans MS"))
print(a)
yielding this:
You can find the name of a font you need for the family
parameter of element_text
with the following code snippet:
> names(wf[wf=="TT Times New Roman"])
[1] "serif"
And then:
library(ggplot2)
library(extrafont)
loadfonts(device = "win")
a <- ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
ggtitle("Fuel Efficiency of 32 Cars") +
xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
theme(text=element_text(size=16, family="serif"))
print(a)
I answered this question: How to secure an ASP.NET Web API 4 years ago using HMAC.
Now, lots of things changed in security, especially that JWT is getting popular. In this answer, I will try to explain how to use JWT in the simplest and basic way that I can, so we won't get lost from jungle of OWIN, Oauth2, ASP.NET Identity... :)
If you don't know about JWT tokens, you need to take a look at:
https://tools.ietf.org/html/rfc7519
Basically, a JWT token looks like this:
<base64-encoded header>.<base64-encoded claims>.<base64-encoded signature>
Example:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6ImN1b25nIiwibmJmIjoxNDc3NTY1NzI0LCJleHAiOjE0Nzc1NjY5MjQsImlhdCI6MTQ3NzU2NTcyNH0.6MzD1VwA5AcOcajkFyKhLYybr3h13iZjDyHm9zysDFQ
A JWT token has three sections:
If you use the website jwt.io with the token above, you can decode the token and see it like below:
Technically, JWT uses a signature which is signed from headers and claims with security algorithm specified in the headers (example: HMACSHA256). Therefore, JWT must be transferred over HTTPs if you store any sensitive information in its claims.
Now, in order to use JWT authentication, you don't really need an OWIN middleware if you have a legacy Web Api system. The simple concept is how to provide JWT token and how to validate the token when the request comes. That's it.
In the demo I've created (github), to keep the JWT token lightweight, I only store username
and expiration time
. But this way, you have to re-build new local identity (principal) to add more information like roles, if you want to do role authorization, etc. But, if you want to add more information into JWT, it's up to you: it's very flexible.
Instead of using OWIN middleware, you can simply provide a JWT token endpoint by using a controller action:
public class TokenController : ApiController
{
// This is naive endpoint for demo, it should use Basic authentication
// to provide token or POST request
[AllowAnonymous]
public string Get(string username, string password)
{
if (CheckUser(username, password))
{
return JwtManager.GenerateToken(username);
}
throw new HttpResponseException(HttpStatusCode.Unauthorized);
}
public bool CheckUser(string username, string password)
{
// should check in the database
return true;
}
}
This is a naive action; in production you should use a POST request or a Basic Authentication endpoint to provide the JWT token.
username
?You can use the NuGet package called System.IdentityModel.Tokens.Jwt
from Microsoft to generate the token, or even another package if you like. In the demo, I use HMACSHA256
with SymmetricKey
:
/// <summary>
/// Use the below code to generate symmetric Secret Key
/// var hmac = new HMACSHA256();
/// var key = Convert.ToBase64String(hmac.Key);
/// </summary>
private const string Secret = "db3OIsj+BXE9NZDy0t8W3TcNekrF+2d/1sFnWG4HnV8TZY30iTOdtVWJG8abWvB1GlOgJuQZdcF2Luqm/hccMw==";
public static string GenerateToken(string username, int expireMinutes = 20)
{
var symmetricKey = Convert.FromBase64String(Secret);
var tokenHandler = new JwtSecurityTokenHandler();
var now = DateTime.UtcNow;
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, username)
}),
Expires = now.AddMinutes(Convert.ToInt32(expireMinutes)),
SigningCredentials = new SigningCredentials(
new SymmetricSecurityKey(symmetricKey),
SecurityAlgorithms.HmacSha256Signature)
};
var stoken = tokenHandler.CreateToken(tokenDescriptor);
var token = tokenHandler.WriteToken(stoken);
return token;
}
The endpoint to provide the JWT token is done.
In the demo, I have built
JwtAuthenticationAttribute
which inherits from IAuthenticationFilter
(more detail about authentication filter in here).
With this attribute, you can authenticate any action: you just have to put this attribute on that action.
public class ValueController : ApiController
{
[JwtAuthentication]
public string Get()
{
return "value";
}
}
You can also use OWIN middleware or DelegateHander if you want to validate all incoming requests for your WebAPI (not specific to Controller or action)
Below is the core method from authentication filter:
private static bool ValidateToken(string token, out string username)
{
username = null;
var simplePrinciple = JwtManager.GetPrincipal(token);
var identity = simplePrinciple.Identity as ClaimsIdentity;
if (identity == null)
return false;
if (!identity.IsAuthenticated)
return false;
var usernameClaim = identity.FindFirst(ClaimTypes.Name);
username = usernameClaim?.Value;
if (string.IsNullOrEmpty(username))
return false;
// More validate to check whether username exists in system
return true;
}
protected Task<IPrincipal> AuthenticateJwtToken(string token)
{
string username;
if (ValidateToken(token, out username))
{
// based on username to get more information from database
// in order to build local identity
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, username)
// Add more claims if needed: Roles, ...
};
var identity = new ClaimsIdentity(claims, "Jwt");
IPrincipal user = new ClaimsPrincipal(identity);
return Task.FromResult(user);
}
return Task.FromResult<IPrincipal>(null);
}
The workflow is to use the JWT library (NuGet package above) to validate the JWT token and then return back ClaimsPrincipal
. You can perform more validation, like check whether user exists on your system, and add other custom validations if you want.
The code to validate JWT token and get principal back:
public static ClaimsPrincipal GetPrincipal(string token)
{
try
{
var tokenHandler = new JwtSecurityTokenHandler();
var jwtToken = tokenHandler.ReadToken(token) as JwtSecurityToken;
if (jwtToken == null)
return null;
var symmetricKey = Convert.FromBase64String(Secret);
var validationParameters = new TokenValidationParameters()
{
RequireExpirationTime = true,
ValidateIssuer = false,
ValidateAudience = false,
IssuerSigningKey = new SymmetricSecurityKey(symmetricKey)
};
SecurityToken securityToken;
var principal = tokenHandler.ValidateToken(token, validationParameters, out securityToken);
return principal;
}
catch (Exception)
{
//should write log
return null;
}
}
If the JWT token is validated and the principal is returned, you should build a new local identity and put more information into it to check role authorization.
Remember to add config.Filters.Add(new AuthorizeAttribute());
(default authorization) at global scope in order to prevent any anonymous request to your resources.
You can use Postman to test the demo:
Request token (naive as I mentioned above, just for demo):
GET http://localhost:{port}/api/token?username=cuong&password=1
Put JWT token in the header for authorized request, example:
GET http://localhost:{port}/api/value
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6ImN1b25nIiwibmJmIjoxNDc3NTY1MjU4LCJleHAiOjE0Nzc1NjY0NTgsImlhdCI6MTQ3NzU2NTI1OH0.dSwwufd4-gztkLpttZsZ1255oEzpWCJkayR_4yvNL1s
The demo can be found here: https://github.com/cuongle/WebApi.Jwt
Have you tried something like this? Put it in the head for it to work properly.
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(){
//using DOMContentLoaded is good as it relies on the DOM being ready for
//manipulation, rather than the windows being fully loaded. Just like
//how jQuery's $(document).ready() does it.
//loop through your inputs and set their values here
}, false);
</script>
I used
btn.setBackgroundColor(Color.TRANSPARENT);
and
android:background="@android:color/transparent"
Try this query -
SELECT
t2.company_name,
t2.expose_new,
t2.expose_used,
t1.title,
t1.seller,
t1.status,
CASE status
WHEN 'New' THEN t2.expose_new
WHEN 'Used' THEN t2.expose_used
ELSE NULL
END as 'expose'
FROM
`products` t1
JOIN manufacturers t2
ON
t2.id = t1.seller
WHERE
t1.seller = 4238
Only you want to set default value parameter. This calling third overloading method.
dt.Columns.Add("MyRow", type(System.Int32),0);
This is more likely to get you what you want:
Scanner input = new Scanner(System.in);
String s = input.next();
System.out.println(s);
1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,
2) AbstractTableModel should be useful, where is in the JTable
required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel
,
3) consider using DefaultTableModel
, (if you are not sure about how to works) instead of AbstractTableModel
,
could be generated from simple code:
import javax.swing.*;
import javax.swing.table.*;
public class TableCheckBox extends JFrame {
private static final long serialVersionUID = 1L;
private JTable table;
public TableCheckBox() {
Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
Object[][] data = {
{"Buy", "IBM", new Integer(1000), new Double(80.50), false},
{"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
{"Sell", "Apple", new Integer(3000), new Double(7.35), true},
{"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table = new JTable(model) {
private static final long serialVersionUID = 1L;
/*@Override
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}*/
@Override
public Class getColumnClass(int column) {
switch (column) {
case 0:
return String.class;
case 1:
return String.class;
case 2:
return Integer.class;
case 3:
return Double.class;
default:
return Boolean.class;
}
}
};
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
TableCheckBox frame = new TableCheckBox();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
});
}
}
You can easily override inline style except inline !important
style
so
<div style="font-size: 18px; color: red;">
Hello World, How Can I Change The Color To Blue?
</div>
div {
color: blue !important;
/* This will Work */
}
but if you have
<div style="font-size: 18px; color: red !important;">
Hello World, How Can I Change The Color To Blue?
</div>
div {
color: blue !important;
/* This Isn't Working */
}
now it will be red
only .. and you can not override it
Adding an answer as some others have upvoted in the comments of the accepted answer they are getting this exception when attempting to cast to ObjectNode (myself included):
Exception in thread "main" java.lang.ClassCastException:
com.fasterxml.jackson.databind.node.TextNode cannot be cast to com.fasterxml.jackson.databind.node.ObjectNode
The solution is to get the 'parent' node, and perform a put
, effectively replacing the entire node, regardless of original node type.
If you need to "modify" the node using the existing value of the node:
get
the value/array of the JsonNode
put
on the parent.Code, where the goal is to modify subfield
, which is the child node of NodeA
and Node1
:
JsonNode nodeParent = someNode.get("NodeA")
.get("Node1");
// Manually modify value of 'subfield', can only be done using the parent.
((ObjectNode) nodeParent).put('subfield', "my-new-value-here");
Credits:
I got this inspiration from here, thanks to wassgreen@
Functor can also be used to simulate defining a local function within a function. Refer to the question and another.
But a local functor can not access outside auto variables. The lambda (C++11) function is a better solution.
Some people have already mentioned HttpURLConnection, URL and URLConnection. If you need all the control and extra features that the curl library provides you (and more), I'd recommend Apache's httpclient.
As suggested above I tried below one with fail.
store.proxy.reader.jsonData
But below one worked for me
store.proxy.reader.rawData
It is all but satisfying, isn't it? The easiest way I have found to specify when setting the context, e.g.:
sns.set_context("paper", rc={"font.size":8,"axes.titlesize":8,"axes.labelsize":5})
This should take care of 90% of standard plotting usage. If you want ticklabels smaller than axes labels, set the 'axes.labelsize' to the smaller (ticklabel) value and specify axis labels (or other custom elements) manually, e.g.:
axs.set_ylabel('mylabel',size=6)
you could define it as a function and load it in your scripts so you don't have to remember your standard numbers, or call it every time.
def set_pubfig:
sns.set_context("paper", rc={"font.size":8,"axes.titlesize":8,"axes.labelsize":5})
Of course you can use configuration files, but I guess the whole idea is to have a simple, straightforward method, which is why the above works well.
Note: If you specify these numbers, specifying font_scale
in sns.set_context
is ignored for all specified font elements, even if you set it.
According to Joshua Bloch (Effective Java), you should use private constructor which always throws exception. That will finally discourage user to create instance of util class.
Marking class abstract is not recommended because is abstract suggests reader that class is designed for inheritance.
You have to set the associatedEmployee on the Vehicle before persisting the Employee.
Employee newEmployee = new Employee("matt");
vehicle1.setAssociatedEmployee(newEmployee);
vehicles.add(vehicle1);
newEmployee.setVehicles(vehicles);
Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);
keep in mind that avoiding text scaling is the main reason responsive layouts exist. the entire logic behind responsive sites is to create functional layouts that effectively display your content so its easily readable and usable on multiple screen sizes.
Although It is necessary to scale text in some cases, be careful not to miniaturise your site and miss the point.
heres an example anyway.
@media(min-width:1200px){
h1 {font-size:34px}
}
@media(min-width:992px){
h1 {font-size:32px}
}
@media(min-width:768px){
h1 {font-size:28px}
}
@media(max-width:767px){
h1 {font-size:26px}
}
Also keep in mind the 480 viewport has been dropped in bootstrap 3.
I have faced a similar issue working in a multiple modules app environment:
Error: Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'. More than one file was found with OS independent path 'META-INF/AL2.0'
This issue was being reported by several of these modules of mine and none of the above solutions were fixing it. Turns out, I was using version Coroutines 1.3.6 which seemed to be embedding META-INF/AL2.0 which was already embedded by another of the libraries I was using. To fix it, I have added the following code snippet to the build.gradle of the module that was failing:
configurations.all {
resolutionStrategy {
exclude group: "org.jetbrains.kotlinx", module: "kotlinx-coroutines-debug"
}
}
Given that it was happening on multiple modules, I have moved that resolutionStrategy
code to my project level build.gradle.
Everything worked after that.
\w
matches a word character. \b
is a zero-width match that matches a position character that has a word character on one side, and something that's not a word character on the other. (Examples of things that aren't word characters include whitespace, beginning and end of the string, etc.)
\w
matches a
, b
, c
, d
, e
, and f
in "abc def"
\b
matches the (zero-width) position before a
, after c
, before d
, and after f
in "abc def"
The easiest way to pass ArrayList using intent
Add this line in dependencies block build.gradle.
implementation 'com.google.code.gson:gson:2.2.4'
pass arraylist
ArrayList<String> listPrivate = new ArrayList<>();
Intent intent = new Intent(MainActivity.this, ListActivity.class);
intent.putExtra("private_list", new Gson().toJson(listPrivate));
startActivity(intent);
retrieve list in another activity
ArrayList<String> listPrivate = new ArrayList<>();
Type type = new TypeToken<List<String>>() {
}.getType();
listPrivate = new Gson().fromJson(getIntent().getStringExtra("private_list"), type);
You can use object also instead of String in type
Works for me..
I think what you are looking for is something like this:
$(field).closest("form").submit();
For example, to handle the onchange event, you would have this:
$(select your fields here).change(function() {
$(this).closest("form").submit();
});
If, for some reason you aren't using jQuery 1.3 or above, you can call parents
instead of closest
.
I want to say something about the "G" status,
G: Changes on the repo were automatically merged into the working copy
I think the above definition is not cleary, it can generate a little confusion, because all files are automatically merged in to working copy, the correct one should be:
U = item (U)pdated to repository version
G = item’s local changes mer(G)ed with repository
C = item’s local changes (C)onflicted with repository
D = item (D)eleted from working copy
A = item (A)dded to working copy
You can use the parse
method from the URL module in the request callback.
var http = require('http');
var url = require('url');
// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
var queryData = url.parse(request.url, true).query;
response.writeHead(200, {"Content-Type": "text/plain"});
if (queryData.name) {
// user told us their name in the GET request, ex: http://host:8000/?name=Tom
response.end('Hello ' + queryData.name + '\n');
} else {
response.end("Hello World\n");
}
});
// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);
I suggest you read the HTTP module documentation to get an idea of what you get in the createServer
callback. You should also take a look at sites like http://howtonode.org/ and checkout the Express framework to get started with Node faster.
The C++ string class is std::string
. To use it you need to include the <string>
header.
For the fundamentals of how to use std::string
, you'll want to consult a good introductory C++ book.
You have to use Convert.FromBase64String to turn a Base64 encoded string
into a byte[]
.
You have to run 'bibtex':
latex paper.tex
bibtex paper
latex paper.tex
latex paper.tex
dvipdf paper.dvi
Yes, Slack has the ability to hyperlink words, as long as Format messages with markup is unchecked under Preferences > Advanced to show the formatting toolbar. According to the documentation, start out with one of these:
- Select text, then click the link icon in the formatting toolbar
- Select text, then press ?ShiftU on Mac or CtrlShiftU on Windows/Linux.
Then do this:
Copy the link you'd like to share and paste it in the empty field under Link, then click Save.
What follows is how this answer used to read when it first became so famous. It was correct until about February 2020.
No.
As a couple of commenters said, and as the Slack documentation says:
Note: It’s not possible to hyperlink words in a Slack message.
You were close... after your code of
WindowState = FormWindowState.Maximized;
THEN, set the form's min/max size capacity to the value once its sized out.
MinimumSize = this.Size;
MaximumSize = this.Size;
Dependency
dependencies {
implementation 'com.squareup.picasso:picasso:2.71828'
}
//Java Code for Image Loading into imageView
Picasso.get().load(werURL).into(imageView);
If you want to delete all records then as a workaround load an empty file into table in OVERWRITE mode
hive> LOAD DATA LOCAL INPATH '/root/hadoop/textfiles/empty.txt' OVERWRITE INTO TABLE employee;
Loading data to table default.employee
Table default.employee stats: [numFiles=1, numRows=0, totalSize=0, rawDataSize=0]
OK
Time taken: 0.19 seconds
hive> SELECT * FROM employee;
OK
Time taken: 0.052 seconds
Incase you need to format the answer in a particular way, you can easily use this method, the default = "dd-MM-yyyy".
extension Date {
func today(format : String = "dd-MM-yyyy") -> String{
let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = format
return formatter.string(from: date)
}
}
Getting today's date can now be done using
Date().today() or Date().today("dd/MM/yyyy")
This worked for me.
You need to run it twice once for globals followed by locals
for name in dir():
if not name.startswith('_'):
del globals()[name]
for name in dir():
if not name.startswith('_'):
del locals()[name]
An array can be initialized by using the new Object {}
syntax.
For example, an array of String
can be declared by either:
String[] s = new String[] {"One", "Two", "Three"};
String[] s2 = {"One", "Two", "Three"};
Primitives can also be similarly initialized either by:
int[] i = new int[] {1, 2, 3};
int[] i2 = {1, 2, 3};
Or an array of some Object
:
Point[] p = new Point[] {new Point(1, 1), new Point(2, 2)};
All the details about arrays in Java is written out in Chapter 10: Arrays in The Java Language Specifications, Third Edition.
First App ID
make sure your ID push notification enable in production side
as appear in picture
Second Certificate
from production section create two certificate with your id (push notification enabled)
App Store and Ad Hoc certificate
Apple Push Notification service SSL (Sandbox) certificate
Third Provisioning Profiles
From Distribution section create App Store profile with your id
Finally
while you upload your bin , you must check what provisioning profile used and have many entitlements
this all cases cause this problem hope this be helpful with you
You will find these assemblies in the Extensions group under Assemblies in Visual Studio 2010, 2012 & 2013 (Reference Manager)
You would define a constructor in an abstract class if you are in one of these situations:
Note that:
In any case, don't forget that if you don't define a constructor, then the compiler will automatically generate one for you (this one is public, has no argument, and does nothing).
Can use either json or ast python modules:
Using json :
=============
import json
jsonStr = '{"one" : "1", "two" : "2", "three" : "3"}'
json_data = json.loads(jsonStr)
print(f"json_data: {json_data}")
print(f"json_data['two']: {json_data['two']}")
Output:
json_data: {'one': '1', 'two': '2', 'three': '3'}
json_data['two']: 2
Using ast:
==========
import ast
jsonStr = '{"one" : "1", "two" : "2", "three" : "3"}'
json_dict = ast.literal_eval(jsonStr)
print(f"json_dict: {json_dict}")
print(f"json_dict['two']: {json_dict['two']}")
Output:
json_dict: {'one': '1', 'two': '2', 'three': '3'}
json_dict['two']: 2
Using jQuery UI dialog:
SCRIPT:
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script>
$(function () {
$("#<%=btnUserDelete.ClientID%>").on("click", function (event) {
event.preventDefault();
$("#dialog-confirm").dialog({
resizable: false,
height: 140,
modal: true,
buttons: {
Ok: function () {
$(this).dialog("close");
__doPostBack($('#<%= btnUserDelete.ClientID %>').attr('name'), '');
},
Cancel: function () {
$(this).dialog("close");
}
}
});
});
});
</script>
HTML:
<div id="dialog-confirm" style="display: none;" title="Confirm Delete">
<p><span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span>Are you sure you want to delete this user?</p>
</div>
Generally you shouldn't rely on system properties to configure a webapp - they may be used to configure the container (e.g. Tomcat) but not an application running inside tomcat.
cliff.meyers has already mentioned the way you should rather use for your webapplication. That's the standard way, that also fits your question of being configurable through context.xml or server.xml means.
That said, should you really need system properties or other jvm options (like max memory settings) in tomcat, you should create a file named "bin/setenv.sh" or "bin/setenv.bat". These files do not exist in the standard archive that you download, but if they are present, the content is executed during startup (if you start tomcat via startup.sh/startup.bat). This is a nice way to separate your own settings from the standard tomcat settings and makes updates so much easier. No need to tweak startup.sh or catalina.sh.
(If you execute tomcat as windows servive, you usually use tomcat5w.exe, tomcat6w.exe etc. to configure the registry settings for the service.)
EDIT: Also, another possibility is to go for JNDI Resources.
I use shared preferences, but Android Studio complained about Editor symbol. Then, I added
import android.content.SharedPreferences.Editor;
and symbol is cool now.
Here's a different approach. The heart of it was created by turning on the Macro Recorder and filtering the columns per your specifications. Then there's a bit of code to copy the results. It will run faster than looping through each row and column:
Sub FilterAndCopy()
Dim LastRow As Long
Sheets("Sheet2").UsedRange.Offset(0).ClearContents
With Worksheets("Sheet1")
.Range("$A:$E").AutoFilter
.Range("$A:$E").AutoFilter field:=1, Criteria1:="#N/A"
.Range("$A:$E").AutoFilter field:=2, Criteria1:="=String1", Operator:=xlOr, Criteria2:="=string2"
.Range("$A:$E").AutoFilter field:=3, Criteria1:=">0"
.Range("$A:$E").AutoFilter field:=5, Criteria1:="Number"
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
.Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
Destination:=Sheets("Sheet2").Range("A1")
End With
End Sub
As a side note, your code has more loops and counter variables than necessary. You wouldn't need to loop through the columns, just through the rows. You'd then check the various cells of interest in that row, much like you did.
First, the signature of your data() function:
bool data(struct *sampleData)
cannot possibly work, because the argument lacks a name. When you declare a function argument that you intend to actually access, it needs a name. So change it to something like:
bool data(struct sampleData *samples)
But in C++, you don't need to use struct
at all actually. So this can simply become:
bool data(sampleData *samples)
Second, the sampleData
struct is not known to data() at that point. So you should declare it before that:
struct sampleData {
int N;
int M;
string sample_name;
string speaker;
};
bool data(sampleData *samples)
{
samples->N = 10;
samples->M = 20;
// etc.
}
And finally, you need to create a variable of type sampleData
. For example, in your main() function:
int main(int argc, char *argv[]) {
sampleData samples;
data(&samples);
}
Note that you need to pass the address of the variable to the data() function, since it accepts a pointer.
However, note that in C++ you can directly pass arguments by reference and don't need to "emulate" it with pointers. You can do this instead:
// Note that the argument is taken by reference (the "&" in front
// of the argument name.)
bool data(sampleData &samples)
{
samples.N = 10;
samples.M = 20;
// etc.
}
int main(int argc, char *argv[]) {
sampleData samples;
// No need to pass a pointer here, since data() takes the
// passed argument by reference.
data(samples);
}
a.button:hover{
background: #383; }
works for me but in my case
#buttonClick:hover {
background-color:green; }
As Hogan notes above, use an AND
instead of &
. See this tutorial for more info.
It's the destructor. This method is called when the instance of your class is destroyed:
Stack<int> *stack= new Stack<int>;
//do something
delete stack; //<- destructor is called here;
It's an old post but i'll leave here my javascript solution just in case someone need it.
// you only need this function_x000D_
function sticky( _el ){_x000D_
_el.parentElement.addEventListener("scroll", function(){_x000D_
_el.style.transform = "translateY("+this.scrollTop+"px)";_x000D_
});_x000D_
}_x000D_
_x000D_
_x000D_
// how to make it work:_x000D_
// get the element you want to be sticky_x000D_
var el = document.querySelector("#blbl > div");_x000D_
// give the element as argument, done._x000D_
sticky(el);
_x000D_
#blbl{_x000D_
position:relative;_x000D_
height:200px; _x000D_
overflow: auto;_x000D_
background: #eee;_x000D_
}_x000D_
_x000D_
#blbl > div{_x000D_
position:absolute; _x000D_
padding:50px; _x000D_
top:10px; _x000D_
left:10px; _x000D_
background: #f00_x000D_
}
_x000D_
<div id="blbl" >_x000D_
<div><!-- sticky div --></div> _x000D_
_x000D_
<br><br><br><br><br><br><br><br><br><br><br><br><br>_x000D_
<br><br><br><br><br><br><br><br><br><br><br><br><br>_x000D_
<br><br><br><br><br><br><br><br><br><br><br><br><br>_x000D_
<br><br><br><br><br><br><br><br><br><br><br><br><br>_x000D_
</div>
_x000D_
Notes
I used transform: translateY(@px) because it should be lightweight to compute, high-performance-animations
I only tried this function with modern browsers, it won't work for old browsers where vendors are required (and IE of course)
You could also try the dateparser module, which may be slower than datefinder on free text but which should cover more potential cases and date formats, as well as a significant number of languages.
http://msdn.microsoft.com/en-us/library/f02979c7(v=VS.90).aspx
You can pass nothing if you don't need the returned integer like so
if integer.TryParse(number,nothing) then
::
is basically a namespace resolution operator. It allows you to access items in modules, or class-level items in classes. For example, say you had this setup:
module SomeModule
module InnerModule
class MyClass
CONSTANT = 4
end
end
end
You could access CONSTANT
from outside the module as SomeModule::InnerModule::MyClass::CONSTANT
.
It doesn't affect instance methods defined on a class, since you access those with a different syntax (the dot .
).
Relevant note: If you want to go back to the top-level namespace, do this: ::SomeModule – Benjamin Oakes
With Ramda, you can simply do R.isNil(yourValue)
Lodash and other helper libraries have the same function.
I want to open external storage directory path for saving file programatically.I tried but not getting sdcard path. How can i do this?is there any solution for this??
To store your app files in SD card, you should use File[] getExternalFilesDirs (String type)
method in Context
class. Generally, second returned path would be the storage path for microSD card (if any).
On my phone, second path returned was /storage/sdcard1/Android/data/your.application.package.appname/files
after passing null
as argument to getExternalFilesDirs (String type)
. But path may vary on different phones, different Android versions.
Both File getExternalStorageDirectory ()
and File getExternalStoragePublicDirectory (String type)
in Environment
class may return SD card directory or internal memory directory depending on your phone's model and Android OS version.
Because According to Official Android Guide external storage can be
removable storage media (such as an SD card) or an internal (non-removable) storage.
The Internal and External Storage terminology according to Google/official Android docs is quite different from what we think.
Now, if the repository is already existing on a remote machine, and you do not have anything locally, you do git clone instead.
The URL format is simple, it is PROTOCOL:/[user@]remoteMachineAddress/path/to/repository.git
For example, cloning a repository on a machine to which you have SSH access using the "dev" user, residing in /srv/repositories/awesomeproject.git and that machine has the ip 10.11.12.13 you do:
git clone ssh://[email protected]/srv/repositories/awesomeproject.git
You can now simply do Instant.parse("2015-04-28T14:23:38.521Z")
and get the correct thing now, especially since you should be using Instant
instead of the broken java.util.Date
with the most recent versions of Java.
You should be using DateTimeFormatter
instead of SimpleDateFormatter
as well.
The explanation below is still valid as as what the format represents. But it was written before Java 8 was ubiquitous so it uses the old classes that you should not be using if you are using Java 8 or higher.
Z
as demonstrated:In the pattern the
T
is escaped with'
on either side.The pattern for the
Z
at the end is actuallyXXX
as documented in the JavaDoc forSimpleDateFormat
, it is just not very clear on actually how to use it sinceZ
is the marker for the oldTimeZone
information as well.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
public class Q2597083
{
/**
* All Dates are normalized to UTC, it is up the client code to convert to the appropriate TimeZone.
*/
public static final TimeZone UTC;
/**
* @see <a href="http://en.wikipedia.org/wiki/ISO_8601#Combined_date_and_time_representations">Combined Date and Time Representations</a>
*/
public static final String ISO_8601_24H_FULL_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";
/**
* 0001-01-01T00:00:00.000Z
*/
public static final Date BEGINNING_OF_TIME;
/**
* 292278994-08-17T07:12:55.807Z
*/
public static final Date END_OF_TIME;
static
{
UTC = TimeZone.getTimeZone("UTC");
TimeZone.setDefault(UTC);
final Calendar c = new GregorianCalendar(UTC);
c.set(1, 0, 1, 0, 0, 0);
c.set(Calendar.MILLISECOND, 0);
BEGINNING_OF_TIME = c.getTime();
c.setTime(new Date(Long.MAX_VALUE));
END_OF_TIME = c.getTime();
}
public static void main(String[] args) throws Exception
{
final SimpleDateFormat sdf = new SimpleDateFormat(ISO_8601_24H_FULL_FORMAT);
sdf.setTimeZone(UTC);
System.out.println("sdf.format(BEGINNING_OF_TIME) = " + sdf.format(BEGINNING_OF_TIME));
System.out.println("sdf.format(END_OF_TIME) = " + sdf.format(END_OF_TIME));
System.out.println("sdf.format(new Date()) = " + sdf.format(new Date()));
System.out.println("sdf.parse(\"2015-04-28T14:23:38.521Z\") = " + sdf.parse("2015-04-28T14:23:38.521Z"));
System.out.println("sdf.parse(\"0001-01-01T00:00:00.000Z\") = " + sdf.parse("0001-01-01T00:00:00.000Z"));
System.out.println("sdf.parse(\"292278994-08-17T07:12:55.807Z\") = " + sdf.parse("292278994-08-17T07:12:55.807Z"));
}
}
sdf.format(BEGINNING_OF_TIME) = 0001-01-01T00:00:00.000Z
sdf.format(END_OF_TIME) = 292278994-08-17T07:12:55.807Z
sdf.format(new Date()) = 2015-04-28T14:38:25.956Z
sdf.parse("2015-04-28T14:23:38.521Z") = Tue Apr 28 14:23:38 UTC 2015
sdf.parse("0001-01-01T00:00:00.000Z") = Sat Jan 01 00:00:00 UTC 1
sdf.parse("292278994-08-17T07:12:55.807Z") = Sun Aug 17 07:12:55 UTC 292278994
When using git rm, the removal will part of your next commit. So if you want to push the change you should use git rm
MySQL only listens to localhost, if we want to enable the remote access to it, then we need to made some changes in my.cnf file:
sudo nano /etc/mysql/my.cnf
We need to comment out the bind-address and skip-external-locking lines:
#bind-address = 127.0.0.1
# skip-external-locking
After making these changes, we need to restart the mysql service:
sudo service mysql restart
Here is what I ended up using
$ipaddress = $(ipconfig | where {$_ -match 'IPv4.+\s(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' } | out-null; $Matches[1])
which breaks down as
Is there a native android way to get a reference to the currently running Activity from a service?
You may not own the "currently running Activity".
I have a service running on the background, and I would like to update my current Activity when an event occurs (in the service). Is there a easy way to do that (like the one I suggested above)?
Intent
to the activity -- here is a sample project demonstrating this patternPendingIntent
(e.g., via createPendingResult()
) that the service invokesbindService()
, and have the service call an event method on that callback/listener objectIntent
to the activity, with a low-priority BroadcastReceiver
as backup (to raise a Notification
if the activity is not on-screen) -- here is a blog post with more on this patternYou will get all the class in below array
event.target.classList
Every time I use finish to close the fragment, the entire activity closes. According to the docs, fragments should remain as long as the parent activity remains.
Instead, I found that I can change views back the the parent activity by using this statement: setContentView(R.layout.activity_main);
This returns me back to the parent activity.
I hope that this helps someone else who may be looking for this.
Here is an answer based on that by Anubis (which is a better approach as it doesn't modify the headers for every request) but which is more equivalent to the code in the original question:
using Newtonsoft.Json;
...
var client = new HttpClient();
var httpRequestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri("https://api.clickatell.com/rest/message"),
Headers = {
{ HttpRequestHeader.Authorization.ToString(), "Bearer xxxxxxxxxxxxxxxxxxx" },
{ HttpRequestHeader.Accept.ToString(), "application/json" },
{ "X-Version", "1" }
},
Content = new StringContent(JsonConvert.SerializeObject(svm))
};
var response = client.SendAsync(httpRequestMessage).Result;
I was able to build a library source code to compiled .jar
file, using approach from this solution:
https://stackoverflow.com/a/19037807/1002054
Here is the breakdown of what I did:
In may case it was a Volley library
I used Android Studio 0.3.7. I've encountered some issues during that step, namely I had to copy gradle
folder from new android project before I was able to import Volley library source code, this may vary depending on source code you use.
build.gradle
file// If your module is a library project, this is needed
//to properly recognize 'android-library' plugin
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.6.3'
}
}
apply plugin: 'android-library'
android {
compileSdkVersion 17
buildToolsVersion = 17
sourceSets {
main {
// Here is the path to your source code
java {
srcDir 'src'
}
}
}
}
// This is the actual solution, as in https://stackoverflow.com/a/19037807/1002054
task clearJar(type: Delete) {
delete 'build/libs/myCompiledLibrary.jar'
}
task makeJar(type: Copy) {
from('build/bundles/release/')
into('build/libs/')
include('classes.jar')
rename ('classes.jar', 'myCompiledLibrary.jar')
}
makeJar.dependsOn(clearJar, build)
gradlew makeJar
command from your project root.I my case I had to copy gradlew.bat
and gradle
files from new android project into my library project root.
You should find your compiled library file myCompiledLibrary.jar
in build\libs
directory.
I hope someone finds this useful.
Edit:
Althought this works, you will encounter duplicate library exception while compiling a project with multiple modules, where more than one module (including application module) depends on the same jar
file (eg. modules have own library directory, that is referenced in build.gradle
of given module).
In case where you need to use single library in more then one module, I would recommend using this approach: Android gradle build and the support library
Unless someone can recommend a free tool to do this, you can achieve this with ReSharper:
ReSharper >> Options... >> Languages/C# >> Line Breaks and Wrapping
Hope that helps.
$scope.downloadSearchAsCSV = function(httpOptions) {
var httpOptions = _.extend({
method: 'POST',
url: '',
data: null
}, httpOptions);
$http(httpOptions).then(function(response) {
if( response.status >= 400 ) {
alert(response.status + " - Server Error \nUnable to download CSV from POST\n" + JSON.stringify(httpOptions.data));
} else {
$scope.downloadResponseAsCSVFile(response)
}
})
};
/**
* @source: https://github.com/asafdav/ng-csv/blob/master/src/ng-csv/directives/ng-csv.js
* @param response
*/
$scope.downloadResponseAsCSVFile = function(response) {
var charset = "utf-8";
var filename = "search_results.csv";
var blob = new Blob([response.data], {
type: "text/csv;charset="+ charset + ";"
});
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, filename); // @untested
} else {
var downloadContainer = angular.element('<div data-tap-disabled="true"><a></a></div>');
var downloadLink = angular.element(downloadContainer.children()[0]);
downloadLink.attr('href', window.URL.createObjectURL(blob));
downloadLink.attr('download', "search_results.csv");
downloadLink.attr('target', '_blank');
$document.find('body').append(downloadContainer);
$timeout(function() {
downloadLink[0].click();
downloadLink.remove();
}, null);
}
//// Gets blocked by Chrome popup-blocker
//var csv_window = window.open("","","");
//csv_window.document.write('<meta name="content-type" content="text/csv">');
//csv_window.document.write('<meta name="content-disposition" content="attachment; filename=data.csv"> ');
//csv_window.document.write(response.data);
};
With the new version of sdk, the accepted answer does not work - it does not wait for the object to be downloaded. The following code snippet will help with the new version:
// dependencies
const AWS = require('aws-sdk');
// get reference to S3 client
const s3 = new AWS.S3();
exports.handler = async (event, context, callback) => {
var bucket = "TestBucket"
var key = "TestKey"
try {
const params = {
Bucket: Bucket,
Key: Key
};
var theObject = await s3.getObject(params).promise();
} catch (error) {
console.log(error);
return;
}
}
CREATE OR REPLACE PROCEDURE ADDEMP
(xml IN CLOB)
AS
BEGIN
INSERT INTO EMPLOYEE (EMPID,EMPNAME,EMPDETAIL,CREATEDBY,CREATED)
SELECT
ExtractValue(column_value,'/ROOT/EMPID') AS EMPID
,ExtractValue(column_value,'/ROOT/EMPNAME') AS EMPNAME
,ExtractValue(column_value,'/ROOT/EMPDETAIL') AS EMPDETAIL
,ExtractValue(column_value,'/ROOT/CREATEDBY') AS CREATEDBY
,ExtractValue(column_value,'/ROOT/CREATEDDATE') AS CREATEDDATE
FROM TABLE(XMLSequence( XMLType(xml))) XMLDUMMAY;
COMMIT;
END;
As of iOS 7 or 8, you can do this (need Entitlement for iOS 12+ as shown below):
@import SystemConfiguration.CaptiveNetwork;
/** Returns first non-empty SSID network info dictionary.
* @see CNCopyCurrentNetworkInfo */
- (NSDictionary *)fetchSSIDInfo {
NSArray *interfaceNames = CFBridgingRelease(CNCopySupportedInterfaces());
NSLog(@"%s: Supported interfaces: %@", __func__, interfaceNames);
NSDictionary *SSIDInfo;
for (NSString *interfaceName in interfaceNames) {
SSIDInfo = CFBridgingRelease(
CNCopyCurrentNetworkInfo((__bridge CFStringRef)interfaceName));
NSLog(@"%s: %@ => %@", __func__, interfaceName, SSIDInfo);
BOOL isNotEmpty = (SSIDInfo.count > 0);
if (isNotEmpty) {
break;
}
}
return SSIDInfo;
}
Example output:
2011-03-04 15:32:00.669 ShowSSID[4857:307] -[ShowSSIDAppDelegate fetchSSIDInfo]: Supported interfaces: (
en0
)
2011-03-04 15:32:00.693 ShowSSID[4857:307] -[ShowSSIDAppDelegate fetchSSIDInfo]: en0 => {
BSSID = "ca:fe:ca:fe:ca:fe";
SSID = XXXX;
SSIDDATA = <01234567 01234567 01234567>;
}
Note that no ifs are supported on the simulator. Test on your device.
You must enable access wifi info from capabilities.
Important To use this function in iOS 12 and later, enable the Access WiFi Information capability for your app in Xcode. When you enable this capability, Xcode automatically adds the Access WiFi Information entitlement to your entitlements file and App ID. Documentation link
Swift 4.2
func getConnectedWifiInfo() -> [AnyHashable: Any]? {
if let ifs = CFBridgingRetain( CNCopySupportedInterfaces()) as? [String],
let ifName = ifs.first as CFString?,
let info = CFBridgingRetain( CNCopyCurrentNetworkInfo((ifName))) as? [AnyHashable: Any] {
return info
}
return nil
}
Just use
$location.url();
Instead of
$location.path();
Just in case somebody finds it usefull.
I had a problem with the KEYCODE_DPAD_UP it belongs to the trackBall. to solve this change your avdfolder/config.ini hw.trackBall=yes and push DEL or F6
"The project works on the laptop, but now having copied the updated source code onto the desktop ..."
I did something similar, creating two versions of a project and copying files between them. It gave me the same error.
My solution was to go into the project file, where I discovered that what had looked like this:
<Compile Include="App_Code\Common\Pair.cs" />
<Compile Include="App_Code\Common\QueryCommand.cs" />
Now looked like this:
<Content Include="App_Code\Common\Pair.cs">
<SubType>Code</SubType>
</Content>
<Content Include="App_Code\Common\QueryCommand.cs">
<SubType>Code</SubType>
</Content>
When I changed them back, Visual Studio was happy again.
I ran into an issue with Andy Earnshaw's answer because I had factored this function out to a separate class within my application, "HelperFunctions", which meant the recursive call to objectToArray() failed.
I overcame this by specifying the class name within the array_map call like so:
public function objectToArray($object) {
if (!is_object($object) && !is_array($object))
return $object;
return array_map(array("HelperFunctions", "objectToArray"), (array) $object);
}
I would have written this in the comments but I don't have enough reputation yet.
The standard way to see if a file exists is with the Test-Path
cmdlet.
Test-Path -path $filename
for mac :- take checkout from server side and a new window will open to select directory from your local machine than put your all code in selected folder then open svn local side and add and commit the project
I would start by turning off TCP offloading. There have been a few things that cause intermittent connectivity issues and this is the one that is usually the culprit.
Note: I have seen this setting cause problems on Win Server 2003 and Win Server 2008
http://blogs.msdn.com/b/mssqlisv/archive/2008/05/27/sql-server-intermittent-connectivity-issue.aspx
http://technet.microsoft.com/en-us/library/gg162682(v=ws.10).aspx
Working solution for all modern browsers.
input[type=checkbox] {_x000D_
transform: scale(1.5);_x000D_
}
_x000D_
<label><input type="checkbox"> Test</label>
_x000D_
Appearance:
[Possibly Windows only]
Beware of spaces in the path, even when your jar is in the current working directory. For example, for me this was failing:
java -jar myjar.jar
I was able to fix this by givng the full, quoted path to the jar:
java -jar "%~dp0\myjar.jar"
Credit goes to this answer for setting me on the right path....
You can delete any QuerySet you'd like. For example, to delete all blog posts with some Post model
Post.objects.all().delete()
and to delete any Post with a future publication date
Post.objects.filter(pub_date__gt=datetime.now()).delete()
You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.
EDIT:
Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForm
s and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.
This works for me. Kudos go here.
jQuery.fn.redraw = function() {
return this.hide(0, function() {
$(this).show();
});
};
$(el).redraw();
If your text is in a Bash variable, then Parameter Substitution ${var//\\//}
can replace substrings:
$ p='C:\foo\bar.xml'
$ printf '%s\n' "$p"
C:\foo\bar.xml
$ printf '%s\n' "${p//\\//}"
C:/foo/bar.xml
This may be leaner and clearer that filtering through a command such as tr
or sed
.
Take a look at cat /proc/stat
grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage "%"}'
EDIT please read comments before copy-paste this or using this for any serious work. This was not tested nor used, it's an idea for people who do not want to install a utility or for something that works in any distribution. Some people think you can "apt-get install" anything.
NOTE: this is not the current CPU usage, but the overall CPU usage in all the cores since the system bootup. This could be very different from the current CPU usage. To get the current value top (or similar tool) must be used.
Current CPU usage can be potentially calculated with:
awk '{u=$2+$4; t=$2+$4+$5; if (NR==1){u1=u; t1=t;} else print ($2+$4-u1) * 100 / (t-t1) "%"; }' \
<(grep 'cpu ' /proc/stat) <(sleep 1;grep 'cpu ' /proc/stat)
In Oracle :
ALTER TABLE one ADD two_id INTEGER CONSTRAINT Fk_two_id REFERENCES two(id);
public static void main(String[] args) {
System.out.println(longestPalindromeString("9912333321456"));
}
static public String intermediatePalindrome(String s, int left, int right) {
if (left > right) return null;
while (left >= 0 && right < s.length()
&& s.charAt(left) == s.charAt(right)) {
left--;
right++;
}
return s.substring(left + 1, right);
}
public static String longestPalindromeString(String s) {
if (s == null) return null;
String longest = s.substring(0, 1);
for (int i = 0; i < s.length() - 1; i++) {
//odd cases like 121
String palindrome = intermediatePalindrome(s, i, i);
if (palindrome.length() > longest.length()) {
longest = palindrome;
}
//even cases like 1221
palindrome = intermediatePalindrome(s, i, i + 1);
if (palindrome.length() > longest.length()) {
longest = palindrome;
}
}
return longest;
}
For new projects, I've started having every class I write extend the same base class where I can put all the utility methods that are annoyingly missing from Java like this one, the equivalent for collections (tired of writing list != null && ! list.isEmpty()), null-safe equals, etc. I still use Apache Commons for the implementation but this saves a small amount of typing and I haven't seen any negative effects.
The 1st element as in no hard returns. A hard return I guess = an empty node/element in the DOM which becomes the 1st element disabling the doc compatability meta tag.
You haven't posted the findvertex
method, but Access Reading Violation with an offset like 0x00000048
means that the Vertex* f;
in your getCost function is receiving null, and when trying to access the member adj
in the null
Vertex pointer (that is, in f
), it is offsetting to adj
(in this case, 72 bytes ( 0x48 bytes in decimal )), it's reading near the 0
or null
memory address.
Doing a read like this violates Operating-System protected memory, and more importantly means whatever you're pointing at isn't a valid pointer. Make sure findvertex
isn't returning null, or do a comparisong for null on f
before using it to keep yourself sane (or use an assert):
assert( f != null ); // A good sanity check
EDIT:
If you have a map
for doing something like a find, you can just use the map's find
method to make sure the vertex exists:
Vertex* Graph::findvertex(string s)
{
vmap::iterator itr = map1.find( s );
if ( itr == map1.end() )
{
return NULL;
}
return itr->second;
}
Just make sure you're still careful to handle the error case where it does return NULL
. Otherwise, you'll keep getting this access violation.
If you have fetched, yet this still happens, the following might be a reason.
It can happen that the commit you are trying to pick, is no longer belonging to any branch. This may happen when you rebase.
In such case, at the remote repo:
git checkout xxxxx
git checkout -b temp-branch
Then in your repo, fetch again. The new branch will be fetched, including that commit.
You might need to set permissions at the database level that allows your schema owner to restore the dump.
Perform a composer update
, then composer dump-autoload
.
If the above doesn't solve the problem, change the classmap
in your composer.json
file such that it contains the project-relative path to your php files:
"autoload-dev": {
"classmap": [
"tests/TestCase.php",
"database/seeds/UserTableSeeder.php" //include the file with its path here
]
}, /** ... */
and soon after, perform a composer dump-autoload
, and it should work now like a breeze!
If composer dump-autoload
is not found, just enable this option composer config -g -- disable-tls true
.
Structure types should, whenever practical, either have all of their state encapsulated in public fields which may independently be set to any values which are valid for their respective type, or else behave as a single unified value which can only bet set via constructor, factory, method, or else by passing an instance of the struct as an explicit ref
parameter to one of its public methods. Contrary to what some people claim, that there's nothing wrong with a struct having public fields, if it is supposed to represent a set of values which may sensibly be either manipulated individually or passed around as a group (e.g. the coordinates of a point). Historically, there have been problems with structures that had public property setters, and a desire to avoid public fields (implying that setters should be used instead) has led some people to suggest that mutable structures should be avoided altogether, but fields do not have the problems that properties had. Indeed, an exposed-field struct is the ideal representation for a loose collection of independent variables, since it is just a loose collection of variables.
In your particular example, however, it appears that the two fields of your struct are probably not supposed to be independent. There are three ways your struct could sensibly be designed:
You could have the only public field be the string, and then have a read-only "helper" property called length
which would report its length if the string is non-null, or return zero if the string is null.
You could have the struct not expose any public fields, property setters, or mutating methods, and have the contents of the only field--a private string--be specified in the object's constructor. As above, length
would be a property that would report the length of the stored string.
You could have the struct not expose any public fields, property setters, or mutating methods, and have two private fields: one for the string and one for the length, both of which would be set in a constructor that takes a string, stores it, measures its length, and stores that. Determining the length of a string is sufficiently fast that it probably wouldn't be worthwhile to compute and cache it, but it might be useful to have a structure that combined a string and its GetHashCode
value.
It's important to be aware of a detail with regard to the third design, however: if non-threadsafe code causes one instance of the structure to be read while another thread is writing to it, that may cause the accidental creation of a struct instance whose field values are inconsistent. The resulting behaviors may be a little different from those that occur when classes are used in non-threadsafe fashion. Any code having anything to do with security must be careful not to assume that structure fields will be in a consistent state, since malicious code--even in a "full trust" enviroment--can easily generate structs whose state is inconsistent if that's what it wants to do.
PS -- If you wish to allow your structure to be initialized using an assignment from a string, I would suggest using an implicit conversion operator and making Length
be a read-only property that returns the length of the underlying string if non-null, or zero if the string is null.
I don't know how stubhub's api works, but generally it should look like this:
s = requests.Session()
data = {"login":"my_login", "password":"my_password"}
url = "http://example.net/login"
r = s.post(url, data=data)
Now your session contains cookies provided by login form. To access cookies of this session simply use
s.cookies
Any further actions like another requests will have this cookie
If I have understood it correctly, you are trying to convert a String representing a given date, to another type.
Note: (As @Samson Scharfrichter has mentioned)
There are a few ways to do it. And you are close to the solution. I would use the CAST (which converts to a DATE_TYPE):
SELECT cast('2018-06-05' as date);
Result: 2018-06-05 DATE_TYPE
or (depending on your pattern)
select cast(to_date(from_unixtime(unix_timestamp('05-06-2018', 'dd-MM-yyyy'))) as date)
Result: 2018-06-05 DATE_TYPE
And if you decide to convert ISO8601 to a date type:
select cast(to_date(from_unixtime(unix_timestamp(regexp_replace('2018-06-05T08:02:59Z', 'T',' ')))) as date);
Result: 2018-06-05 DATE_TYPE
Hive has its own functions, I have written some examples for the sake of illustration of these date- and cast- functions:
Date and timestamp functions examples:
Convert String/Timestamp/Date to DATE
SELECT cast(date_format('2018-06-05 15:25:42.23','yyyy-MM-dd') as date); -- 2018-06-05 DATE_TYPE
SELECT cast(date_format(current_date(),'yyyy-MM-dd') as date); -- 2018-06-05 DATE_TYPE
SELECT cast(date_format(current_timestamp(),'yyyy-MM-dd') as date); -- 2018-06-05 DATE_TYPE
Convert String/Timestamp/Date to BIGINT_TYPE
SELECT to_unix_timestamp('2018/06/05 15:25:42.23','yyyy/MM/dd HH:mm:ss'); -- 1528205142 BIGINT_TYPE
SELECT to_unix_timestamp(current_date(),'yyyy/MM/dd HH:mm:ss'); -- 1528205000 BIGINT_TYPE
SELECT to_unix_timestamp(current_timestamp(),'yyyy/MM/dd HH:mm:ss'); -- 1528205142 BIGINT_TYPE
Convert String/Timestamp/Date to STRING
SELECT date_format('2018-06-05 15:25:42.23','yyyy-MM-dd'); -- 2018-06-05 STRING_TYPE
SELECT date_format(current_timestamp(),'yyyy-MM-dd'); -- 2018-06-05 STRING_TYPE
SELECT date_format(current_date(),'yyyy-MM-dd'); -- 2018-06-05 STRING_TYPE
Convert BIGINT unixtime to STRING
SELECT to_date(from_unixtime(unixtime,'yyyy/MM/dd HH:mm:ss')); -- 2018-06-05 STRING_TYPE
Convert String to BIGINT unixtime
SELECT unix_timestamp('2018-06-05 15:25:42.23','yyyy-MM-dd') as TIMESTAMP; -- 1528149600 BIGINT_TYPE
Convert String to TIMESTAMP
SELECT cast(unix_timestamp('2018-06-05 15:25:42.23','yyyy-MM-dd') as TIMESTAMP); -- 1528149600 TIMESTAMP_TYPE
Idempotent (String -> String)
SELECT from_unixtime(to_unix_timestamp('2018/06/05 15:25:42.23','yyyy/MM/dd HH:mm:ss')); -- 2018-06-05 15:25:42 STRING_TYPE
Idempotent (Date -> Date)
SELECT cast(current_date() as date); -- 2018-06-26 DATE_TYPE
Current date / timestamp
SELECT current_date(); -- 2018-06-26 DATE_TYPE
SELECT current_timestamp(); -- 2018-06-26 14:03:38.285 TIMESTAMP_TYPE
Since no one yet mentioned this, in one particular case:
OLD_FILES=`echo *`
... create new files ...
rm -r $OLD_FILES
(or just rm $OLD_FILES
)
or
OLD_FILES=`ls *`
... create new files ...
rm -r $OLD_FILES
You may need to use shopt -s nullglob
if some files may be either there or not there:
SET_OLD_NULLGLOB=`shopt -p nullglob`
shopt -s nullglob
FILES=`echo *.sh *.bash`
$SET_OLD_NULLGLOB
without nullglob, echo *.sh *.bash
may give you "a.sh b.sh *.bash".
(Having said all that, I myself prefer this answer, even though it does not work in OSX)
The #1 reason has already been stated - it hides errors that you did not expect.
(#2) - It makes your code difficult for others to read and understand. If you catch a FileNotFoundException when you are trying to read a file, then it is pretty obvious to another developer what functionality the 'catch' block should have. If you do not specify an exception, then you need additional commenting to explain what the block should do.
(#3) - It demonstrates lazy programming. If you use the generic try/catch, it indicates either that you do not understand the possible run-time errors in your program, or that you do not know what exceptions are possible in Python. Catching a specific error shows that you understand both your program and the range of errors that Python throws. This is more likely to make other developers and code-reviewers trust your work.
how remote is that url ? is it from the same domain ? the code looks okay
try this
$.ajaxSetup({async:false});
$.get(remote_url, function(data) { remote = data; });
// or
remote = $.get(remote_url).responseText;
The FULLY WORKING SOLUTION for both Android
or React-native
users facing this issue just add this
android:usesCleartextTraffic="true"
in AndroidManifest.xml file like this:
android:usesCleartextTraffic="true"
tools:ignore="GoogleAppIndexingWarning">
<uses-library
android:name="org.apache.http.legacy"
android:required="false" />
in between <application>
.. </application>
tag like this:
<application
android:name=".MainApplication"
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
android:allowBackup="false"
android:theme="@style/AppTheme"
android:usesCleartextTraffic="true"
tools:ignore="GoogleAppIndexingWarning">
<uses-library
android:name="org.apache.http.legacy"
android:required="false" />
<activity
android:name=".MainActivity"
android:label="@string/app_name"/>
</application>
you can use
git name-rev --name-only HEAD
git revert HEAD -m 1
In the above code line. "Last argument represents"
or
git reset --hard siriwjdd
The question is LeetCode #148, and there are plenty of solutions offered in all major languages. Mine is as follows, but I'm wondering about the time complexity. In order to find the middle element, we traverse the complete list each time. First time n
elements are iterated over, second time 2 * n/2
elements are iterated over, so on and so forth. It seems to be O(n^2)
time.
def sort(linked_list: LinkedList[int]) -> LinkedList[int]:
# Return n // 2 element
def middle(head: LinkedList[int]) -> LinkedList[int]:
if not head or not head.next:
return head
slow = head
fast = head.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
def merge(head1: LinkedList[int], head2: LinkedList[int]) -> LinkedList[int]:
p1 = head1
p2 = head2
prev = head = None
while p1 and p2:
smaller = p1 if p1.val < p2.val else p2
if not head:
head = smaller
if prev:
prev.next = smaller
prev = smaller
if smaller == p1:
p1 = p1.next
else:
p2 = p2.next
if prev:
prev.next = p1 or p2
else:
head = p1 or p2
return head
def merge_sort(head: LinkedList[int]) -> LinkedList[int]:
if head and head.next:
mid = middle(head)
mid_next = mid.next
# Makes it easier to stop
mid.next = None
return merge(merge_sort(head), merge_sort(mid_next))
else:
return head
return merge_sort(linked_list)
But in my opinion one important thing.
The "char(number)" it's lenght of variable.
If we've got table with "Names" like for example [Test1..Test200] and we declare char(5) in SELECT like:
DECLARE @variable char(5)
SET @variable = 'Test1%'
SELECT * FROM table WHERE Name like @variable
the result will be only - "Test1"! (char(5) - 5 chars in lenght; Test11 is 6 )
The rest of potential interested data like [Test11..Test200] will not be returned in the result.
It's ok if we want to limit the SELECT by this way. But if it's not intentional way of doing it could return incorrect results from planned ( Like "all Names begining with Test1..." ).
In my opinion if we don't know the precise lenght of a SELECTed value, a better solution could be something like this one:
DECLARE @variable varchar(max)
SET @variable = 'Test1%'
SELECT * FROM <table> WHERE variable1 like @variable
This returns (Test1 but also Test11..Test19 and Test100..Test199).
npm set registry http://85.10.209.91/
(this proxy fetches the original data from registry.npmjs.org and manipulates the tarball urls to fix the tarball file structure issue).
The other solutions seem to have outdated versions.
I always had problems with that, and I made a getx.bat script:
:: getx %envvar% [\m]
:: Reads envvar from user environment variable and stores it in the getxvalue variable
:: with \m read system environment
@SETLOCAL EnableDelayedExpansion
@echo OFF
@set l_regpath="HKEY_CURRENT_USER\Environment"
@if "\m"=="%2" set l_regpath="HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
::REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v PATH /t REG_SZ /f /d "%PATH%"
::@REG QUERY %l_regpath% /v %1 /S
@FOR /F "tokens=*" %%A IN ('REG QUERY %l_regpath% /v %1 /S') DO (
@ set l_a=%%A
@ if NOT "!l_a!"=="!l_a: =!" set l_line=!l_a!
)
:: Delimiter is four spaces. Change it to tab \t
@set l_line=!l_line!
@set l_line=%l_line: = %
@set getxvalue=
@FOR /F "tokens=3* delims= " %%A IN ("%l_line%") DO (
@ set getxvalue=%%A
)
@set getxvalue=!getxvalue!
@echo %getxvalue% > getxfile.tmp.txt
@ENDLOCAL
:: We already used tab as a delimiter
@FOR /F "delims= " %%A IN (getxfile.tmp.txt) DO (
@set getxvalue=%%A
)
@del getxfile.tmp.txt
@echo ON
Use the -isEqualToString:
method to compare the value of two strings. Using the C ==
operator will simply compare the addresses of the objects.
if ([category isEqualToString:@"Some String"])
{
// Do stuff...
}
SQL doesn't return any ordering by default because it's faster this way. It doesn't have to go through your data first and then decide what to do.
You need to add an order by clause, and probably order by which ever ID you expect. (There's a duplicate of names, thus I'd assume you want One.ID)
select * From one
inner join two
ON one.one_name = two.one_name
ORDER BY one.ID
Checks for errors:
Dim result As String = str
If str.Length > 5 Then
result = str.Substring(str.Length - 5)
End If
Use "read()" instead o fscanf:
ssize_t read(int fildes, void *buf, size_t nbyte);
DESCRIPTION
The read() function shall attempt to read
nbyte
bytes from the file associated with the open file descriptor,fildes
, into the buffer pointed to bybuf
.
Here is an example:
http://cmagical.blogspot.com/2010/01/c-programming-on-unix-implementing-cat.html
Working part from that example:
f=open(argv[1],O_RDONLY);
while ((n=read(f,l,80)) > 0)
write(1,l,n);
An alternate approach is to use getc
/putc
to read/write 1 char at a time. A lot less efficient. A good example: http://www.eskimo.com/~scs/cclass/notes/sx13.html
I was taking a look at the call logs and I noticed that apart from the usual fields in the contents of managedCursor, we have a column "simid" in Dual SIM phones (I checked on Xolo A500s Lite), so as to tag each call in the call log with a SIM. This value is either 1 or 2, most probably denoting SIM1/SIM2.
managedCursor = context.getContentResolver().query(contacts, null, null, null, null);
managedCursor.moveToNext();
for(int i=0;i<managedCursor.getColumnCount();i++)
{//for dual sim phones
if(managedCursor.getColumnName(i).toLowerCase().equals("simid"))
indexSIMID=i;
}
I did not find this column in a single SIM phone (I checked on Xperia L).
So although I don't think this is a foolproof way to check for dual SIM nature, I am posting it here because it could be useful to someone.
var EM = new events_managment();
EM.addEvent(window, 'resize', function(win,doc, event_){
console.log('resized');
//EM.removeEvent(win,doc, event_);
});
function events_managment(){
this.events = {};
this.addEvent = function(node, event_, func){
if(node.addEventListener){
if(event_ in this.events){
node.addEventListener(event_, function(){
func(node, event_);
this.events[event_](win_doc, event_);
}, true);
}else{
node.addEventListener(event_, function(){
func(node, event_);
}, true);
}
this.events[event_] = func;
}else if(node.attachEvent){
var ie_event = 'on' + event_;
if(ie_event in this.events){
node.attachEvent(ie_event, function(){
func(node, ie_event);
this.events[ie_event]();
});
}else{
node.attachEvent(ie_event, function(){
func(node, ie_event);
});
}
this.events[ie_event] = func;
}
}
this.removeEvent = function(node, event_){
if(node.removeEventListener){
node.removeEventListener(event_, this.events[event_], true);
this.events[event_] = null;
delete this.events[event_];
}else if(node.detachEvent){
node.detachEvent(event_, this.events[event_]);
this.events[event_] = null;
delete this.events[event_];
}
}
}
You can use array_intersect()
.
$result = !empty(array_intersect($people, $criminals));
Bitcode makes crash reporting harder. Here is a quote from HockeyApp (which also true for any other crash reporting solutions):
When uploading an app to the App Store and leaving the "Bitcode" checkbox enabled, Apple will use that Bitcode build and re-compile it on their end before distributing it to devices. This will result in the binary getting a new UUID and there is an option to download a corresponding dSYM through Xcode.
Note: the answer was edited on Jan 2016 to reflect most recent changes
var table = $('#myTableId').DataTable();
var a= [];
$.each(table.rows('.myClassName').data(), function() {
a.push(this["productId"]);
});
console.log(a[0]);
HTML
<div id="mydiv" data-myval="10"></div>
JavaScript:
Using DOM's getAttribute()
property
var brand = mydiv.getAttribute("data-myval")//returns "10"
mydiv.setAttribute("data-myval", "20") //changes "data-myval" to "20"
mydiv.removeAttribute("data-myval") //removes "data-myval" attribute entirely
Using JavaScript's dataset
property
var myval = mydiv.dataset.myval //returns "10"
mydiv.dataset.myval = '20' //changes "data-myval" to "20"
mydiv.dataset.myval = null //removes "data-myval" attribute
Another solution that might work for you is to not declare your toolbar as the app's action bar ( by setActionBar
or setSupportActionBar
) and set the back icon in your onActivityCreated using the code mentioned in another answer on this page
final Drawable upArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
upArrow.setColorFilter(getResources().getColor(R.color.grey), PorterDuff.Mode.SRC_ATOP);
toolbar.setNavigationIcon(upArrow);
Now, you will not get the onOptionItemSelected
callback when you press the back button. However, you can register for that using setNavigationOnClickListener
. This is what i do:
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getActivity().onBackPressed(); //or whatever you used to do on your onOptionItemSelected's android.R.id.home callback
}
});
I'm not sure if it will work if you work with menu items.
Here is the simple explanation of Redux over Flux. Redux does not have a dispatcher.It relies on pure functions called reducers. It does not need a dispatcher. Each actions are handled by one or more reducers to update the single store. Since data is immutable, reducers returns a new updated state that updates the store
For more information Flux vs Redux
First off, (though this won't change the performance at all) consider cleaning up your code, similar to this:
import matplotlib.pyplot as plt
import numpy as np
import time
x = np.arange(0, 2*np.pi, 0.01)
y = np.sin(x)
fig, axes = plt.subplots(nrows=6)
styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-']
lines = [ax.plot(x, y, style)[0] for ax, style in zip(axes, styles)]
fig.show()
tstart = time.time()
for i in xrange(1, 20):
for j, line in enumerate(lines, start=1):
line.set_ydata(np.sin(j*x + i/10.0))
fig.canvas.draw()
print 'FPS:' , 20/(time.time()-tstart)
With the above example, I get around 10fps.
Just a quick note, depending on your exact use case, matplotlib may not be a great choice. It's oriented towards publication-quality figures, not real-time display.
However, there are a lot of things you can do to speed this example up.
There are two main reasons why this is as slow as it is.
1) Calling fig.canvas.draw()
redraws everything. It's your bottleneck. In your case, you don't need to re-draw things like the axes boundaries, tick labels, etc.
2) In your case, there are a lot of subplots with a lot of tick labels. These take a long time to draw.
Both these can be fixed by using blitting.
To do blitting efficiently, you'll have to use backend-specific code. In practice, if you're really worried about smooth animations, you're usually embedding matplotlib plots in some sort of gui toolkit, anyway, so this isn't much of an issue.
However, without knowing a bit more about what you're doing, I can't help you there.
Nonetheless, there is a gui-neutral way of doing it that is still reasonably fast.
import matplotlib.pyplot as plt
import numpy as np
import time
x = np.arange(0, 2*np.pi, 0.1)
y = np.sin(x)
fig, axes = plt.subplots(nrows=6)
fig.show()
# We need to draw the canvas before we start animating...
fig.canvas.draw()
styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-']
def plot(ax, style):
return ax.plot(x, y, style, animated=True)[0]
lines = [plot(ax, style) for ax, style in zip(axes, styles)]
# Let's capture the background of the figure
backgrounds = [fig.canvas.copy_from_bbox(ax.bbox) for ax in axes]
tstart = time.time()
for i in xrange(1, 2000):
items = enumerate(zip(lines, axes, backgrounds), start=1)
for j, (line, ax, background) in items:
fig.canvas.restore_region(background)
line.set_ydata(np.sin(j*x + i/10.0))
ax.draw_artist(line)
fig.canvas.blit(ax.bbox)
print 'FPS:' , 2000/(time.time()-tstart)
This gives me ~200fps.
To make this a bit more convenient, there's an animations
module in recent versions of matplotlib.
As an example:
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
x = np.arange(0, 2*np.pi, 0.1)
y = np.sin(x)
fig, axes = plt.subplots(nrows=6)
styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-']
def plot(ax, style):
return ax.plot(x, y, style, animated=True)[0]
lines = [plot(ax, style) for ax, style in zip(axes, styles)]
def animate(i):
for j, line in enumerate(lines, start=1):
line.set_ydata(np.sin(j*x + i/10.0))
return lines
# We'd normally specify a reasonable "interval" here...
ani = animation.FuncAnimation(fig, animate, xrange(1, 200),
interval=0, blit=True)
plt.show()
I strongly recommend you to use virtual environments for python package installation. With virtualenv, you prevent any package conflict and total isolation from your python related userland commands.
To delete all your package follow this;
It's possible to uninstall packages installed with --user
flag. This one worked for me;
pip freeze --user | xargs pip uninstall -y
For python 3;
pip3 freeze --user | xargs pip3 uninstall -y
But somehow these commands don't uninstall setuptools and pip. After those commands (if you really want clean python) you may delete them with;
pip uninstall setuptools && pip uninstall pip
To achieve this functionality you could use ncurses library which was implemented both on Windows and Linux (and MacOS as far as I know).
ALTER TABLE tableName MODIFY tableNameID MEDIUMINT NOT NULL AUTO_INCREMENT;
Here tableName is name of your table,
tableName is your column name which is primary has to be modified
MEDIUMINT is a data type of your existing primary key
AUTO_INCREMENT you have to add just auto_increment after not null
It will make that primary key auto_increment......
Hope this is helpful:)
There is no need to use :checkbox
, also replace #activelist
with #inactivelist
:
$('#inactivelist').change(function () {
alert('changed');
});
You can use the Eclipse Indigo EE version for Android development. It is quite good, and I haven't faced any issues so far.
You can also do this -
var handle = Activator.CreateInstance("AssemblyName",
"Full name of the class including the namespace and class name");
var obj = handle.Unwrap();
Try to modify the eclipse.ini
so that both Xms
and Xmx
are of the same value:
-Xms6000m
-Xmx6000m
This should force the Eclipse's VM to allocate 6GB
of heap right from the beginning.
But be careful about either using the eclipse.ini
or the command-line ./eclipse/eclipse -vmargs ...
. It should work in both cases but pick one and try to stick with it.
Using CliWrap:
var result = await Cli.Wrap("foobar.bat").ExecuteBufferedAsync();
var exitCode = result.ExitCode;
var stdOut = result.StandardOutput;
before you send the email you can press <ESC> f
(Escape followed by f) to change the From:
Address.
Constraint: This only works if you use mutt in curses mode and do not wan't to script it or if you want to change the address permanent. Then the other solutions are way better!
@Future-searchers: you can use aspell to do the dictionary checks, it has bindings in ruby and python. It would make your job much simpler.
Came here with the additional requirement, that also parameter/return types should vary. Following Ben Supnik this would be for some type T
typedef T(*binary_T_op)(T, T);
instead of
typedef int(*binary_int_op)(int, int);
The solution here is to put the function type definition and the function template into a surrounding struct template.
template <typename T> struct BinOp
{
typedef T(*binary_T_op )(T, T); // signature for all valid template params
template<binary_T_op op>
T do_op(T a, T b)
{
return op(a,b);
}
};
double mulDouble(double a, double b)
{
return a * b;
}
BinOp<double> doubleBinOp;
double res = doubleBinOp.do_op<&mulDouble>(4, 5);
Alternatively BinOp could be a class with static method template do_op(...), then called as
double res = BinOp<double>::do_op<&mulDouble>(4, 5);
@echo off
for /f "usebackq tokens=*" %%x in (`chdir`) do set var=%%x
echo The currenct directory is: %var%
But, of course, gmaran23's answer is the much easier one.
This presents a bit of a usability issue.
If you want to display a checkbox, but not let it be interacted with, why even a checkbox then?
However, my approach would be to use disabled (The user expects a disabled checkbox to not be editable, instead of using JS to make an enabled one not work), and add a form submit handler using javascript that enables checkboxes right before the form is submitted. This way you you do get your values posted.
ie something like this:
var form = document.getElementById('yourform');
form.onSubmit = function ()
{
var formElems = document.getElementsByTagName('INPUT');
for (var i = 0; i , formElems.length; i++)
{
if (formElems[i].type == 'checkbox')
{
formElems[i].disabled = false;
}
}
}
01. Open the page for which you want to get the information.
02. Clear the address bar [where you type the address of the sites]:
and type or copy/paste from below:
javascript:alert(document.lastModified)
03. Press Enter or Go button.
The colors changed due to the order of CSS files.
Place the custom CSS under the bootstrap CSS.
You can override the onDraw method of your view and draw the circle.
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawCircle(x, y, radius, paint);
}
For a better reference on drawing custom views check out the official Android documentation.
http://developer.android.com/training/custom-views/custom-drawing.html
This is the answer, hope it helps someone :)
First there are two variations on how the xml can be written:
<row>
<IdInvernadero>8</IdInvernadero>
<IdProducto>3</IdProducto>
<IdCaracteristica1>8</IdCaracteristica1>
<IdCaracteristica2>8</IdCaracteristica2>
<Cantidad>25</Cantidad>
<Folio>4568457</Folio>
</row>
<row>
<IdInvernadero>3</IdInvernadero>
<IdProducto>3</IdProducto>
<IdCaracteristica1>1</IdCaracteristica1>
<IdCaracteristica2>2</IdCaracteristica2>
<Cantidad>72</Cantidad>
<Folio>4568457</Folio>
</row>
Answer:
SELECT
Tbl.Col.value('IdInvernadero[1]', 'smallint'),
Tbl.Col.value('IdProducto[1]', 'smallint'),
Tbl.Col.value('IdCaracteristica1[1]', 'smallint'),
Tbl.Col.value('IdCaracteristica2[1]', 'smallint'),
Tbl.Col.value('Cantidad[1]', 'int'),
Tbl.Col.value('Folio[1]', 'varchar(7)')
FROM @xml.nodes('//row') Tbl(Col)
<row IdInvernadero="8" IdProducto="3" IdCaracteristica1="8" IdCaracteristica2="8" Cantidad ="25" Folio="4568457" />
<row IdInvernadero="3" IdProducto="3" IdCaracteristica1="1" IdCaracteristica2="2" Cantidad ="72" Folio="4568457" />
Answer:
SELECT
Tbl.Col.value('@IdInvernadero', 'smallint'),
Tbl.Col.value('@IdProducto', 'smallint'),
Tbl.Col.value('@IdCaracteristica1', 'smallint'),
Tbl.Col.value('@IdCaracteristica2', 'smallint'),
Tbl.Col.value('@Cantidad', 'int'),
Tbl.Col.value('@Folio', 'varchar(7)')
FROM @xml.nodes('//row') Tbl(Col)
Taken from:
Though nearly the same as most of the other responses, I think this is the most efficient and concise way to implement it. Using TryGetValue is faster than using ContainsKey and reindexing into the dictionary as some other solutions have shown.
void Add(string key, string val)
{
List<string> list;
if (!dictionary.TryGetValue(someKey, out list))
{
values = new List<string>();
dictionary.Add(key, list);
}
list.Add(val);
}
You can try this. its working for me 'name' is a property in arr.
repeat="item in (tagWordOptions | filter:{ name: $select.search } ) track by $index
I have encountered the same error while trying to execute a script file created in windows OS using textpad. so that one can select proper file format like unix/mac etc.. or recreate the script in linux iteself.
You can also get a quick list of changed files if thats all you're looking for using the status command with the -u option
svn status -u
This will show you what revision the file is in the current code base versus the latest revision in the repository. I only use diff when I actually want to see differences in the files themselves.
There is a good tutorial on svn command here that explains a lot of these common scenarios: SVN Command Reference
php artisan config:clear
(NOT cache)
This answer is more like an addition and a slight modification to the answers above.
In some versions of Visual Studio (and possibly other compilers) there is a bug that is really annoying and doesn't make sense. So if you declare/define your swap
function like this:
friend void swap(A& first, A& second) {
std::swap(first.size, second.size);
std::swap(first.arr, second.arr);
}
... the compiler will yell at you when you call the swap
function:
This has something to do with a friend
function being called and this
object being passed as a parameter.
A way around this is to not use friend
keyword and redefine the swap
function:
void swap(A& other) {
std::swap(size, other.size);
std::swap(arr, other.arr);
}
This time, you can just call swap
and pass in other
, thus making the compiler happy:
After all, you don't need to use a friend
function to swap 2 objects. It makes just as much sense to make swap
a member function that has one other
object as a parameter.
You already have access to this
object, so passing it in as a parameter is technically redundant.
Yes, on the server side $_SERVER['DOCUMENT_ROOT']
is equivalent to /
on the client side.
For example: the value of "{$_SERVER['DOCUMENT_ROOT']}/images/thumbnail.png"
will be the string /var/www/html/images/thumbnail.png
on a server where it's local file at that path can be reached from the client side at the url http://example.com/images/thumbnail.png
No, in other words the value of $_SERVER['DOCUMENT_ROOT']
is not /
rather it is the server's local path to what the server shows the client at example.com/
note: $_SERVER['DOCUMENT_ROOT']
does not include a trailing /
Try this Demo
HTML
<table>
<tr>
<td>One</td>
<td>Two</td>
<td>Three</td>
<td>Four</td>
</tr>
</table>
CSS
td:nth-of-type(2) {
padding-right: 10px;
}
please, be sure your connected to a ubuntu server, I Had the same problem but I was connected to other distro, check the AMI value in your details instance, it should be something like
AMI: ubuntu/images/ebs/ubuntu-precise-12.04-amd64-server-20130411.1
hope it helps
This functionality just what you need. http://docs.angularjs.org/api/ng.directive:input.number
EDIT:
You can wrap the jquery plugin into directive. I created an example here: http://jsfiddle.net/anazimok/jTJCF/
HTML:
<div ng-app="myApp">
<div>
<input type="text" min="0" max="99" number-mask="" ng-model="message">
<button ng-click="handleClick()">Broadcast</button>
</div>
</div>
CSS:
.ng-invalid {
border: 1px solid red;
}
JS:
// declare a module
var app = angular.module('myApp', []);
app.directive('numberMask', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
$(element).numeric();
}
}
});
I investigated this a bit since I have the same Issue. What I did not like about the previous solutions was, that the autocomplete already fired the AutocompleteService to show the predictions. Therefore, the predictions should be somewhere and should not be loaded again.
I found out that the predictions of place inkl. place_id is stored in
Autocomplete.gm_accessors_.place.Kc.l
and you will be able to get a lot of data from the records [0].data
. Imho, it's faster and better to get the location by using the place_id instead of address data. This very strange object selection appears not very good to me, tho.
Do you know, if there is a better way to retrieve the first prediction from the autocomplete?
Your resource methods won't get hit, so their headers will never get set. The reason is that there is what's called a preflight request before the actual request, which is an OPTIONS
request. So the error comes from the fact that the preflight request doesn't produce the necessary headers.
For RESTeasy, you should use CorsFilter
. You can see here for some example how to configure it. This filter will handle the preflight request. So you can remove all those headers you have in your resource methods.
See Also:
If using a StackTraceElement, use:
String fullClassName = stackTraceElement.getClassName();
String simpleClassName = fullClassName.substring(fullClassName.lastIndexOf('.') + 1);
System.out.println(simpleClassName);
is this use of typedef super common/rare/never seen in the code you work with?
I have never seen this particular pattern in the C++ code I work with, but that doesn't mean it's not out there.
is this use of typedef super Ok (i.e. do you see strong or not so strong reasons to not use it)?
It doesn't allow for multiple inheritance (cleanly, anyway).
should "super" be a good thing, should it be somewhat standardized in C++, or is this use through a typedef enough already?
For the above cited reason (multiple inheritance), no. The reason why you see "super" in the other languages you listed is that they only support single inheritance, so there is no confusion as to what "super" is referring to. Granted, in those languages it IS useful but it doesn't really have a place in the C++ data model.
Oh, and FYI: C++/CLI supports this concept in the form of the "__super" keyword. Please note, though, that C++/CLI doesn't support multiple inheritance either.
For Python 3
sudo apt-get install python3-pip
sudo pip3 install beautifulsoup4
For Python 2
sudo apt-get install python2-pip
sudo pip2 install beautifulsoup4
On Debian/Ubuntu,
pip
is the command to use when installing packages for Python 2, whilepip3
is the command to use when installing packages for Python 3.
Don't have sql server around to test but I think it's just:
insert into newtable select * from oldtable;
You haven't mentioned a language, so I'm going to give you some some hints how to do it with the straight Windows API in C.
First, open a connection to the printer with OpenPrinter
. Next, start a document with StartDocPrinter
having the pDatatype
field of the DOC_INFO_1
structure set to "RAW"
- this tells the printer driver not to encode anything going to the printer, but to pass it along unchanged. Use StartPagePrinter
to indicate the first page, WritePrinter
to send the data to the printer, and close it with EndPagePrinter
, EndDocPrinter
and ClosePrinter
when done.
As per Google recent announcement, usage of the Google Maps APIs now requires a key. If you are using the Google Maps API on localhost or your domain was not active prior to June 22nd, 2016, it will require a key going forward. Please see the Google Maps APIs documentation to get a key and add it to your application.
the problem with datagridview is that it select the first row automatically so you want to clear the selection by
grvPackingList.ClearSelection();
dataGridView1.Rows[rowindex].Cells[columnindex].Selected = true;
other wise it will not work
To compare two git commits 12345 and abcdef as patches one can use the diff command as
diff <(git show 123456) <(git show abcdef)
Your local branch likely has modifications to it you want to discard. To do this, you'll need to use git reset
to reset the branch head to the last spot that you diverged from the upstream repo's branch. Use git branch -v
to find the sha1 id of the upstream branch, and reset your branch it it using git reset SHA1ID
. Then you should be able to do a git checkout
to discard the changes it left in your directory.
Note: always do this on a backed-up repo. That way you can assure you're self it worked right. Or if it didn't, you have a backup to revert to.
CoundDownLatch enables you to make a thread wait till all other threads are done with their execution.
Pseudo code can be:
// Main thread starts
// Create CountDownLatch for N threads
// Create and start N threads
// Main thread waits on latch
// N threads completes there tasks are returns
// Main thread resume execution
After trying some of the answers in this post, I consulted with Louie Mantia (former Apple, Square, and Iconfactory designer) and all the answers so far on this post are wrong (or at least incomplete). Apple starts with the 57px icon and a radius of 10 then scales up or down from there. Thus you can calculate the radius for any icon size using 10/57 x new size
(for example 10/57 x 114
gives 20, which is the proper radius for a 114px icon). Here is a list of the most commonly used icons, proper naming conventions, pixel dimensions, and corner radii.
Also, as mentioned in other answers, you don't actually want to crop any of the images you use in the binary or submit to Apple. Those should all be square and not have any transparency. Apple will automatically mask each icon in the appropriate context.
Knowing the above is important, however, for icon usage within app UI where you have to apply the mask in code, or pre-rendered in photoshop. It's also helpful when creating artwork for websites and other promotional material.
Additional reading:
Neven Mrgan on additional icon sizes and other design considerations: ios app icon sizes
Bjango's Marc Edwards on the different options for creating roundrects in Photoshop and why it matters: roundrect
Apple's official docs on icon size and design considerations: Icons and Images
Update:
I did some tests in Photoshop CS6 and it seems as though 3 digits after the decimal point is enough precision to end up with the exact same vector (at least as displayed by Photoshop at 3200% zoom). The Round Rect Tool sometimes rounds the input to the nearest whole number, but you can see a significant difference between 90 and 89.825. And several times the Round Rectangle Tool didn't round up and actually showed multiple digits after the decimal point. Not sure what's going on there, but it's definitely using and storing the more precise number that was entered.
Anyhow, I've updated the list above to include just 3 digits after the decimal point (before there were 13!). In most situations it would probably be hard to tell the difference between a transparent 512px icon masked at a 90px radius and one masked at 89.825, but the antialiasing of the rounded corner would definitely end up slightly different and would likely be visible in certain circumstances especially if a second, more precise mask is applied by Apple, in code, or otherwise.
You can invoke a PHP script manually from the command line
hello.php
<?php
echo 'hello world!';
?>
Command line:
php hello.php
Output:
hello world!
See the documentation: http://php.net/manual/en/features.commandline.php
EDIT OP edited the question to add a critical detail: the script is to be executed by another script.
There are a couple of approaches. First and easiest, you could simply include the file. When you include a file, the code within is "executed" (actually, interpreted). Any code that is not within a function or class body will be processed immediately. Take a look at the documentation for include
(docs) and/or require
(docs) (note: include_once
and require_once
are related, but different in an important way. Check out the documents to understand the difference) Your code would look like this:
include('hello.php');
/* output
hello world!
*/
Second and slightly more complex is to use shell_exec
(docs). With shell_exec
, you will call the php binary and pass the desired script as the argument. Your code would look like this:
$output = shell_exec('php hello.php');
echo "<pre>$output</pre>";
/* output
hello world!
*/
Finally, and most complex, you could use the CURL library to call the file as though it were requested via a browser. Check out the CURL library documentation here: http://us2.php.net/manual/en/ref.curl.php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.myDomain.com/hello.php");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true)
$output = curl_exec($ch);
curl_close($ch);
echo "<pre>$output</pre>";
/* output
hello world!
*/
Documentation for functions used
include
: http://us2.php.net/manual/en/function.include.phprequire
: http://us2.php.net/manual/en/function.require.phpshell_exec
: http://us2.php.net/manual/en/function.shell-exec.phpcurl_init
: http://us2.php.net/manual/en/function.curl-init.phpcurl_setopt
: http://us2.php.net/manual/en/function.curl-setopt.phpcurl_exec
: http://us2.php.net/manual/en/function.curl-exec.phpcurl_close
: http://us2.php.net/manual/en/function.curl-close.phpJust pointing out that the Java Validation API (javax.validation.constraints.*
) doesn't come with a @Nullable
annotation, which is very valuable in a static analysis context. It makes sense for runtime bean validation as this is the default for any non-primitive field in Java (i.e. nothing to validate/enforce). For the purposes stated that should weigh towards the alternatives.
public static boolean isPalindrome(int x) {
int newX = x;
int newNum = 0;
boolean result = false;
if (x >= 0) {
while (newX >= 10) {
newNum = newNum+newX % 10;
newNum = newNum * 10;
newX = newX / 10;
}
newNum += newX;
if(newNum==x) {
result = true;
}
else {
result=false;
}
}
else {
result = false;
}
return result;
}
You must use a .ts
file - e.g. test.ts
to get Typescript validation, intellisense typing
of vars, return types, as well as "typed" error checking (e.g. passing a string
to a method that expects an number
param will error out).
It will be transpiled into (standard) .js
via tsc
.
Clarification needed based on down-votes, very helpful comments and other answers.
types
Yes, you can do type
checking in VS Code in .js
files with @ts-check
- as shown in the animation
What I originally was referring to for Typescript types
is something like this in .ts
which isn't quite the same thing:
hello-world.ts
function hello(str: string): string {
return 1;
}
function foo(str:string):void{
console.log(str);
}
This will not compile. Error: Type "1" is not assignable to String
if you tried this syntax in a Javascript hello-world.js
file:
//@ts-check
function hello(str: string): string {
return 1;
}
function foo(str:string):void{
console.log(str);
}
The error message referenced by OP is shown: [js] 'types' can only be used in a .ts file
If there's something I missed that covers this as well as the OP's context, please add. Let's all learn.
But always look out in the console / log for messages. If you see a notification that your query could not be converted to SQL and will be evaluated locally then you may need to rewrite it.
Entity Framework 7 (now renamed to Entity Framework Core 1.0 / 2.0) does not yet support GroupBy()
for translation to GROUP BY
in generated SQL (even in the final 1.0 release it won't). Any grouping logic will run on the client side, which could cause a lot of data to be loaded.
Eventually code written like this will automagically start using GROUP BY, but for now you need to be very cautious if loading your whole un-grouped dataset into memory will cause performance issues.
For scenarios where this is a deal-breaker you will have to write the SQL by hand and execute it through EF.
If in doubt fire up Sql Profiler and see what is generated - which you should probably be doing anyway.
https://blogs.msdn.microsoft.com/dotnet/2016/05/16/announcing-entity-framework-core-rc2
This has been here quite a while but posting this. Might be useful for someone.
@RequestMapping( "/{id}/**" )
public void foo( @PathVariable String id, HttpServletRequest request ) {
String urlTail = new AntPathMatcher()
.extractPathWithinPattern( "/{id}/**", request.getRequestURI() );
}
To contribute my 5 cents to the thorough explanation from Amadan.
Where classes are a description "of a type" in an abstract way. Objects are their realizations: the living breathing thing. In the object-orientated world there are principal ideas you can almost call the essence of everything. They are:
Objects have one, or more characteristics (= Attributes) and behaviors (= Methods). The behavior mostly depends on the characteristics. Classes define what the behavior should accomplish in a general way, but as long as the class is not realized (instantiated) as an object it remains an abstract concept of a possibility. Let me illustrate with the help of "inheritance" and "polymorphism".
class Human:
gender
nationality
favorite_drink
core_characteristic
favorite_beverage
name
age
def love
def drink
def laugh
def do_your_special_thing
class Americans(Humans)
def drink(beverage):
if beverage != favorite_drink: print "You call that a drink?"
else: print "Great!"
class French(Humans)
def drink(beverage, cheese):
if beverage == favourite_drink and cheese == None: print "No cheese?"
elif beverage != favourite_drink and cheese == None: print "Révolution!"
class Brazilian(Humans)
def do_your_special_thing
win_every_football_world_cup()
class Germans(Humans)
def drink(beverage):
if favorite_drink != beverage: print "I need more beer"
else: print "Lecker!"
class HighSchoolStudent(Americans):
def __init__(self, name, age):
self.name = name
self.age = age
jeff = HighSchoolStudent(name, age):
hans = Germans()
ronaldo = Brazilian()
amelie = French()
for friends in [jeff, hans, ronaldo]:
friends.laugh()
friends.drink("cola")
friends.do_your_special_thing()
print amelie.love(jeff)
>>> True
print ronaldo.love(hans)
>>> False
Some characteristics define human beings. But every nationality differs somewhat. So "national-types" are kinda Humans with extras. "Americans" are a type of "Humans " and inherit some abstract characteristics and behavior from the human type (base-class) : that's inheritance. So all Humans can laugh and drink, therefore all child-classes can also! Inheritance (2).
But because they are all of the same kind (Type/base-class : Humans) you can exchange them sometimes: see the for-loop at the end. But they will expose an individual characteristic, and thats Polymorphism (3).
So each human has a favorite_drink, but every nationality tend towards a special kind of drink.
If you subclass a nationality from the type of Humans you can overwrite the inherited behavior as I have demonstrated above with the drink()
Method.
But that's still at the class-level and because of this it's still a generalization.
hans = German(favorite_drink = "Cola")
instantiates the class German and I "changed" a default characteristic at the beginning. (But if you call hans.drink('Milk') he would still print "I need more beer" - an obvious bug ... or maybe that's what i would call a feature if i would be a Employee of a bigger Company. ;-)! )
The characteristic of a type e.g. Germans (hans) are usually defined through the constructor (in python : __init__
) at the moment of the instantiation. This is the point where you define a class to become an object. You could say breath life into an abstract concept (class) by filling it with individual characteristics and becoming an object.
But because every object is an instance of a class they share all some basic characteristic-types and some behavior. This is a major advantage of the object-orientated concept.
To protect the characteristics of each object you encapsulate them - means you try to couple behavior and characteristic and make it hard to manipulate it from outside the object. That's Encapsulation (1)
The code below will do the trick.
$('input[type=radio]').click(function() {_x000D_
if($(this).hasClass("checked")){_x000D_
this.checked = false;_x000D_
$(this).removeClass("checked")_x000D_
}else{_x000D_
$(this).addClass("checked")_x000D_
}_x000D_
});
_x000D_
A simple solution for the situation is:
$(document).mouseup(function (e)
{
var container = $("YOUR SELECTOR"); // Give you class or ID
if (!container.is(e.target) && // If the target of the click is not the desired div or section
container.has(e.target).length === 0) // ... nor a descendant-child of the container
{
container.hide();
}
});
The above script will hide the div
if outside of the div
click event is triggered.
You can see the following blog for more information : http://www.codecanal.com/detect-click-outside-div-using-javascript/
current working directory variable ie full path /home/dev/other
dir=$PWD
print the full path
echo $dir
You could do, assuming you have an array with value and array length: arrayVal[i]
, arrayLength
:
int sum = 0;
for (int i = 0; i < arrayLength; i++) {
sum += arrayVal[i];
}
System.out.println("the sum is" + sum);
I hope this helps.
I don't think you can call
$.attr('checked',true);
because there is no element selector in the first place. $ must be followed by $('selector_name'). GOod luck!
simply use find tool.
find absolute_path
displays full paths on my Linux machine, while
find relative_path
will not.
When you want a relative path from your home directory (on any UNIX) you use this strange syntax:
ssh://[user@]host.xz[:port]/~[user]/path/to/repo
For Example, if the repo is in /home/jack/projects/jillweb
on the server jill.com
and you are logging in as jack
with sshd
listening on port 4242:
ssh://[email protected]:4242/~/projects/jillweb
And when logging in as jill
(presuming you have file permissions):
ssh://[email protected]:4242/~jack/projects/jillweb
One option is to use an attribute on the image, and modify that using jQuery. Then take that value in CSS:
HTML (note I'm assuming .cloumn
is a div
but it could be anything):
<div class="column" bf-width=100 >
<img src="..." />
</div>
jQuery:
// General use:
$('.column').attr('bf-width', 100);
// With your image, along the lines of:
$('.column').attr('bf-width', $('img').width());
And then in order to use that value in CSS:
.column:before {
content: attr(data-content) 'px';
/* ... */
}
This will grab the attribute value from .column
, and apply it on the before.
Sources: CSS attr (note the examples with before), jQuery attr.
There is exactly one reason why the following is preferred:
with open('filename.txt') as fp:
for line in fp:
print line
We are all spoiled by CPython's relatively deterministic reference-counting scheme for garbage collection. Other, hypothetical implementations of Python will not necessarily close the file "quickly enough" without the with
block if they use some other scheme to reclaim memory.
In such an implementation, you might get a "too many files open" error from the OS if your code opens files faster than the garbage collector calls finalizers on orphaned file handles. The usual workaround is to trigger the GC immediately, but this is a nasty hack and it has to be done by every function that could encounter the error, including those in libraries. What a nightmare.
Or you could just use the with
block.
(Stop reading now if are only interested in the objective aspects of the question.)
Why isn't that included in the iterator protocol for file objects?
This is a subjective question about API design, so I have a subjective answer in two parts.
On a gut level, this feels wrong, because it makes iterator protocol do two separate things—iterate over lines and close the file handle—and it's often a bad idea to make a simple-looking function do two actions. In this case, it feels especially bad because iterators relate in a quasi-functional, value-based way to the contents of a file, but managing file handles is a completely separate task. Squashing both, invisibly, into one action, is surprising to humans who read the code and makes it more difficult to reason about program behavior.
Other languages have essentially come to the same conclusion. Haskell briefly flirted with so-called "lazy IO" which allows you to iterate over a file and have it automatically closed when you get to the end of the stream, but it's almost universally discouraged to use lazy IO in Haskell these days, and Haskell users have mostly moved to more explicit resource management like Conduit which behaves more like the with
block in Python.
On a technical level, there are some things you may want to do with a file handle in Python which would not work as well if iteration closed the file handle. For example, suppose I need to iterate over the file twice:
with open('filename.txt') as fp:
for line in fp:
...
fp.seek(0)
for line in fp:
...
While this is a less common use case, consider the fact that I might have just added the three lines of code at the bottom to an existing code base which originally had the top three lines. If iteration closed the file, I wouldn't be able to do that. So keeping iteration and resource management separate makes it easier to compose chunks of code into a larger, working Python program.
Composability is one of the most important usability features of a language or API.
At the bottom, I have a general solution to replace lines in a file. But first, here is the answer to the specific question at hand. Helper function:
public static void replaceSelected(String replaceWith, String type) {
try {
// input the file content to the StringBuffer "input"
BufferedReader file = new BufferedReader(new FileReader("notes.txt"));
StringBuffer inputBuffer = new StringBuffer();
String line;
while ((line = file.readLine()) != null) {
inputBuffer.append(line);
inputBuffer.append('\n');
}
file.close();
String inputStr = inputBuffer.toString();
System.out.println(inputStr); // display the original file for debugging
// logic to replace lines in the string (could use regex here to be generic)
if (type.equals("0")) {
inputStr = inputStr.replace(replaceWith + "1", replaceWith + "0");
} else if (type.equals("1")) {
inputStr = inputStr.replace(replaceWith + "0", replaceWith + "1");
}
// display the new file for debugging
System.out.println("----------------------------------\n" + inputStr);
// write the new string with the replaced line OVER the same file
FileOutputStream fileOut = new FileOutputStream("notes.txt");
fileOut.write(inputStr.getBytes());
fileOut.close();
} catch (Exception e) {
System.out.println("Problem reading file.");
}
}
Then call it:
public static void main(String[] args) {
replaceSelected("Do the dishes", "1");
}
Original Text File Content:
Do the dishes0
Feed the dog0
Cleaned my room1
Output:
Do the dishes0
Feed the dog0
Cleaned my room1
----------------------------------
Do the dishes1
Feed the dog0
Cleaned my room1
New text file content:
Do the dishes1
Feed the dog0
Cleaned my room1
And as a note, if the text file was:
Do the dishes1
Feed the dog0
Cleaned my room1
and you used the method replaceSelected("Do the dishes", "1");
,
it would just not change the file.
Since this question is pretty specific, I'll add a more general solution here for future readers (based on the title).
// read file one line at a time
// replace line as you read the file and store updated lines in StringBuffer
// overwrite the file with the new lines
public static void replaceLines() {
try {
// input the (modified) file content to the StringBuffer "input"
BufferedReader file = new BufferedReader(new FileReader("notes.txt"));
StringBuffer inputBuffer = new StringBuffer();
String line;
while ((line = file.readLine()) != null) {
line = ... // replace the line here
inputBuffer.append(line);
inputBuffer.append('\n');
}
file.close();
// write the new string with the replaced line OVER the same file
FileOutputStream fileOut = new FileOutputStream("notes.txt");
fileOut.write(inputBuffer.toString().getBytes());
fileOut.close();
} catch (Exception e) {
System.out.println("Problem reading file.");
}
}
Looks like you need the package from the installation media if you're you're offline (located at D:\sources\sxs
) You could copy this to each machine that you require .NET 3.5 on (so technically you only need the installation media once to get the package) and get each machine to run the command:
Dism.exe /online /enable-feature /featurename:NetFX3 /All /Source:c:\dotnet35 /LimitAccess
There's a guide on MSDN.
Not mentionned here so far, but this can come also from stash. We encountered the same issue, the root cause for our problem was that the stash instance we use for jenkins did crash. Restarting stash solved it in our case.
First you need to create the config file, using cmd :
jupyter notebook --generate-config
Then, search for C:\Users\your_username\.jupyter folder (Search for that folder), and right click edit the jupyter_notebook_config.py.
Then, Ctrl+F: #c.NotebookApp.notebook_dir ='' . Note that the quotes are single quotes. Select your directory you want to have as home for your jupyter, and copy it with Ctrl+C, for example: C:\Users\username\Python Projects.
Then on that line, paste it like this : c.NotebookApp.notebook_dir = 'C:\\Users\\username\\Python Projects'
Make sure to remove #, as it is as comment.
Make sure to double slash \\ on each name of your path. Ctrl+S to save the config.py file !!!
Go back to your cmd and run jupyter notebook.
It should be in your directory of choice. Test it by making a folder and watch your directory from your computer.
1 check current limit:
(in my os)php -i | grep limit => memory_limit => 256M => 256M
2 locate php.ini
php --ini =>
Configuration File (php.ini) Path: /etc
Loaded Configuration File: /etc/php.ini
Scan for additional .ini files in: /etc/php.d
Additional .ini files parsed: /etc/php.d/curl.ini
...
3 change memory_limit in php.ini
vi /etc/php.ini
memory_limit = 512M
4 restart nginx and (php-fpm if being used)
service php-fpm restart
service nginx restart
if you are writing styles in styles.xml then
remove android:inputType property and add below lines
<item name="android:capitalize">words</item>
Most suggestions will fail if there so much as a single leading or trailing space, which would matter if the file is being edited by hand. This would make it less susceptible in that case:
grep '^[[:blank:]]*ABB\.log[[:blank:]]*$' a.tmp
A simple while-read loop in shell would do this implicitly:
while read file
do
case $file in
(ABB.log) printf "%s\n" "$file"
esac
done < a.tmp
Android provides a couple of different library sets. One is called the Android support Library, and the other is called AndroidX. Selecting "Use android.* artifacts" indicates that we want to use AndroidX.
There are many answers, but none that mentions Object.create from ECMAScript 5, which admittedly does not give you an exact copy, but sets the source as the prototype of the new object.
Thus, this is not an exact answer to the question, but it is a one-line solution and thus elegant. And it works best for 2 cases:
Example:
var foo = { a : 1 };
var bar = Object.create(foo);
foo.a; // 1
bar.a; // 1
foo.a = 2;
bar.a; // 2 - prototype changed
bar.a = 3;
foo.a; // Still 2, since setting bar.a makes it an "own" property
Why do I consider this solution to be superior? It's native, thus no looping, no recursion. However, older browsers will need a polyfill.
That is an object, not an array. So you would do:
var json = { cool: 34.33, alsocool: 45454 };
json.supercool = 3.14159;
console.dir(json);
I'm able to run an SQL query by piping it to SQL*Plus:
@echo select count(*) from table; | sqlplus username/password@database
Give
@echo execute some_procedure | sqlplus username/password@databasename
a try.
This question already has a great answer, but I ran into the same error, in a different scenario: displaying a List
in an EditorTemplate.
I have a model like this:
public class Foo
{
public string FooName { get; set; }
public List<Bar> Bars { get; set; }
}
public class Bar
{
public string BarName { get; set; }
}
And this is my main view:
@model Foo
@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
@Html.EditorFor(m => m.Bars)
And this is my Bar EditorTemplate (Bar.cshtml)
@model List<Bar>
<div class="some-style">
@foreach (var item in Model)
{
<label>@item.BarName</label>
}
</div>
And I got this error:
The model item passed into the dictionary is of type 'Bar', but this dictionary requires a model item of type 'System.Collections.Generic.List`1[Bar]
The reason for this error is that EditorFor
already iterates the List
for you, so if you pass a collection to it, it would display the editor template once for each item in the collection.
This is how I fixed this problem:
Brought the styles outside of the editor template, and into the main view:
@model Foo
@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
<div class="some-style">
@Html.EditorFor(m => m.Bars)
</div>
And changed the EditorTemplate (Bar.cshtml) to this:
@model Bar
<label>@Model.BarName</label>
cd /usr/local
git status
git status
til it's cleanbrew update
For when graceful-fs doesn't work... or you just want to understand where the leak is coming from. Follow this process.
(e.g. graceful-fs isn't gonna fix your wagon if your issue is with sockets.)
From My Blog Article: http://www.blakerobertson.com/devlog/2014/1/11/how-to-determine-whats-causing-error-connect-emfile-nodejs.html
This command will output the number of open handles for nodejs processes:
lsof -i -n -P | grep nodejs
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
...
nodejs 12211 root 1012u IPv4 151317015 0t0 TCP 10.101.42.209:40371->54.236.3.170:80 (ESTABLISHED)
nodejs 12211 root 1013u IPv4 151279902 0t0 TCP 10.101.42.209:43656->54.236.3.172:80 (ESTABLISHED)
nodejs 12211 root 1014u IPv4 151317016 0t0 TCP 10.101.42.209:34450->54.236.3.168:80 (ESTABLISHED)
nodejs 12211 root 1015u IPv4 151289728 0t0 TCP 10.101.42.209:52691->54.236.3.173:80 (ESTABLISHED)
nodejs 12211 root 1016u IPv4 151305607 0t0 TCP 10.101.42.209:47707->54.236.3.172:80 (ESTABLISHED)
nodejs 12211 root 1017u IPv4 151289730 0t0 TCP 10.101.42.209:45423->54.236.3.171:80 (ESTABLISHED)
nodejs 12211 root 1018u IPv4 151289731 0t0 TCP 10.101.42.209:36090->54.236.3.170:80 (ESTABLISHED)
nodejs 12211 root 1019u IPv4 151314874 0t0 TCP 10.101.42.209:49176->54.236.3.172:80 (ESTABLISHED)
nodejs 12211 root 1020u IPv4 151289768 0t0 TCP 10.101.42.209:45427->54.236.3.171:80 (ESTABLISHED)
nodejs 12211 root 1021u IPv4 151289769 0t0 TCP 10.101.42.209:36094->54.236.3.170:80 (ESTABLISHED)
nodejs 12211 root 1022u IPv4 151279903 0t0 TCP 10.101.42.209:43836->54.236.3.171:80 (ESTABLISHED)
nodejs 12211 root 1023u IPv4 151281403 0t0 TCP 10.101.42.209:43930->54.236.3.172:80 (ESTABLISHED)
....
Notice the: 1023u (last line) - that's the 1024th file handle which is the default maximum.
Now, Look at the last column. That indicates which resource is open. You'll probably see a number of lines all with the same resource name. Hopefully, that now tells you where to look in your code for the leak.
If you don't know multiple node processes, first lookup which process has pid 12211. That'll tell you the process.
In my case above, I noticed that there were a bunch of very similar IP Addresses. They were all 54.236.3.###
By doing ip address lookups, was able to determine in my case it was pubnub related.
Use this syntax to determine how many open handles a process has open...
I used this command to test the number of files that were opened after doing various events in my app.
lsof -i -n -P | grep "8465" | wc -l
# lsof -i -n -P | grep "nodejs.*8465" | wc -l
28
# lsof -i -n -P | grep "nodejs.*8465" | wc -l
31
# lsof -i -n -P | grep "nodejs.*8465" | wc -l
34
ulimit -a
The line you want will look like this:
open files (-n) 1024
In case you are expecting to open many connections (websockets is a good example), you can permanently increase the limit:
file: /etc/pam.d/common-session (add to the end)
session required pam_limits.so
file: /etc/security/limits.conf (add to the end, or edit if already exists)
root soft nofile 40000
root hard nofile 100000
restart your nodejs and logout/login from ssh.
this may not work for older NodeJS you'll need to restart server
use instead of if your node runs with different uid.
how about something along these lines
<style type="text/css">
#container {
margin: 0 auto;
text-align: center; /* for IE */
}
#yourdiv {
width: 400px;
border: 1px solid #000;
}
</style>
....
<div id="container">
<div id="yourdiv">
weee
</div>
</div>
//Data Table
protected DataTable tblDynamic
{
get
{
return (DataTable)ViewState["tblDynamic"];
}
set
{
ViewState["tblDynamic"] = value;
}
}
//DynamicReport_GetUserType() function for getting data from DB
System.Data.DataSet ds = manage.DynamicReport_GetUserType();
tblDynamic = ds.Tables[13];
//Add Column as "TypeName"
tblDynamic.Columns.Add(new DataColumn("TypeName", typeof(string)));
//fill column data against ds.Tables[13]
for (int i = 0; i < tblDynamic.Rows.Count; i++)
{
if (tblDynamic.Rows[i]["Type"].ToString()=="A")
{
tblDynamic.Rows[i]["TypeName"] = "Apple";
}
if (tblDynamic.Rows[i]["Type"].ToString() == "B")
{
tblDynamic.Rows[i]["TypeName"] = "Ball";
}
if (tblDynamic.Rows[i]["Type"].ToString() == "C")
{
tblDynamic.Rows[i]["TypeName"] = "Cat";
}
if (tblDynamic.Rows[i]["Type"].ToString() == "D")
{
tblDynamic.Rows[i]["TypeName"] = "Dog;
}
}
Open gradle-wrapper.properties
Change the version there on distributionUrl
line
Others have provided answers for how to change the title size, but as for the axes tick label size, you can also use the set_tick_params method.
E.g., to make the x-axis tick label size small:
ax.xaxis.set_tick_params(labelsize='small')
or, to make the y-axis tick label large:
ax.yaxis.set_tick_params(labelsize='large')
You can also enter the labelsize
as a float, or any of the following string options: 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', or 'xx-large'.
Sadly it appears that the /deep/ selector is deprecated (at least in Chrome) https://www.chromestatus.com/features/6750456638341120
In short it appears there is (currently) no long term solution other than to somehow get your child component to style things dynamically.
You could pass a style object to your child and have it applied via:
<div [attr.style]="styleobject">
Or if you have a specific style you can use something like:
<div [style.background-color]="colorvar">
More discussion related to this: https://github.com/angular/angular/issues/6511
I tested various combinations of android:background
, android:backgroundTint
and android:backgroundTintMode
.
android:backgroundTint
applies the color filter to the resource of android:background
when used together with android:backgroundTintMode
.
Here are the results:
Here's the code if you want to experiment further:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:showIn="@layout/activity_main">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="32dp"
android:textSize="45sp"
android:background="#37AEE4"
android:text="Background" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="32dp"
android:textSize="45sp"
android:backgroundTint="#FEFBDE"
android:text="Background tint" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="32dp"
android:textSize="45sp"
android:background="#37AEE4"
android:backgroundTint="#FEFBDE"
android:text="Both together" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="32dp"
android:textSize="45sp"
android:background="#37AEE4"
android:backgroundTint="#FEFBDE"
android:backgroundTintMode="multiply"
android:text="With tint mode" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="32dp"
android:textSize="45sp"
android:text="Without any" />
</LinearLayout>
background:url(bgimage.jpg) no-repeat; background-size: cover;
This did the trick
I found this question by the title. If anyone else is looking for the answer on how to just get the domain name, use the following environment variable.
System.Environment.UserDomainName
I'm aware that the author to the question mentions this, but I missed it at the first glance and thought someone else might do the same.
What the description of the question then ask for is the fully qualified domain name (FQDN).
The argparse
documentation is reasonably good but leaves out a few useful details which might not be obvious. (@Diego Navarro already mentioned some of this but I'll try to expand on his answer slightly.) Basic usage is as follows:
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--my-foo', default='foobar')
parser.add_argument('-b', '--bar-value', default=3.14)
args = parser.parse_args()
The object you get back from parse_args()
is a 'Namespace' object: An object whose member variables are named after your command-line arguments. The Namespace
object is how you access your arguments and the values associated with them:
args = parser.parse_args()
print args.my_foo
print args.bar_value
(Note that argparse
replaces '-' in your argument names with underscores when naming the variables.)
In many situations you may wish to use arguments simply as flags which take no value. You can add those in argparse like this:
parser.add_argument('--foo', action='store_true')
parser.add_argument('--no-foo', action='store_false')
The above will create variables named 'foo' with value True, and 'no_foo' with value False, respectively:
if (args.foo):
print "foo is true"
if (args.no_foo is False):
print "nofoo is false"
Note also that you can use the "required" option when adding an argument:
parser.add_argument('-o', '--output', required=True)
That way if you omit this argument at the command line argparse
will tell you it's missing and stop execution of your script.
Finally, note that it's possible to create a dict structure of your arguments using the vars
function, if that makes life easier for you.
args = parser.parse_args()
argsdict = vars(args)
print argsdict['my_foo']
print argsdict['bar_value']
As you can see, vars
returns a dict with your argument names as keys and their values as, er, values.
There are lots of other options and things you can do, but this should cover the most essential, common usage scenarios.
This should also work and is a closer answer to what is asked in the question:
for i in range(len(x)):
if valeur.item(i) <= 0.6:
print ("this works")
else:
print ("valeur is too high")