just add /FORCE as linker flag and you're all set.
for instance, if you're working on CMakeLists.txt. Then add following line:
SET(CMAKE_EXE_LINKER_FLAGS "/FORCE")
public class FileUploadExample extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// Parse the request
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (!item.isFormField()) {
String fileName = item.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root + "/uploads");
if (!path.exists()) {
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
System.out.println(uploadedFile.getAbsolutePath());
item.write(uploadedFile);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
This error occurred for me when I mistakenly added a comment following a line continuation character in VB.Net. I removed the comment and the problem went away.
<maven.compiler.release>
(not source
& target
)Several of the other Answers show <maven.compiler.source>
& <maven.compiler.target>
. Both of these are now supplanted by the simpler single element: <maven.compiler.release>
.
<maven.compiler.release>15</maven.compiler.release>
So this:
<!--old-school-->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>15</maven.compiler.source>
<maven.compiler.target>15</maven.compiler.target>
</properties>
…becomes:
<!--modern-->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.release>15</maven.compiler.release>
</properties>
See Question, “maven.compiler.release” as an replacement for source and target?
From http://en.wikipedia.org/wiki/CDATA:
Since it is useful to be able to use less-than signs (<) and ampersands (&) in web page scripts, and to a lesser extent styles, without having to remember to escape them, it is common to use CDATA markers around the text of inline and elements in XHTML documents. But so that the document can also be parsed by HTML parsers, which do not recognise the CDATA markers, the CDATA markers are usually commented-out, as in this JavaScript example:
<script type="text/javascript">
//<![CDATA[
document.write("<");
//]]>
</script>
Use the span
tag
<style>
.redText
{
color:red;
}
.blackText
{
color:black;
font-weight:bold;
}
</style>
<span class="redText">My Name is:</span> <span class="blackText">Tintincute</span>
It's also a good idea to avoid inline styling. Use a custom CSS class instead.
Cron does not load the user's profile when running a task and you have to include the profile in your shell script explicitly.
I had difficulty with this problem as well. I code mainly in Actionscript 3.0 which is base coding for the Adobe Flash Platform, but there are simularities in the Languages:
The solution I came up with is the following:
//Code for Rounding to the nearest 0.05
var r:Number = Math.random() * 10; // NUMBER - Input Your Number here
var n:int = r * 10; // INTEGER - Shift Decimal 2 places to right
var f:int = Math.round(r * 10 - n) * 5;// INTEGER - Test 1 or 0 then convert to 5
var d:Number = (n + (f / 10)) / 10; // NUMBER - Re-assemble the number
trace("ORG No: " + r);
trace("NEW No: " + d);
Thats pretty much it. Note the use of 'Numbers' and 'Integers' and the way they are processed.
Good Luck!
the easiest way is to use position:absolute
on both elements. You can absolutely position relative to the page, or you can absolutely position relative to a container div by setting the container div to position:relative
<div id="container" style="position:relative;">
<div id="div1" style="position:absolute; top:0; left:0;"></div>
<div id="div2" style="position:absolute; top:0; left:0;"></div>
</div>
This is my solution to the problem
const _ = require('lodash');
var objects = [{ 'x': 1, 'y': 2, 'z':3, a:{b:1, c:2, d:{n:0}}, p:[1, 2, 3] }, { 'x': 2, 'y': 1, z:3, a:{b:2, c:2,d:{n:1}}, p:[1,3], m:3 }];
const diffFn=(a,b, path='')=>_.reduce(a, function(result, value, key) {
if(_.isObjectLike(value)){
if(_.isEqual(value, b[key])){
return result;
}else{
return result.concat(diffFn(value, b[key], path?(`${path}.${key}`):key))
}
}else{
return _.isEqual(value, b[key]) ?
result : result.concat(path?(`${path}.${key}`):key);
}
}, []);
const diffKeys1=diffFn(objects[0], objects[1])
const diffKeys2=diffFn(objects[1], objects[0])
const diffKeys=_.union(diffKeys1, diffKeys2)
const res={};
_.forEach(diffKeys, (key)=>_.assign(res, {[key]:{ old: _.get(objects[0], key), new:_.get(objects[1], key)} }))
res
/*
Returns
{
x: { old: 1, new: 2 },
y: { old: 2, new: 1 },
'a.b': { old: 1, new: 2 },
'a.d.n': { old: 0, new: 1 },
'p.1': { old: 2, new: 3 },
'p.2': { old: 3, new: undefined },
m: { old: undefined, new: 3 }
}
*/
Several people seem to have the same problem. The issue is that the IDE only displays the preview if editing a layout file in the res/layout*
directory of an Android project.
In particular, it won't show if editing a file in build/res/layout*
since those are not source directory but output directory. In your case, you are editing a file in the build/
directory...
The Resource folder is set automatically, and can be viewed (and changed) in Project Structure > Modules > [Module name] > Android > Resources directory.
Unless you want to do something more complicated, feeding data from a HTML form into Flask is pretty easy.
my_form_post
).request.form
.templates/my-form.html
:
<form method="POST">
<input name="text">
<input type="submit">
</form>
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/')
def my_form():
return render_template('my-form.html')
@app.route('/', methods=['POST'])
def my_form_post():
text = request.form['text']
processed_text = text.upper()
return processed_text
This is the Flask documentation about accessing request data.
If you need more complicated forms that need validation then you can take a look at WTForms and how to integrate them with Flask.
Note: unless you have any other restrictions, you don't really need JavaScript at all to send your data (although you can use it).
I managed to solved this by adding FcgidBusyTimeout . Just in case if anyone have similar issue with me.
Here is my settings on my apache.conf:
<VirtualHost *:80>
.......
<IfModule mod_fcgid.c>
FcgidBusyTimeout 3600
</IfModule>
</VirtualHost>
Command to install GCC and Development Tools on a CentOS / RHEL 7 server
Type the following yum command as root user:
OR
If above command failed, try:
You were on the right track with response.getOutputStream()
, but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:
@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
// convert JSON to Employee
Employee emp = convertSomehow(json);
// generate the file
PdfUtil.showHelp(emp);
// retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
byte[] contents = (...);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PDF);
// Here you have to set the actual filename of your pdf
String filename = "output.pdf";
headers.setContentDispositionFormData(filename, filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
return response;
}
Notes:
showHelp
is not a good ideabyte[]
: example hereshowHelp()
to avoid overwriting the file if two users send a request at the same timesimple solution from my end is to keep another Table with border and insert your table in the outer table.
<table border="1">
<tr>
<td>
<table border="0">
<tr>
<td>one</td>
<td>two</td>
</tr>
<tr>
<td>one</td>
<td>two</td>
</tr>
</table>
</td>
</tr>
</table>
When installing a tool globally it's to be used by a user as a command line utility anywhere, including outside of node projects. Global installs for a node project are bad because they make deployment more difficult.
The npx
utility bundled with npm
5.2
solves this problem. With it you can invoke locally installed utilities like globally installed utilities (but you must begin the command with npx
). For example, if you want to invoke a locally installed eslint
, you can do:
npx eslint .
When used in a script
field of your package.json, npm
searches node_modules
for the tool as well as globally installed modules, so the local install is sufficient.
So, if you are happy with (in your package.json):
"devDependencies": {
"gulp": "3.5.2"
}
"scripts": {
"test": "gulp test"
}
etc. and running with npm run test
then you shouldn't need the global install at all.
Both methods are useful for getting people set up with your project since sudo
isn't needed. It also means that gulp
will be updated when the version is bumped in the package.json, so everyone will be using the same version of gulp when developing with your project.
It appears that gulp has some unusual behaviour when used globally. When used as a global install, gulp looks for a locally installed gulp to pass control to. Therefore a gulp global install requires a gulp local install to work. The answer above still stands though. Local installs are always preferable to global installs.
If you think about it, a body XRay scan (at the medical center) too needs this kind of measurement for estimating size of tumors. So they place a 1 Dollar Coin on the body, to do a comparative measurement.
Even newspaper is printed with some marks on the corners.
You need a reference to measure. May be you can get your person to wear a cap which has a few bright green circles. Once you recognize the size of the circle you can comparatively measure the remaining.
Or you can create a transparent 1 inch circle which will superimpose on the face, move the camera toward/away the face, aim your superimposed circle on that bright green circle on the cap. Then on your photo will be as per scale.
You can simply do:
"123456".Select(q => new string(q,1)).ToArray();
to have an enumerable of integers, as per comment request, you can:
"123456".Select(q => int.Parse(new string(q,1))).ToArray();
It is a little weak since it assumes the string actually contains numbers.
Please note, the way that build parameters are accessed inside pipeline scripts (pipeline plugin) has changed. This approach:
getBinding().hasVariable("MY_PARAM")
Is not working anymore. Please try this instead:
def myBool = env.getEnvironment().containsKey("MY_BOOL") ? Boolean.parseBoolean("$env.MY_BOOL") : false
The error message should tell you which application is already using the port - in my case it was explorer.exe, so it was just a case of restarting explorer from task manager.
What should happen if there are more than 1 longest string (think '12', and '01')?
Try that to get the longest element
max_length,longest_element = max([(len(x),x) for x in ('a','b','aa')])
And then regular foreach
for st in mylist:
if len(st)==max_length:...
Works for me on a mysql database also:
Entity\Entity_name:
type: entity
table: table_name
fields:
field_name:
type: integer
nullable: true
options:
default: 1
ExecuteScalar();
will work, but an output parameter would be a superior solution.
As mentioned by @jerry you can add services with the below command.
update-rc.d <service> defaults
update-rc.d <service> start 20 3 4 5
update-rc.d -f <service> remove
To validate them check the above commands you can check /etc/rc*.d/ directory where service start with "k" means it will not execute during the boot and service start with "S" will start during the boot.
# for runlevel symlinks:
ls /etc/rc*.d/
In the below screenshot you can see apache2 starting in runlevel2(S02apache2) and stopping in runlevel1(K01apache2)
You can also check the service status with the below command where "+" means service is in running state "-" is in stopped.
service --status-all
OR
install sysv-rc-conf utility.
apt-get install sysv-rc-conf
example
sysv-rc-conf --level 2345 apach22 on
man sysv-rc-conf
Adding my solution for Net Framework and NetCore.
I used this for my Net Framework implementation:
public static class EnumerationExtension
{
public static string Description( this Enum value )
{
// get attributes
var field = value.GetType().GetField( value.ToString() );
var attributes = field.GetCustomAttributes( typeof( DescriptionAttribute ), false );
// return description
return attributes.Any() ? ( (DescriptionAttribute)attributes.ElementAt( 0 ) ).Description : "Description Not Found";
}
}
This doesn't work for NetCore so I modified it to do this:
public static class EnumerationExtension
{
public static string Description( this Enum value )
{
// get attributes
var field = value.GetType().GetField( value.ToString() );
var attributes = field.GetCustomAttributes( false );
// Description is in a hidden Attribute class called DisplayAttribute
// Not to be confused with DisplayNameAttribute
dynamic displayAttribute = null;
if (attributes.Any())
{
displayAttribute = attributes.ElementAt( 0 );
}
// return description
return displayAttribute?.Description ?? "Description Not Found";
}
}
Enumeration Example:
public enum ExportTypes
{
[Display( Name = "csv", Description = "text/csv" )]
CSV = 0
}
Sample Usage for either static added:
var myDescription = myEnum.Description();
Use the xattr
command. You can inspect the extended attributes:
$ xattr s.7z
com.apple.metadata:kMDItemWhereFroms
com.apple.quarantine
and use the -d
option to delete one extended attribute:
$ xattr -d com.apple.quarantine s.7z
$ xattr s.7z
com.apple.metadata:kMDItemWhereFroms
you can also use the -c
option to remove all extended attributes:
$ xattr -c s.7z
$ xattr s.7z
xattr -h
will show you the command line options, and xattr has a man page.
You can compare both approaches for the same data:
def myGeneratorList(n):
for i in range(n):
yield i
def myIterableList(n):
ll = n*[None]
for i in range(n):
ll[i] = i
return ll
# Same values
ll1 = myGeneratorList(10)
ll2 = myIterableList(10)
for i1, i2 in zip(ll1, ll2):
print("{} {}".format(i1, i2))
# Generator can only be read once
ll1 = myGeneratorList(10)
ll2 = myIterableList(10)
print("{} {}".format(len(list(ll1)), len(ll2)))
print("{} {}".format(len(list(ll1)), len(ll2)))
# Generator can be read several times if converted into iterable
ll1 = list(myGeneratorList(10))
ll2 = myIterableList(10)
print("{} {}".format(len(list(ll1)), len(ll2)))
print("{} {}".format(len(list(ll1)), len(ll2)))
Besides, if you check the memory footprint, the generator takes much less memory as it doesn't need to store all the values in memory at the same time.
This is the simplest way to do it. Allows for group authorities, as well as user authorities.
-- Postgres syntax
create table users (
user_id serial primary key,
enabled boolean not null default true,
password text not null,
username citext not null unique
);
create index on users (username);
create table groups (
group_id serial primary key,
name citext not null unique
);
create table authorities (
authority_id serial primary key,
authority citext not null unique
);
create table user_authorities (
user_id int references users,
authority_id int references authorities,
primary key (user_id, authority_id)
);
create table group_users (
group_id int references groups,
user_id int referenecs users,
primary key (group_id, user_id)
);
create table group_authorities (
group_id int references groups,
authority_id int references authorities,
primary key (group_id, authority_id)
);
Then in META-INF/applicationContext-security.xml
<beans:bean class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" id="passwordEncoder" />
<authentication-manager>
<authentication-provider>
<jdbc-user-service
data-source-ref="dataSource"
users-by-username-query="select username, password, enabled from users where username=?"
authorities-by-username-query="select users.username, authorities.authority from users join user_authorities using(user_id) join authorities using(authority_id) where users.username=?"
group-authorities-by-username-query="select groups.id, groups.name, authorities.authority from users join group_users using(user_id) join groups using(group_id) join group_authorities using(group_id) join authorities using(authority_id) where users.username=?"
/>
<password-encoder ref="passwordEncoder" />
</authentication-provider>
</authentication-manager>
SELECT IF((
SELECT count(*) FROM gdata_calendars
WHERE `group` = ? AND id = ?)
,1,0);
For Detail explanation you can visit here
API 11 added a setRotation() method to all views.
If you don't want to add a new dependency just to do this (like HTMLEntities
) and you're already using Hpricot
, it can both escape and unescape for you. It handles much more than CGI
:
Hpricot.uxs "foo bär"
=> "foo bär"
You can either branch gh-pages to run your code or try this extension (Chrome, Firefox): https://github.com/ryt/githtml
If what you need are tests, you could embed your JS files into: http://jsperf.com/
Below applies to all tags with the following two classes
.abc.xyz {
width: 200px !important;
}
applies to div tags with the following two classes
div.abc.xyz {
width: 200px !important;
}
If you wanted to modify this using jQuery
$(document).ready(function() {
$("div.abc.xyz").width("200px");
});
try below approach, very simple easy to implement
Below is the jsfiddle link
http://jsfiddle.net/v2t2k8ke/2/
HTML:
<table border='1' id='tbl_cnt'>
<thead><tr></tr></thead><tbody></tbody>
CSS:
#tbl_cnt{
border-collapse: collapse; width: 100%;word-break:break-all;
}
#tbl_cnt thead, #tbl_cnt tbody{
display: block;
}
#tbl_cnt thead tr{
background-color: #8C8787; text-align: center;width:100%;display:block;
}
#tbl_cnt tbody {
height: 100px;overflow-y: auto;overflow-x: hidden;
}
Jquery:
var data = [
{
"status":"moving","vehno":"tr544","loc":"bng","dri":"ttt"
}, {
"status":"stop","vehno":"tr54","loc":"che", "dri":"ttt"
},{ "status":"idle","vehno":"yy5499999999999994","loc":"bng","dri":"ttt"
},{
"status":"moving","vehno":"tr544","loc":"bng", "dri":"ttt"
}, {
"status":"stop","vehno":"tr54","loc":"che","dri":"ttt"
},{
"status":"idle","vehno":"yy544","loc":"bng","dri":"ttt"
}
];
var sth = '';
$.each(data[0], function (key, value) {
sth += '<td>' + key + '</td>';
});
var stb = '';
$.each(data, function (key, value) {
stb += '<tr>';
$.each(value, function (key, value) {
stb += '<td>' + value + '</td>';
});
stb += '</tr>';
});
$('#tbl_cnt thead tr').append(sth);
$('#tbl_cnt tbody').append(stb);
setTimeout(function () {
var col_cnt=0
$.each(data[0], function (key, value) {col_cnt++;});
$('#tbl_cnt thead tr').css('width', ($("#tbl_cnt tbody") [0].scrollWidth)+ 'px');
$('#tbl_cnt thead tr td,#tbl_cnt tbody tr td').css('width', ($('#tbl_cnt thead tr ').width()/Number(col_cnt)) + 'px');}, 100)
Prior to running python, type cd
in the commmand line, and it will tell you the directory you are currently in. When python runs, it can only access files in this directory. hello.py
needs to be in this directory, so you can move hello.py
from its existing location to this folder as you would move any other file in Windows or you can change directories and run python in the directory hello.py
is.
Edit: Python cannot access the files in the subdirectory unless a path to it provided. You can access files in any directory by providing the path. python C:\Python27\Projects\hello.p
Because Convert.ToInt32
rounds:
Return Value: rounded to the nearest 32-bit signed integer. If value is halfway between two whole numbers, the even number is returned; that is, 4.5 is converted to 4, and 5.5 is converted to 6.
...while the cast truncates:
When you convert from a double or float value to an integral type, the value is truncated.
Update: See Jeppe Stig Nielsen's comment below for additional differences (which however do not come into play if score
is a real number as is the case here).
Oracle syntax from the 11g Documentation:
CASE { simple_case_expression | searched_case_expression }
[ else_clause ]
END
simple_case_expression
expr { WHEN comparison_expr THEN return_expr }...
searched_case_expression
{ WHEN condition THEN return_expr }...
else_clause
ELSE else_expr
I am trying to do something similar to this. As commented above, I think you would want to build a new image with a custom Dockerfile (using the image you pulled as a base image), ADD
your certificate, then RUN update-ca-certificates
. This way you will have a consistent state each time you start a container from this new image.
# Dockerfile
FROM some-base-image:0.1
ADD you_certificate.crt:/container/cert/path
RUN update-ca-certificates
Let's say a docker build
against that Dockerfile produced IMAGE_ID. On the next docker run -d [any other options] IMAGE_ID
, the container started by that command will have your certificate info. Simple and reproducible.
You can simply replace all \n
with <br/>
tag so that when page is displayed then it breaks line.
UPDATE table SET field = REPLACE(field, '\n', '<br/>')
While @Jared's answer for incrementing works for 0.5
step size, it fails for other step sizes due to rounding issues:
np.arange(11, 17, 0.1).tolist()
# [11.0,11.1,11.2,11.299999999999999, ... 16.79999999999998, 16.899999999999977]
Instead I needed something like this myself, working not just for 0.5
:
# Example 11->16 step 0.5
s = 11
e = 16
step = 0.5
my_list = [round(num, 2) for num in np.linspace(s,e,(e-s)*int(1/step)+1).tolist()]
# [11.0, 11.5, 12.0, 12.5, 13.0, 13.5, 14.0, 14.5, 15.0, 15.5, 16.0]
# Example 0->1 step 0.1
s = 0
e = 1
step = 0.1
my_list = [round(num, 2) for num in np.linspace(s,e,(e-s)*int(1/step)+1).tolist()]
# [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
I normally differentiate these two via this diagram:
Use PrimaryKeyJoinColumn
Use JoinColumn
Whilst the listed answer is correct, may I suggest that if your column is to hold case sensitive strings you read the documentation and alter your table definition accordingly.
In my case this amounted to defining my column as:
`tag` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT ''
This is in my opinion preferential to adjusting your queries.
If you want to do something to each row in a DataFrame object, use map
. This will allow you to perform further calculations on each row. It's the equivalent of looping across the entire dataset from 0
to len(dataset)-1
.
Note that this will return a PipelinedRDD, not a DataFrame.
Yes, you can put arrays in sessions, example:
$_SESSION['name_here'] = $your_array;
Now you can use the $_SESSION['name_here']
on any page you want but make sure that you put the session_start()
line before using any session functions, so you code should look something like this:
session_start();
$_SESSION['name_here'] = $your_array;
Possible Example:
session_start();
$_SESSION['name_here'] = $_POST;
Now you can get field values on any page like this:
echo $_SESSION['name_here']['field_name'];
As for the second part of your question, the session variables remain there unless you assign different array data:
$_SESSION['name_here'] = $your_array;
Session life time is set into php.ini file.
Very easy, trial and error. Go to the cell you want the month in. Type the Month, go to the next cell and type the year, something weird will come up but then go to your number section click on the little arrow in the right bottom and highlight text and it will change to the year you originally typed
You can add atom beauty package for formatting text in atom..
file --> setting --> Install
then you type atom-beautify in search area.
then click Package button.. select atom beuty and install it.
next you can format your text using (Alt + ctrl + b) or right click and select beautify editor contents
From VS:
From VS on a different machine
You don't need VS to be on the same machine as the enlistment as you can edit remote enlistments! In the dialog that comes up when you press the "Workspaces..." item there is a check box stating "Show Remote Workspaces" - just tick that and you'll get a list of all your enlistments:
From the command line
Call "tf workspace" from a developer command prompt. It will bring up the "Manage Workspaces" directly!
Your best option is to call System.gc()
which simply is a hint to the garbage collector that you want it to do a collection. There is no way to force and immediate collection though as the garbage collector is non-deterministic.
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
http://www.tutorialspoint.com/mysql/mysql-date-time-functions.htm
use Date function directly. Hope it works
It's not entirely clear what you mean by "the filepath of the file that is currently running within the process".
sys.argv[0]
usually contains the location of the script that was invoked by the Python interpreter.
Check the sys documentation for more details.
As @Tim and @Pat Notz have pointed out, the __file__ attribute provides access to
the file from which the module was loaded, if it was loaded from a file
This worked for me:
git log
`git reset --hard <089810b5be5e907ad9e3b01f>`
git pull
git status
I need to do the same thing for a project I am currently working on. Here is how I solved things:
/* Prompt user for input */
printf("Enter a number: ");
/* Read user input */
char input[255]; //Of course, you can choose a different input size
fgets(input, sizeof(input), stdin);
/* Strip trailing newline */
size_t ln = strlen(input) - 1;
if( input[ln] == '\n' ) input[ln] = '\0';
/* Ensure that input is a number */
for( size_t i = 0; i < ln; i++){
if( !isdigit(input[i]) ){
fprintf(stderr, "%c is not a number. Try again.\n", input[i]);
getInput(); //Assuming this is the name of the function you are using
return;
}
}
Guys I found the issue
I just tried by adding the qualifier name in employee service finally it solved my issue.
@Service("employeeService")
public class EmployeeServiceImpl implements EmployeeService{
}
As explained in other answers it converts the variable to a number. Specially useful when d
can be either a number or a string that evaluates to a number.
Example (using the addMonths
function in the question):
addMonths(34,1,true);
addMonths("34",1,true);
then the +d
will evaluate to a number in all cases. Thus avoiding the need to check for the type and take different code paths depending on whether d
is a number, a function or a string that can be converted to a number.
I had the same problem, Oracle config in default affects letter register. In exact my Scheme_Name was written all Capital letters. You can see your Scheme_Name on "Other Users" tab, if you are using Oracle S
.exe - the 'normal' executable
.vshost.exe - a special version of the executable to aid debuging; see MSDN for details
.pdb - the Program Data Base with debug symbols
.vshost.exe.manifest - a kind of configuration file containing mostly dependencies on libraries
I am using Linux raspi 4.19.118+ #1311 via ssh Powershell on Win 10 Pro 1909 with German keyboard. nano shortcut Goto Line with "Crtl + Shift + -" was not working Solution: Step 1 - Do Current Position with "Crtl + C" Step 2 - Goto Line with "Crtl + Shift + -" IS working!
I dont know what effects it. But now its working without step 1!
Alternatively you can use img2pdf to convert images to pdf. Install it on Debian or Ubuntu with:
sudo apt install img2pdf
Convert one or more images to pdf:
img2pdf img.jpg -o output.pdf
It uses a different mechanism than imagemagick to embed the image into the pdf. When possible Img2pdf embeds the image directly into the pdf, without decoding and recoding the image.
Things you can add to declarations: [] in modules
Pro Tip: The error message explains it - Please add a @Pipe/@Directive/@Component annotation.
If you're doing programatic customisation, don't hard code the system font. Use UIFont systemFontOfSize:
, UIFont boldSystemFontOfSize:
and UIFont italicSystemFontOfSize
(Apple documentation).
This has become especially relevant since iOS 7, which changed the system font to Helvetica Neue.
This has become super especially relevant since iOS 9, which changed the system font again to San Francisco.
You can use the following code to check if the file can be opened with exclusive access (that is, it is not opened by another application). If the file isn't closed, you could wait a few moments and check again until the file is closed and you can safely copy it.
You should still check if File.Copy fails, because another application may open the file between the moment you check the file and the moment you copy it.
public static bool IsFileClosed(string filename)
{
try
{
using (var inputStream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None))
{
return true;
}
}
catch (IOException)
{
return false;
}
}
In combination with the above answer, you want to ask jq for raw output, so your last filter should be eg.:
cat input.json | jq -r 'keys'
From jq help:
-r output raw strings, not JSON texts;
You can add a callback function to your DatePicker to tell it to blur the input field before showing the DatePicker.
$('.selector').datepicker({
beforeShow: function(){$('input').blur();}
});
Note: The iOS keyboard will appear for a fraction of a second and then hide.
You can also compare two different files in two different revisions, like this:
git diff <revision_1>:<file_1> <revision_2>:<file_2>
See the code below, this is the complete code about getting a mouse event(rightclick, leftclick) And you can DIY this code and make it on your own.
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace Demo_mousehook_csdn
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
MouseHook mh;
private void Form1_Load(object sender, EventArgs e)
{
mh = new MouseHook();
mh.SetHook();
mh.MouseMoveEvent += mh_MouseMoveEvent;
mh.MouseClickEvent += mh_MouseClickEvent;
mh.MouseDownEvent += mh_MouseDownEvent;
mh.MouseUpEvent += mh_MouseUpEvent;
}
private void mh_MouseDownEvent(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
richTextBox1.AppendText("Left Button Press\n");
}
if (e.Button == MouseButtons.Right)
{
richTextBox1.AppendText("Right Button Press\n");
}
}
private void mh_MouseUpEvent(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
richTextBox1.AppendText("Left Button Release\n");
}
if (e.Button == MouseButtons.Right)
{
richTextBox1.AppendText("Right Button Release\n");
}
}
private void mh_MouseClickEvent(object sender, MouseEventArgs e)
{
//MessageBox.Show(e.X + "-" + e.Y);
if (e.Button == MouseButtons.Left)
{
string sText = "(" + e.X.ToString() + "," + e.Y.ToString() + ")";
label1.Text = sText;
}
}
private void mh_MouseMoveEvent(object sender, MouseEventArgs e)
{
int x = e.Location.X;
int y = e.Location.Y;
textBox1.Text = x + "";
textBox2.Text = y + "";
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
mh.UnHook();
}
private void Form1_FormClosed_1(object sender, FormClosedEventArgs e)
{
mh.UnHook();
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
}
public class Win32Api
{
[StructLayout(LayoutKind.Sequential)]
public class POINT
{
public int x;
public int y;
}
[StructLayout(LayoutKind.Sequential)]
public class MouseHookStruct
{
public POINT pt;
public int hwnd;
public int wHitTestCode;
public int dwExtraInfo;
}
public delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern bool UnhookWindowsHookEx(int idHook);
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern int CallNextHookEx(int idHook, int nCode, IntPtr wParam, IntPtr lParam);
}
public class MouseHook
{
private Point point;
private Point Point
{
get { return point; }
set
{
if (point != value)
{
point = value;
if (MouseMoveEvent != null)
{
var e = new MouseEventArgs(MouseButtons.None, 0, point.X, point.Y, 0);
MouseMoveEvent(this, e);
}
}
}
}
private int hHook;
private const int WM_MOUSEMOVE = 0x200;
private const int WM_LBUTTONDOWN = 0x201;
private const int WM_RBUTTONDOWN = 0x204;
private const int WM_MBUTTONDOWN = 0x207;
private const int WM_LBUTTONUP = 0x202;
private const int WM_RBUTTONUP = 0x205;
private const int WM_MBUTTONUP = 0x208;
private const int WM_LBUTTONDBLCLK = 0x203;
private const int WM_RBUTTONDBLCLK = 0x206;
private const int WM_MBUTTONDBLCLK = 0x209;
public const int WH_MOUSE_LL = 14;
public Win32Api.HookProc hProc;
public MouseHook()
{
this.Point = new Point();
}
public int SetHook()
{
hProc = new Win32Api.HookProc(MouseHookProc);
hHook = Win32Api.SetWindowsHookEx(WH_MOUSE_LL, hProc, IntPtr.Zero, 0);
return hHook;
}
public void UnHook()
{
Win32Api.UnhookWindowsHookEx(hHook);
}
private int MouseHookProc(int nCode, IntPtr wParam, IntPtr lParam)
{
Win32Api.MouseHookStruct MyMouseHookStruct = (Win32Api.MouseHookStruct)Marshal.PtrToStructure(lParam, typeof(Win32Api.MouseHookStruct));
if (nCode < 0)
{
return Win32Api.CallNextHookEx(hHook, nCode, wParam, lParam);
}
else
{
if (MouseClickEvent != null)
{
MouseButtons button = MouseButtons.None;
int clickCount = 0;
switch ((Int32)wParam)
{
case WM_LBUTTONDOWN:
button = MouseButtons.Left;
clickCount = 1;
MouseDownEvent(this, new MouseEventArgs(button, clickCount, point.X, point.Y, 0));
break;
case WM_RBUTTONDOWN:
button = MouseButtons.Right;
clickCount = 1;
MouseDownEvent(this, new MouseEventArgs(button, clickCount, point.X, point.Y, 0));
break;
case WM_MBUTTONDOWN:
button = MouseButtons.Middle;
clickCount = 1;
MouseDownEvent(this, new MouseEventArgs(button, clickCount, point.X, point.Y, 0));
break;
case WM_LBUTTONUP:
button = MouseButtons.Left;
clickCount = 1;
MouseUpEvent(this, new MouseEventArgs(button, clickCount, point.X, point.Y, 0));
break;
case WM_RBUTTONUP:
button = MouseButtons.Right;
clickCount = 1;
MouseUpEvent(this, new MouseEventArgs(button, clickCount, point.X, point.Y, 0));
break;
case WM_MBUTTONUP:
button = MouseButtons.Middle;
clickCount = 1;
MouseUpEvent(this, new MouseEventArgs(button, clickCount, point.X, point.Y, 0));
break;
}
var e = new MouseEventArgs(button, clickCount, point.X, point.Y, 0);
MouseClickEvent(this, e);
}
this.Point = new Point(MyMouseHookStruct.pt.x, MyMouseHookStruct.pt.y);
return Win32Api.CallNextHookEx(hHook, nCode, wParam, lParam);
}
}
public delegate void MouseMoveHandler(object sender, MouseEventArgs e);
public event MouseMoveHandler MouseMoveEvent;
public delegate void MouseClickHandler(object sender, MouseEventArgs e);
public event MouseClickHandler MouseClickEvent;
public delegate void MouseDownHandler(object sender, MouseEventArgs e);
public event MouseDownHandler MouseDownEvent;
public delegate void MouseUpHandler(object sender, MouseEventArgs e);
public event MouseUpHandler MouseUpEvent;
}
}
You can download the demo And the tutorial here : C# Mouse Hook Demo
In this simple way
char str [10] = "IAmCute";
printf ("%c",str[4]);
DEMO : http://jsfiddle.net/shfj70qp/
//dd/mm/yyyy
var date = new Date();
var month = date.getMonth();
var day = date.getDate();
var year = date.getFullYear();
console.log(month+"/"+day+"/"+year);
I wanted a text field that only allowed integers. Here's what I ended up with (using info from here and elsewhere):
Create integer number formatter (in UIApplicationDelegate so it can be reused):
@property (nonatomic, retain) NSNumberFormatter *integerNumberFormatter;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Create and configure an NSNumberFormatter for integers
integerNumberFormatter = [[NSNumberFormatter alloc] init];
[integerNumberFormatter setMaximumFractionDigits:0];
return YES;
}
Use filter in UITextFieldDelegate:
@interface MyTableViewController : UITableViewController <UITextFieldDelegate> {
ictAppDelegate *appDelegate;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// Make sure the proposed string is a number
NSNumberFormatter *inf = [appDelegate integerNumberFormatter];
NSString* proposedString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSNumber *proposedNumber = [inf numberFromString:proposedString];
if (proposedNumber) {
// Make sure the proposed number is an integer
NSString *integerString = [inf stringFromNumber:proposedNumber];
if ([integerString isEqualToString:proposedString]) {
// proposed string is an integer
return YES;
}
}
// Warn the user we're rejecting the change
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
return NO;
}
private void _MenuExit_Click(object sender, RoutedEventArgs e)
{
System.Windows.Application.Current.MainWindow.Close();
}
//Override the onClose method in the Application Main window
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
MessageBoxResult result = MessageBox.Show("Do you really want to close", "",
MessageBoxButton.OKCancel);
if (result == MessageBoxResult.Cancel)
{
e.Cancel = true;
}
base.OnClosing(e);
}
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location location) {
CameraUpdate center=CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(11);
mMap.moveCamera(center);
mMap.animateCamera(zoom);
}
});
I face this error on testing WebAPI in Postman tool.
After building the code, If we remove any line (For Example: In my case when I remove one Commented line this error was occur...) in debugging mode then the "Non-static method requires a target" error will occur.
Again, I tried to send the same request. This time code working properly. And I get the response properly in Postman.
I hope it will use to someone...
You can use .empty()
, like this:
$("#foo").empty();
Remove all child nodes of the set of matched elements from the DOM.
I might be late. Simply add a new field ID in the table with type AutoNumber. This will generate unique IDs and can utilize in Access too
download rpm packages and run the following command:
rpm -Uvh glibc-2.15-60.el6.x86_64.rpm \
glibc-common-2.15-60.el6.x86_64.rpm \
glibc-devel-2.15-60.el6.x86_64.rpm \
glibc-headers-2.15-60.el6.x86_64.rpm
This works for me: http://gitblit.com/setup_client.html
Eclipse/EGit/JGit
Window->Preferences->Team->Git->Configuration
Click the New Entry button
Key = http.sslVerify
Value = false
Try this one for finding 5th highest salary-
SELECT DISTINCT(column name) FROM table ORDER BY (column name) desc LIMIT 4,1
for nth salary-
SELECT DISTINCT(column name) FROM table ORDER BY (column name) desc LIMIT n-1,1
I have tried it on phpmyadmin panel..
You would use the WITH ADMIN OPTION
option in the GRANT
statement
GRANT CREATE SESSION TO <<username>> WITH ADMIN OPTION
You'd obviously figure it out after a while but just posting this so that it might help someone. This could also happen when your file path contains any whitespace appended or prepended to it.
While it might be possible to use numpy alone to do this, the operation is not built-in. That said, you can use scikit-image
(which is built on numpy) to do this kind of image manipulation.
Scikit-Image rescaling documentation is here.
For example, you could do the following with your image:
from skimage.transform import resize
bottle_resized = resize(bottle, (140, 54))
This will take care of things like interpolation, anti-aliasing, etc. for you.
if (a) b else c
^ is what you can use instead of the ternary operator expression a ? b : c
which Kotlin syntax does not allow.
In Kotlin, many control statements, such as if
, when
, and even try
, can be used as expressions. As a result, these statements can have a result which may be assigned to a variable, be returned from a function, etc.
As a result of Kotlin's expressions, the language does not really need the ternary operator.
if (a) b else c
is what you can use instead of the ternary operator expression a ? b : c
.
I think the idea is that the former expression is more readable since everybody knows what ifelse
does, whereas ? :
is rather unclear if you're not familiar with the syntax already.
Nevertheless, I have to admit that I often miss the more convenient ternary operator.
Other Alternatives
when
You might also see when
constructs used in Kotlin when conditions are checked. It's also a way to express if-else cascades in an alternative way. The following corresponds to the OTs example.
when(a) {
true -> b
false -> c
}
Extensions
As many good examples (Kotlin Ternary Conditional Operator) in the other answers show, extensions can also help with solving your use case.
My best guess at why you had problems with the ----- covering your first result is that you actually read the input line from a file. That line probably had a \r on the end so you ended up with something like this:
-----------test2-------test3
What happened is the machine actually printed this:
test-------test2-------test3\r-------
That means, because of the carriage return at the end of test3, that the dashes after test3 were printed over the top of the first word (and a few of the existing dashes between test and test2 but you wouldn't notice that because they were already dashes).
There was a time when adding strings into an array and finalising the string by using join
was the fastest/best method. These days browsers have highly optimised string routines and it is recommended that +
and +=
methods are fastest/best
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.yourRadioGroup);
radioGroup.setOnClickListener(v -> {
// get selected radio button from radioGroup
int selectedId = radioGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
radioButton = findViewById(selectedId);
String slectedValue=radioButton.getText()
});
Templates. I think that is Smarty syntax.
The simple way to get a date x days in the future is to increment the date:
function addDays(dateObj, numDays) {
return dateObj.setDate(dateObj.getDate() + numDays);
}
Note that this modifies the supplied date object, e.g.
function addDays(dateObj, numDays) {
dateObj.setDate(dateObj.getDate() + numDays);
return dateObj;
}
var now = new Date();
var tomorrow = addDays(new Date(), 1);
var nextWeek = addDays(new Date(), 7);
alert(
'Today: ' + now +
'\nTomorrow: ' + tomorrow +
'\nNext week: ' + nextWeek
);
I don't know jQuery, but I do know that if you get the select element, it contains an 'options' object.
var myOpts = document.getElementById('yourselect').options;
alert(myOpts[0].value) //=> Value of the first option
I almost always use curly-braces; however, in some cases where I'm writing tests, I do keyword packing/unpacking, and in these cases dict() is much more maintainable, as I don't need to change:
a=1,
b=2,
to:
'a': 1,
'b': 2,
It also helps in some circumstances where I think I might want to turn it into a namedtuple or class instance at a later time.
In the implementation itself, because of my obsession with optimisation, and when I don't see a particularly huge maintainability benefit, I'll always favour curly-braces.
In tests and the implementation, I would never use dict() if there is a chance that the keys added then, or in the future, would either:
dict(1foo=2)
raises a SyntaxError)The only "big" difference between POST & GET (when using them with AJAX) is since GET is URL provided, they are limited in ther length (since URL arent infinite in length).
String current = elements[i];
if (i != elements.length - 1) {
String next = elements[i+1];
}
This makes sure you don't get an ArrayIndexOutOfBoundsException
for the last element (there is no 'next' there). The other option is to iterate to i < elements.length - 1
. It depends on your requirements.
If I want to create JavaScript Object from string generated by for loop then I would JSON to Object approach. I would generate JSON string by iterating for loop and then use any popular JavaScript Framework to evaluate JSON to Object.
I have used Prototype JavaScript Framework. I have two array with keys and values. I iterate through for loop and generate valid JSON string. I use evalJSON() function to convert JSON string to JavaScript object.
Here is example code. Tryout on your FireBug Console
var key = ["color", "size", "fabric"];
var value = ["Black", "XL", "Cotton"];
var json = "{ ";
for(var i = 0; i < key.length; i++) {
(i + 1) == key.length ? json += "\"" + key[i] + "\" : \"" + value[i] + "\"" : json += "\"" + key[i] + "\" : \"" + value[i] + "\",";
}
json += " }";
var obj = json.evalJSON(true);
console.log(obj);
if (checkbox.checked && columnname != a && columnname != b && columnname != c)
{
"statement 1"
}
else if (columnname != a && columnname != b && columnname != c
&& columnname != A2)
{
"statement 1"
}
is one way to simplify a little.
For me it worked like I had images in icons
folder under src
and I wrote below code.
new ImageIcon(getClass().getResource("/icons/rsz_measurment_01.png"));
In modern browsers you can build on top of @Sushil's answer with pure JavaScript and the DOM:
function validateEmail(value) {
var input = document.createElement('input');
input.type = 'email';
input.required = true;
input.value = value;
return typeof input.checkValidity === 'function' ? input.checkValidity() : /\S+@\S+\.\S+/.test(value);
}
I've put together an example in the fiddle http://jsfiddle.net/boldewyn/2b6d5/. Combined with feature detection and the bare-bones validation from Squirtle's Answer, it frees you from the regular expression massacre and does not bork on old browsers.
Do you have your date variable stored as a String or a Date type?
In which case you will need to do something like
DateTime myDate = null;
DateTime.TryParse(myString,myDate);
or
Convert.ToDateTime(myString);
You can then call ToString("dd-MM-yyyy") on your date variable
HTML: text/html
, full-stop.
XHTML: application/xhtml+xml
, or only if following HTML compatbility guidelines, text/html
. See the W3 Media Types Note.
XML: text/xml
, application/xml
(RFC 2376).
There are also many other media types based around XML, for example application/rss+xml
or image/svg+xml
. It's a safe bet that any unrecognised but registered ending in +xml
is XML-based. See the IANA list for registered media types ending in +xml
.
(For unregistered x-
types, all bets are off, but you'd hope +xml
would be respected.)
There's a nice jQuery number plugin: https://github.com/teamdf/jquery-number
It allows you to change any number in the format you like, with options for decimal digits and separator characters for decimal and thousand:
$.number(12345.4556, 2); // -> 12,345.46
$.number(12345.4556, 3, ',', ' ') // -> 12 345,456
You can use it inside input fields directly, which is nicer, using same options like above:
$("input").number(true, 2);
Or you can apply to a whole set of DOM elements using selector:
$('span.number').number(true, 2);
Use mouseup and keyup
$(":input").bind('keyup mouseup', function () {
alert("changed");
});
I think this should be a comment or an edit to ThinkingMedia's answer on this very question (Check free disk space for current partition in bash), but I am not allowed to comment (not enough rep) and my edit has been rejected (reason: "this should be a comment or an answer"). So please, powers of the SO universe, don't damn me for repeating and fixing someone else's "answer". But someone on the internet was wrong!™ and they wouldn't let me fix it.
The code
df --output=avail -h "$PWD" | sed '1d;s/[^0-9]//g'
has a substantial flaw:
Yes, it will output 50G
free as 50 -- but it will also output 5.0M
free as 50 or 3.4G
free as 34 or 15K
free as 15.
To create a script with the purpose of checking for a certain amount of free disk space you have to know the unit you're checking against. Remove it (as sed
does in the example above) the numbers don't make sense anymore.
If you actually want it to work, you will have to do something like:
FREE=`df -k --output=avail "$PWD" | tail -n1` # df -k not df -h
if [[ $FREE -lt 10485760 ]]; then # 10G = 10*1024*1024k
# less than 10GBs free!
fi;
Also for an installer to df -k $INSTALL_TARGET_DIRECTORY
might make more sense than df -k "$PWD"
.
Finally, please note that the --output
flag is not available in every version of df / linux.
Here is an example:
$.ajax({
type: "post",
url: "ajax/example.php",
data: 'page=' + btn_page,
success: function (data) {
var a = data; // This line shows error.
$.ajax({
type: "post",
url: "example.php",
data: 'page=' + a,
success: function (data) {
}
});
}
});
select <column list> into <dest. table> from <source table>;
You could do this way.
SELECT windows_release, windows_service_pack_level,
windows_sku, os_language_version
into new_table_name
FROM sys.dm_os_windows_info OPTION (RECOMPILE);
I think I just discovered a way to apply overlapping conditions in the expected way using VBA. After hours of trying out different approaches I found that what worked was changing the "Applies to" range for the conditional format rule, after every single one was created!
This is my working example:
Sub ResetFormatting()
' ----------------------------------------------------------------------------------------
' Written by..: Julius Getz Mørk
' Purpose.....: If conditional formatting ranges are broken it might cause a huge increase
' in duplicated formatting rules that in turn will significantly slow down
' the spreadsheet.
' This macro is designed to reset all formatting rules to default.
' ----------------------------------------------------------------------------------------
On Error GoTo ErrHandler
' Make sure we are positioned in the correct sheet
WS_PROMO.Select
' Disable Events
Application.EnableEvents = False
' Delete all conditional formatting rules in sheet
Cells.FormatConditions.Delete
' CREATE ALL THE CONDITIONAL FORMATTING RULES:
' (1) Make negative values red
With Cells(1, 1).FormatConditions.add(xlCellValue, xlLess, "=0")
.Font.Color = -16776961
.StopIfTrue = False
End With
' (2) Highlight defined good margin as green values
With Cells(1, 1).FormatConditions.add(xlCellValue, xlGreater, "=CP_HIGH_MARGIN_DEFINITION")
.Font.Color = -16744448
.StopIfTrue = False
End With
' (3) Make article strategy "D" red
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""D""")
.Font.Bold = True
.Font.Color = -16776961
.StopIfTrue = False
End With
' (4) Make article strategy "A" blue
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""A""")
.Font.Bold = True
.Font.Color = -10092544
.StopIfTrue = False
End With
' (5) Make article strategy "W" green
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""W""")
.Font.Bold = True
.Font.Color = -16744448
.StopIfTrue = False
End With
' (6) Show special cost in bold green font
With Cells(1, 1).FormatConditions.add(xlCellValue, xlNotEqual, "=0")
.Font.Bold = True
.Font.Color = -16744448
.StopIfTrue = False
End With
' (7) Highlight duplicate heading names. There can be none.
With Cells(1, 1).FormatConditions.AddUniqueValues
.DupeUnique = xlDuplicate
.Font.Color = -16383844
.Interior.Color = 13551615
.StopIfTrue = False
End With
' (8) Make heading rows bold with yellow background
With Cells(1, 1).FormatConditions.add(Type:=xlExpression, Formula1:="=IF($B8=""H"";TRUE;FALSE)")
.Font.Bold = True
.Interior.Color = 13434879
.StopIfTrue = False
End With
' Modify the "Applies To" ranges
Cells.FormatConditions(1).ModifyAppliesToRange Range("O8:P507")
Cells.FormatConditions(2).ModifyAppliesToRange Range("O8:O507")
Cells.FormatConditions(3).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(4).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(5).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(6).ModifyAppliesToRange Range("E8:E507")
Cells.FormatConditions(7).ModifyAppliesToRange Range("A7:AE7")
Cells.FormatConditions(8).ModifyAppliesToRange Range("B8:L507")
ErrHandler:
Application.EnableEvents = False
End Sub
There are some cool answers here (errator esp.), but for something analogous to split in other languages -- which is what I took the original question to mean -- I settled on this:
IN="[email protected];[email protected]"
declare -a a="(${IN/;/ })";
Now ${a[0]}
, ${a[1]}
, etc, are as you would expect. Use ${#a[*]}
for number of terms. Or to iterate, of course:
for i in ${a[*]}; do echo $i; done
IMPORTANT NOTE:
This works in cases where there are no spaces to worry about, which solved my problem, but may not solve yours. Go with the $IFS
solution(s) in that case.
$ readlink -m FILE
/path/to/FILE
This is better than readlink -e FILE
or realpath
, because it works even if the file doesn't exist.
C++ has two kinds of enum
:
enum class
esenum
sHere are a couple of examples on how to declare them:
enum class Color { red, green, blue }; // enum class
enum Animal { dog, cat, bird, human }; // plain enum
What is the difference between the two?
enum class
es - enumerator names are local to the enum and their values do not implicitly convert to other types (like another enum
or int
)
Plain enum
s - where enumerator names are in the same scope as the enum and their
values implicitly convert to integers and other types
Example:
enum Color { red, green, blue }; // plain enum
enum Card { red_card, green_card, yellow_card }; // another plain enum
enum class Animal { dog, deer, cat, bird, human }; // enum class
enum class Mammal { kangaroo, deer, human }; // another enum class
void fun() {
// examples of bad use of plain enums:
Color color = Color::red;
Card card = Card::green_card;
int num = color; // no problem
if (color == Card::red_card) // no problem (bad)
cout << "bad" << endl;
if (card == Color::green) // no problem (bad)
cout << "bad" << endl;
// examples of good use of enum classes (safe)
Animal a = Animal::deer;
Mammal m = Mammal::deer;
int num2 = a; // error
if (m == a) // error (good)
cout << "bad" << endl;
if (a == Mammal::deer) // error (good)
cout << "bad" << endl;
}
enum class
es should be preferred because they cause fewer surprises that could potentially lead to bugs.
This error occurs when you're trying to target an element that is wrapped in a condition.
So, here if I use ngIf in place of [hidden], it will give me TypeError: Cannot read property 'nativeElement' of undefined
So use [hidden], class.show or class.hide in place of *ngIf.
<button (click)="displayMap()" class="btn btn-primary">Display Map</button>
<div [hidden]="!display">
<div #mapContainer id="map">Content to render when condition is true.</div>
</div>
One way to achieve this is
>>> pd.DataFrame(np.array([[2, 3, 4]]), columns=['A', 'B', 'C']).append(df, ignore_index=True)
Out[330]:
A B C
0 2 3 4
1 5 6 7
2 7 8 9
Generally, it's easiest to append dataframes, not series. In your case, since you want the new row to be "on top" (with starting id), and there is no function pd.prepend()
, I first create the new dataframe and then append your old one.
ignore_index
will ignore the old ongoing index in your dataframe and ensure that the first row actually starts with index 1
instead of restarting with index 0
.
Typical Disclaimer: Cetero censeo ... appending rows is a quite inefficient operation. If you care about performance and can somehow ensure to first create a dataframe with the correct (longer) index and then just inserting the additional row into the dataframe, you should definitely do that. See:
>>> index = np.array([0, 1, 2])
>>> df2 = pd.DataFrame(columns=['A', 'B', 'C'], index=index)
>>> df2.loc[0:1] = [list(s1), list(s2)]
>>> df2
Out[336]:
A B C
0 5 6 7
1 7 8 9
2 NaN NaN NaN
>>> df2 = pd.DataFrame(columns=['A', 'B', 'C'], index=index)
>>> df2.loc[1:] = [list(s1), list(s2)]
So far, we have what you had as df
:
>>> df2
Out[339]:
A B C
0 NaN NaN NaN
1 5 6 7
2 7 8 9
But now you can easily insert the row as follows. Since the space was preallocated, this is more efficient.
>>> df2.loc[0] = np.array([2, 3, 4])
>>> df2
Out[341]:
A B C
0 2 3 4
1 5 6 7
2 7 8 9
found a paper at: http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1924044 that suggests a formula to calculate the downloads:
d_iPad=13,516*rank^(-0.903)
d_iPhone=52,958*rank^(-0.944)
This will be the second question in a row I've answered with this, so I think it's worth pointing out that I have no affiliation with this product, but I use it and love it and think it's the right answer to this question too: DbVisualizer.
Multiple way to iterate object in javascript
Using for...in loop
var p = {_x000D_
"p1": "value1",_x000D_
"p2": "value2",_x000D_
"p3": "value3"_x000D_
};_x000D_
for (let key in p){_x000D_
if(p.hasOwnProperty(key)){_x000D_
console.log(`${key} : ${p[key]}`)_x000D_
}_x000D_
}
_x000D_
Using for...of loop
var p = {_x000D_
"p1": "value1",_x000D_
"p2": "value2",_x000D_
"p3": "value3"_x000D_
};_x000D_
for (let key of Object.keys(p)){_x000D_
console.log(`key: ${key} & value: ${p[key]}`)_x000D_
}
_x000D_
Using forEach() with Object.keys, Object.values, Object.entries
var p = {_x000D_
"p1": "value1",_x000D_
"p2": "value2",_x000D_
"p3": "value3"_x000D_
};_x000D_
Object.keys(p).forEach(key=>{_x000D_
console.log(`${key} : ${p[key]}`);_x000D_
});_x000D_
Object.values(p).forEach(value=>{_x000D_
console.log(value);_x000D_
});_x000D_
Object.entries(p).forEach(([key,value])=>{_x000D_
console.log(`${key}:${value}`)_x000D_
})
_x000D_
If you want to retrieve POST data:
first_name = request.form.get("firstname")
If you want to retrieve GET (query string) data:
first_name = request.args.get("firstname")
Or if you don't care/know whether the value is in the query string or in the post data:
first_name = request.values.get("firstname")
request.values is a CombinedMultiDict that combines Dicts from request.form and request.args.
You have a ; at the end of the if
.
Change:
if (fp == NULL);
return 0;
to
if (fp == NULL)
return 0;
The MyKey class (@Embeddable) should not have any relationships like @ManyToOne
If you look at the documentation for the built-in errors, you'll see that most Exception
classes assign their first argument as a message
attribute. Not all of them do though.
Notably,EnvironmentError
(with subclasses IOError
and OSError
) has a first argument of errno
, second of strerror
. There is no message
... strerror
is roughly analogous to what would normally be a message
.
More generally, subclasses of Exception
can do whatever they want. They may or may not have a message
attribute. Future built-in Exception
s may not have a message
attribute. Any Exception
subclass imported from third-party libraries or user code may not have a message
attribute.
I think the proper way of handling this is to identify the specific Exception
subclasses you want to catch, and then catch only those instead of everything with an except Exception
, then utilize whatever attributes that specific subclass defines however you want.
If you must print
something, I think that printing the caught Exception
itself is most likely to do what you want, whether it has a message
attribute or not.
You could also check for the message attribute if you wanted, like this, but I wouldn't really suggest it as it just seems messy:
try:
pass
except Exception as e:
# Just print(e) is cleaner and more likely what you want,
# but if you insist on printing message specifically whenever possible...
if hasattr(e, 'message'):
print(e.message)
else:
print(e)
The real trick is: Use a Backslash at the end of the target path where to copy the file. The /Y is for overwriting existing files, if you want no warnings.
Example:
xcopy /Y "C:\file\from\here.txt" "C:\file\to\here\"
Take a look on life cycle of Activity
Where
***onCreate()***
Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one. Always followed by onStart().
***onStart()***
Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.
And you can write your simple class to take a look when these methods call
public class TestActivity extends Activity {
/** Called when the activity is first created. */
private final static String TAG = "TestActivity";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i(TAG, "On Create .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onDestroy()
*/
@Override
protected void onDestroy() {
super.onDestroy();
Log.i(TAG, "On Destroy .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onPause()
*/
@Override
protected void onPause() {
super.onPause();
Log.i(TAG, "On Pause .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onRestart()
*/
@Override
protected void onRestart() {
super.onRestart();
Log.i(TAG, "On Restart .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onResume()
*/
@Override
protected void onResume() {
super.onResume();
Log.i(TAG, "On Resume .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onStart()
*/
@Override
protected void onStart() {
super.onStart();
Log.i(TAG, "On Start .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onStop()
*/
@Override
protected void onStop() {
super.onStop();
Log.i(TAG, "On Stop .....");
}
}
Hope this will clear your confusion.
And take a look here for details.
Lifecycle Methods in Details is a very good example and demo application, which is a very good article to understand the life cycle.
What about element.tagName
?
See also tagName
docs on MDN.
You can read your BufferedInputStream like this. It will read data till it reaches end of stream which is indicated by -1.
inputS = new BufferedInputStream(inBS);
byte[] buffer = new byte[1024]; //If you handle larger data use a bigger buffer size
int read;
while((read = inputS.read(buffer)) != -1) {
System.out.println(read);
// Your code to handle the data
}
I don't know if you even need to wrap it. Won't this work?
SELECT COUNT(*), SUM(DATEDIFF(now(),availables.updated_at))
FROM availables
INNER JOIN rooms ON availables.room_id=rooms.id
WHERE availables.bookdate BETWEEN '2009-06-25'
AND date_add('2009-06-25', INTERVAL 4 DAY)
AND rooms.hostel_id = 5094
GROUP BY availables.bookdate);
If your goal is to return both result sets then you'll need to store it some place temporarily.
Simply using an outer directory for the output, solved the problem for me.
sudo tar czf ./../31OCT18.tar.gz ./
you can set PYTHONPATH
, by os.environ['PATHPYTHON']=/some/path
, then you need to call os.system('python')
to restart the python shell to make the newly added path effective.
Is your type really arbitrary? If you know it is just going to be a int float or string you could just do
if val.dtype == float and np.isnan(val):
assuming it is wrapped in numpy , it will always have a dtype and only float and complex can be NaN
If you want to style the output of a data frame in a jupyter notebook cell, you can set the display style on a per-dataframe basis:
df = pd.DataFrame({'A': np.random.randn(4)*1e7})
df.style.format("{:.1f}")
See the documentation here.
The existing answers posted either rely on the CLI utility flock
or do not properly secure the lock file. The flock utility is not available on all non-Linux systems (i.e. FreeBSD), and does not work properly on NFS.
In my early days of system administration and system development, I was told that a safe and relatively portable method of creating a lock file was to create a temp file using mkemp(3)
or mkemp(1)
, write identifying information to the temp file (i.e. PID), then hard link the temp file to the lock file. If the link was successful, then you have successfully obtained the lock.
When using locks in shell scripts, I typically place an obtain_lock()
function in a shared profile and then source it from the scripts. Below is an example of my lock function:
obtain_lock()
{
LOCK="${1}"
LOCKDIR="$(dirname "${LOCK}")"
LOCKFILE="$(basename "${LOCK}")"
# create temp lock file
TMPLOCK=$(mktemp -p "${LOCKDIR}" "${LOCKFILE}XXXXXX" 2> /dev/null)
if test "x${TMPLOCK}" == "x";then
echo "unable to create temporary file with mktemp" 1>&2
return 1
fi
echo "$$" > "${TMPLOCK}"
# attempt to obtain lock file
ln "${TMPLOCK}" "${LOCK}" 2> /dev/null
if test $? -ne 0;then
rm -f "${TMPLOCK}"
echo "unable to obtain lockfile" 1>&2
if test -f "${LOCK}";then
echo "current lock information held by: $(cat "${LOCK}")" 1>&2
fi
return 2
fi
rm -f "${TMPLOCK}"
return 0;
};
The following is an example of how to use the lock function:
#!/bin/sh
. /path/to/locking/profile.sh
PROG_LOCKFILE="/tmp/myprog.lock"
clean_up()
{
rm -f "${PROG_LOCKFILE}"
}
obtain_lock "${PROG_LOCKFILE}"
if test $? -ne 0;then
exit 1
fi
trap clean_up SIGHUP SIGINT SIGTERM
# bulk of script
clean_up
exit 0
# end of script
Remember to call clean_up
at any exit points in your script.
I've used the above in both Linux and FreeBSD environments.
Check this out... I just got this working and it seems exactly what you are trying to do as well.
2 functions. One to select the table and copy it to the clipboard, and the second writes it to excel en masse. Just call write_to_excel() and put in your table id (or modify it to take it as an argument).
function selectElementContents(el) {
var body = document.body, range, sel;
if (document.createRange && window.getSelection) {
range = document.createRange();
sel = window.getSelection();
sel.removeAllRanges();
try {
range.selectNodeContents(el);
sel.addRange(range);
} catch (e) {
range.selectNode(el);
sel.addRange(range);
}
} else if (body.createTextRange) {
range = body.createTextRange();
range.moveToElementText(el);
range.select();
}
range.execCommand("Copy");
}
function write_to_excel()
{
var tableID = "AllItems";
selectElementContents( document.getElementById(tableID) );
var excel = new ActiveXObject("Excel.Application");
// excel.Application.Visible = true;
var wb=excel.WorkBooks.Add();
var ws=wb.Sheets("Sheet1");
ws.Cells(1,1).Select;
ws.Paste;
ws.DrawingObjects.Delete;
ws.Range("A1").Select
excel.Application.Visible = true;
}
Heavily influenced from: Select a complete table with Javascript (to be copied to clipboard)
flex-grow - This defines the ability for a flex item to grow if necessary. It accepts a unitless value that serves as a proportion. It dictates what amount of the available space inside the flex container the item should take up.
If all items have flex-grow set to 1, the remaining space in the container will be distributed equally to all children. If one of the children has a value of 2, the remaining space would take up twice as much space as the others (or it will try to, at least). See more here
.parent {_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
.child {_x000D_
flex-grow: 1; // It accepts a unitless value that serves as a proportion_x000D_
}_x000D_
_x000D_
.left {_x000D_
background: red;_x000D_
}_x000D_
_x000D_
.right {_x000D_
background: green;_x000D_
}
_x000D_
<div class="parent"> _x000D_
<div class="child left">_x000D_
Left 50%_x000D_
</div>_x000D_
<div class="child right">_x000D_
Right 50%_x000D_
</div>_x000D_
</div>
_x000D_
Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)
Here is how the cars.csv file looks.
Print out drives_right column as Series:
print(cars.loc[:,"drives_right"])
US True
AUS False
JAP False
IN False
RU True
MOR True
EG True
Name: drives_right, dtype: bool
The single bracket version gives a Pandas Series, the double bracket version gives a Pandas DataFrame.
Print out drives_right column as DataFrame
print(cars.loc[:,["drives_right"]])
drives_right
US True
AUS False
JAP False
IN False
RU True
MOR True
EG True
Adding a Series to another Series creates a DataFrame.
You could make your own plugins.
jQuery.fn.visible = function() {
return this.css('visibility', 'visible');
};
jQuery.fn.invisible = function() {
return this.css('visibility', 'hidden');
};
jQuery.fn.visibilityToggle = function() {
return this.css('visibility', function(i, visibility) {
return (visibility == 'visible') ? 'hidden' : 'visible';
});
};
If you want to overload the original jQuery toggle()
, which I don't recommend...
!(function($) {
var toggle = $.fn.toggle;
$.fn.toggle = function() {
var args = $.makeArray(arguments),
lastArg = args.pop();
if (lastArg == 'visibility') {
return this.visibilityToggle();
}
return toggle.apply(this, arguments);
};
})(jQuery);
In case any one stumbles upon this as I just have...
Find First blank cell in a column(I'm using column D but didn't want to include D1)
NextFree = Range("D2:D" & Rows.Count).Cells.SpecialCells(xlCellTypeBlanks).Row
Range("D" & NextFree).Select
NextFree is just a name, you could use sausages if you wanted.
To hide both letter e
and minus sign -
just go for:
onkeydown="return event.keyCode !== 69 && event.keyCode !== 189"
The CSS table model is based on the HTML table model http://www.w3.org/TR/CSS21/tables.html
A table is divided into ROWS, and each row contains one or more cells. Cells are children of ROWS, they are NEVER children of columns.
"display: table-column" does NOT provide a mechanism for making columnar layouts (e.g. newspaper pages with multiple columns, where content can flow from one column to the next).
Rather, "table-column" ONLY sets attributes that apply to corresponding cells within the rows of a table. E.g. "The background color of the first cell in each row is green" can be described.
The table itself is always structured the same way it is in HTML.
In HTML (observe that "td"s are inside "tr"s, NOT inside "col"s):
<table ..>
<col .. />
<col .. />
<tr ..>
<td ..></td>
<td ..></td>
</tr>
<tr ..>
<td ..></td>
<td ..></td>
</tr>
</table>
Corresponding HTML using CSS table properties (Note that the "column" divs do not contain any contents -- the standard does not allow for contents directly in columns):
.mytable {_x000D_
display: table;_x000D_
}_x000D_
.myrow {_x000D_
display: table-row;_x000D_
}_x000D_
.mycell {_x000D_
display: table-cell;_x000D_
}_x000D_
.column1 {_x000D_
display: table-column;_x000D_
background-color: green;_x000D_
}_x000D_
.column2 {_x000D_
display: table-column;_x000D_
}
_x000D_
<div class="mytable">_x000D_
<div class="column1"></div>_x000D_
<div class="column2"></div>_x000D_
<div class="myrow">_x000D_
<div class="mycell">contents of first cell in row 1</div>_x000D_
<div class="mycell">contents of second cell in row 1</div>_x000D_
</div>_x000D_
<div class="myrow">_x000D_
<div class="mycell">contents of first cell in row 2</div>_x000D_
<div class="mycell">contents of second cell in row 2</div>_x000D_
</div>_x000D_
</div>
_x000D_
OPTIONAL: both "rows" and "columns" can be styled by assigning multiple classes to each row and cell as follows. This approach gives maximum flexibility in specifying various sets of cells, or individual cells, to be styled:
//Useful css declarations, depending on what you want to affect, include:_x000D_
_x000D_
/* all cells (that have "class=mycell") */_x000D_
.mycell {_x000D_
}_x000D_
_x000D_
/* class row1, wherever it is used */_x000D_
.row1 {_x000D_
}_x000D_
_x000D_
/* all the cells of row1 (if you've put "class=mycell" on each cell) */_x000D_
.row1 .mycell {_x000D_
}_x000D_
_x000D_
/* cell1 of row1 */_x000D_
.row1 .cell1 {_x000D_
}_x000D_
_x000D_
/* cell1 of all rows */_x000D_
.cell1 {_x000D_
}_x000D_
_x000D_
/* row1 inside class mytable (so can have different tables with different styles) */_x000D_
.mytable .row1 {_x000D_
}_x000D_
_x000D_
/* all the cells of row1 of a mytable */_x000D_
.mytable .row1 .mycell {_x000D_
}_x000D_
_x000D_
/* cell1 of row1 of a mytable */_x000D_
.mytable .row1 .cell1 {_x000D_
}_x000D_
_x000D_
/* cell1 of all rows of a mytable */_x000D_
.mytable .cell1 {_x000D_
}
_x000D_
<div class="mytable">_x000D_
<div class="column1"></div>_x000D_
<div class="column2"></div>_x000D_
<div class="myrow row1">_x000D_
<div class="mycell cell1">contents of first cell in row 1</div>_x000D_
<div class="mycell cell2">contents of second cell in row 1</div>_x000D_
</div>_x000D_
<div class="myrow row2">_x000D_
<div class="mycell cell1">contents of first cell in row 2</div>_x000D_
<div class="mycell cell2">contents of second cell in row 2</div>_x000D_
</div>_x000D_
</div>
_x000D_
In today's flexible designs, which use <div>
for multiple purposes, it is wise to put some class on each div, to help refer to it. Here, what used to be <tr>
in HTML became class myrow
, and <td>
became class mycell
. This convention is what makes the above CSS selectors useful.
PERFORMANCE NOTE: putting class names on each cell, and using the above multi-class selectors, is better performance than using selectors ending with *
, such as .row1 *
or even .row1 > *
. The reason is that selectors are matched last first, so when matching elements are being sought, .row1 *
first does *
, which matches all elements, and then checks all the ancestors of each element, to find if any ancestor has class row1
. This might be slow in a complex document on a slow device. .row1 > *
is better, because only the immediate parent is examined. But it is much better still to immediately eliminate most elements, via .row1 .cell1
. (.row1 > .cell1
is an even tighter spec, but it is the first step of the search that makes the biggest difference, so it usually isn't worth the clutter, and the extra thought process as to whether it will always be a direct child, of adding the child selector >
.)
The key point to take away re performance is that the last item in a selector should be as specific as possible, and should never be *
.
Reading the R language documentation, as.integer
has more to do with how the number is stored than if it is practically equivalent to an integer. is.integer
tests if the number is declared as an integer. You can declare an integer by putting a L
after it.
> is.integer(66L)
[1] TRUE
> is.integer(66)
[1] FALSE
Also functions like round
will return a declared integer, which is what you are doing with x==round(x)
. The problem with this approach is what you consider to be practically an integer. The example uses less precision for testing equivalence.
> is.wholenumber(1+2^-50)
[1] TRUE
> check.integer(1+2^-50)
[1] FALSE
So depending on your application you could get into trouble that way.
js
var el = document.getElementById("el");
el.scrollTop = el.scrollHeight - el.scrollTop;
$('#my_select option:selected').attr('id');
put .gitignore in your main catalog
git status (you will see which files you can commit)
git add -A
git commit -m "message"
git push
In case you have an object logged:
Store as a global variable
temp1
copy(temp1)
It might be smart to also just create a new list if the current list item meets the desired criteria.
so:
for item in originalList:
if (item != badValue):
newList.append(item)
and to avoid having to re-code the entire project with the new lists name:
originalList[:] = newList
note, from Python documentation:
copy.copy(x) Return a shallow copy of x.
copy.deepcopy(x) Return a deep copy of x.
Should be probably changed to
firstName = firstName.trim().replaceAll("\\.", "");
I assume that since you're using an XML declaration, you're not worrying about IE or older browsers.
So you can use display:table-cell
and display:table-row
like so:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
.toolbar ul {
display:table-row;
}
.toolbar ul li
{
display: table-cell;
height: 100px;
list-style-type: none;
margin: 10px;
vertical-align: middle;
}
.toolbar ul li a {
display:table-cell;
vertical-align: middle;
height:100px;
border: solid 1px black;
}
.toolbar ul li.button a {
height:50px;
border: solid 1px black;
}
</style>
</head>
<body>
<div class="toolbar">
<ul>
<li><a href="#">first item<br />
first item<br />
first item</a></li>
<li><a href="#">second item</a></li>
<li><a href="#">last item</a></li>
<li class="button"><a href="#">button<br />
button</a></li>
</ul>
</div>
</body>
</html>
Using Following Code You Solve thisQuestion.... If you run a file using localhost server than this problem solve by following Jsp Page Code.This Code put Between Head Tag in jsp file
<style type="text/css">
<%@include file="css/style.css" %>
</style>
<script type="text/javascript">
<%@include file="js/script.js" %>
</script>
My solution is just compilation of best ideas in thread, with a little improvement. I use both dedicated procedure (@Tomasz Borowiec) to facilitate reuse, and exception handling (@Tobias Twardon) to reduce code and to get rid of redundant table name in procedure.
DECLARE
PROCEDURE create_table_if_doesnt_exist(
p_create_table_query VARCHAR2
) IS
BEGIN
EXECUTE IMMEDIATE p_create_table_query;
EXCEPTION
WHEN OTHERS THEN
-- suppresses "name is already being used" exception
IF SQLCODE = -955 THEN
NULL;
END IF;
END;
BEGIN
create_table_if_doesnt_exist('
CREATE TABLE "MY_TABLE" (
"ID" NUMBER(19) NOT NULL PRIMARY KEY,
"TEXT" VARCHAR2(4000),
"MOD_TIME" TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
');
END;
/
By 'the wiz' I'm assuming you're talking about the 'SQL Server Import and Export Wizard'. (I'm also pretty new so I don't understand most questions, much less most answers, but I think I get this one). If so couldn't you take the spreadsheet, or a copy of it, delete the columns you don't want imported and then use the wizard?
I've always found the ability to do what I need with it and I'm only on SQL Server 2000 (not sure how other versions differ).
Edit: In fact I'm looking at it now and I seem to be able to choose which columns I want to map to which rows in an existing table. On the 'Select Source Tables and Views' screen I check the datasheet I'm using, select the 'Destination' then click the 'Edit...' button. From there you can choose the Excel column and the table column to map it to.
winpty works as long as you don't specify volumes to be mounted such as ".:/mountpoint" or "${pwd}:/mountpoint"
The best workaround I have found is to use the git-bash plugin inside Visual Code Studio and use the terminal to start and stop containers or docker-compose.
Sure there's an entity for tabs:
	
(The tab is ASCII character 9, or Unicode U+0009.)
However, just like literal tabs (ones you type in to your text editor), all tab characters are treated as whitespace by HTML parsers and collapsed into a single space except those within a <pre>
block, where literal tabs will be rendered as 8 spaces in a monospace font.
jQuery's .show() and .hide() functions are probably your best bet.
if you're connecting to a postgres database, the following works:
result = cursor.execute(query)
if result.returns_rows:
# we got rows!
return [{k:v for k,v in zip(result.keys(), r)} for r in result.rows]
else:
return None
mailx -a /path/to/file email@address
You might go into interactive mode (it will prompt you with "Subject: " and then a blank line), enter a subject, then enter a body and hit Ctrl+D (EOT) to finish.
ComponentWillReceiveProps()
is going to be deprecated in the future due to bugs and inconsistencies. An alternative solution for re-rendering a component on props change is to use ComponentDidUpdate()
and ShouldComponentUpdate()
.
ComponentDidUpdate()
is called whenever the component updates AND if ShouldComponentUpdate()
returns true (If ShouldComponentUpdate()
is not defined it returns true
by default).
shouldComponentUpdate(nextProps){
return nextProps.changedProp !== this.state.changedProp;
}
componentDidUpdate(props){
// Desired operations: ex setting state
}
This same behavior can be accomplished using only the ComponentDidUpdate()
method by including the conditional statement inside of it.
componentDidUpdate(prevProps){
if(prevProps.changedProp !== this.props.changedProp){
this.setState({
changedProp: this.props.changedProp
});
}
}
If one attempts to set the state without a conditional or without defining ShouldComponentUpdate()
the component will infinitely re-render
Happened to me today.
My issue was that I had too many tabs open (I didn't know they were open) with source code on them.
If you close all the tabs, maybe you will unconfuse IntelliJ into indexing the dependencies correctly
$('select').val() // Get's the value
$('select option:selected').val() ; // Get's the value
$('select').find('option:selected').val() ; // Get's the value
$('select option:selected').text() // Gets you the text of the selected option
I have created a user specific ssh-config, so my user automatically logs in with the correct credentials and key.
First I needed to generate an key-pair
ssh-keygen -t rsa -b 4096 -C "[email protected]"
and saved it to e.g ~/.ssh/id_my_domain
. Note that this is also the keypair (private and public) I've connected to my Github account, so mine is stored in~/.ssh/id_github_com
.
I have then created (or altered) a file called ~/.ssh/config
with an entry:
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_github_com
On another server, the "ssh-url" is [email protected]:username/private-repo.git
and the entry for this server would have been:
Host domain.com
HostName domain.com
User admin
IdentityFile ~/.ssh/id_domain_com
Just to clarify that you need ensure that the User
, Host
and HostName
is set correctly.
Now I can just browse into the go path and then go get <package>
, e.g go get main
where the file main/main.go
includes the package (from last example above) domain.com:username/private-repo.git
.
Brother this piece of code is not a solution just change it to
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args){
if (args.get_error() != undefined){
**alert(args.get_error().message.substr(args.get_error().name.length + 2));**
args.set_errorHandled(true);
}
}
</script>
and you will see the error is there but you are just not throwing it on UI.
New to the python world!
I need a System Time independent Stopwatch so I did translate my old C++ class into Python:
from ctypes.wintypes import DWORD
import win32api
import datetime
class Stopwatch:
def __init__(self):
self.Restart()
def Restart(self):
self.__ulStartTicks = DWORD(win32api.GetTickCount()).value
def ElapsedMilliSecs(self):
return DWORD(DWORD(win32api.GetTickCount()).value-DWORD(self.__ulStartTicks).value).value
def ElapsedTime(self):
return datetime.timedelta(milliseconds=self.ElapsedMilliSecs())
This has no 49 days run over issue due to DWORD math but NOTICE that GetTickCount
has about 15 milliseconds granularity so do not use this class if your need 1-100 milliseconds elapsed time ranges.
Any improvement or feedback is welcome!
Thanks,Bruno for giving me heads up on Common Name and Subject Alternative Name. As we figured out certificate was generated with CN with DNS name of network and asked for regeneration of new certificate with Subject Alternative Name entry i.e. san=ip:10.0.0.1. which is the actual solution.
But, we managed to find out a workaround with which we can able to run on development phase. Just add a static block in the class from which we are making ssl connection.
static {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier()
{
public boolean verify(String hostname, SSLSession session)
{
// ip address of the service URL(like.23.28.244.244)
if (hostname.equals("23.28.244.244"))
return true;
return false;
}
});
}
If you happen to be using Java 8, there is a much slicker way of achieving the same result:
static {
HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> hostname.equals("127.0.0.1"));
}
create shake.xml in anim folder
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="0"
android:toXDelta="10"
android:duration="1000"
android:interpolator="@anim/cycle" />
and cycle.xml in anim folder
<?xml version="1.0" encoding="utf-8"?>
<cycleInterpolator xmlns:android="http://schemas.android.com/apk/res/android"
android:cycles="4" />
now add animation on your code
Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
anyview.startAnimation(shake);
If you want vertical animation, change fromXdelta and toXdelta value to fromYdelta and toYdelta value
Seems you need to use JToggleButton
:
JToggleButton tb = new JToggleButton("push me");
tb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JToggleButton btn = (JToggleButton) e.getSource();
btn.setText(btn.isSelected() ? "pushed" : "push me");
}
});
Working example here at : http://jsfiddle.net/tQ2CZ/1/
HTML
<div id="video_container">
<video poster="http://media.w3.org/2010/05/sintel/poster.png" preload="none" controls="" id="video" tabindex="0">
<source type="video/mp4" src="http://media.w3.org/2010/05/sintel/trailer.mp4" id="mp4"></source>
<source type="video/webm" src="http://media.w3.org/2010/05/sintel/trailer.webm" id="webm"></source>
<source type="video/ogg" src="http://media.w3.org/2010/05/sintel/trailer.ogv" id="ogv"></source>
<p>Your user agent does not support the HTML5 Video element.</p>
</video>
</div>
<div>Current Time : <span id="currentTime">0</span></div>
<div>Total time : <span id="totalTime">0</span></div>
JS
$(function(){
$('#currentTime').html($('#video_container').find('video').get(0).load());
$('#currentTime').html($('#video_container').find('video').get(0).play());
})
setInterval(function(){
$('#currentTime').html($('#video_container').find('video').get(0).currentTime);
$('#totalTime').html($('#video_container').find('video').get(0).duration);
},500)
If we just do x.append(y)
, y gets referenced into x such that any changes made to y will affect appended x as well. So if we need to insert only elements, we should do following:
x = [1,2,3]
y = [4,5,6]
x.append(y[:])
This is how I have achieved it using purely CSS and HTML (no JavaScript/images etc.).
It gracefully degrades in most browsers (I do need to add in a fix for lack of last-of-type in < IE9).
Do you understand the concept of casting? Casting is the process of type conversion, which is in Java very common because its a statically typed language. Some examples:
Cast the String "1" to an int -> no problem
Cast the String "abc" to an int -> raises a ClassCastException
Or think of a class diagram with Animal.class, Dog.class and Cat.class
Animal a = new Dog();
Dog d = (Dog) a; // No problem, the type animal can be casted to a dog, because its a dog.
Cat c = (Dog) a; // Raises class cast exception; you can't cast a dog to a cat.
//for update
(from x in dataBase.Customers
where x.Name == "Test"
select x).ToList().ForEach(xx => xx.Name="New Name");
//for delete
dataBase.Customers.RemoveAll(x=>x.Name=="Name");
For concatenating it's:
input[name="Sex"][value="M"] {}
And for taking union it's:
input[name="Sex"], input[value="M"] {}
No. There is no way you can edit the result grid. The result grid is mainly for displaying purposes of the query you executed.
This for the reason that anybody can execute complex queries. Hopefully for the next release they will include this kind of functionality.
I Hope that answer your question.
Try the following to see if you have the proper repository installed:
# yum search java | grep 'java-'
This is going to return a list of available packages that have java in the title. Specifically we are interested in the java- anything, as the jdk will typically be in 'java-version#' type format... Anyhow, if you have to install a repo look at Dag Wieers repo:
http://dag.wieers.com/rpm/FAQ.php#B
After you've got it installed try yum search again... This time you'll have a bunch of java stuff.
# yum search java | grep 'java-'
This will return the list of the available java packages. You can install one like this:
# yum install java-1.7.0-openjdk.x86_64
No need to use a macro. Supposing your first string is in A1.
=RIGHT(A1, 4)
Drag this down and you will get your four last characters.
Edit: To be sure, if you ever have sequences like 'ABC DEF' and want the last four LETTERS and not CHARACTERS you might want to use trimspaces()
=RIGHT(TRIMSPACES(A1), 4)
Edit: As per brettdj's suggestion, you may want to check that your string is actually 4-character long or more:
=IF(TRIMSPACES(A1)>=4, RIGHT(TRIMSPACES(A1), 4), TRIMSPACES(A1))
Yes, quite straight forward:
Private _name As String
Public Property Name() As String
Get
Return _name
End Get
Private Set(ByVal value As String)
_name = value
End Set
End Property
As a slight improvement over the other answers, you can do the mkdir
and chmod
as a single operation using mkdir
's -m
switch.
$ mkdir -m 700 ${HOME}/.ssh
From a Linux system
$ mkdir --help
Usage: mkdir [OPTION]... DIRECTORY...
Create the DIRECTORY(ies), if they do not already exist.
Mandatory arguments to long options are mandatory for short options too.
-m, --mode=MODE set file mode (as in chmod), not a=rwx - umask
...
...
SELECT CONVERT(NVARCHAR(10), PaymentDate, 120) [Month], SUM(Amount) [TotalAmount]
FROM Payments
GROUP BY CONVERT(NVARCHAR(10), PaymentDate, 120)
ORDER BY [Month]
You could also try:
SELECT DATEPART(Year, PaymentDate) Year, DATEPART(Month, PaymentDate) Month, SUM(Amount) [TotalAmount]
FROM Payments
GROUP BY DATEPART(Year, PaymentDate), DATEPART(Month, PaymentDate)
ORDER BY Year, Month
According to new Swift 2.0 we should use do try catch. The code would look like this:
var badumSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("BadumTss", ofType: "mp3"))
var audioPlayer = AVAudioPlayer()
do {
player = try AVAudioPlayer(contentsOfURL: badumSound)
} catch {
print("No sound found by URL:\(badumSound)")
}
player.prepareToPlay()
Good working example here: http://jsfiddle.net/MrTest/t4NXD/62/
Plus:
fade in / fade out
animation:hover
Tested and working!
You Can use Follow code Textbox Keypress Event:
Private Sub txtbox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtbox1.KeyPress
Try
If Val(txtbox1.text) < 10 Then
If Char.IsLetterOrDigit(e.KeyChar) = False And Char.IsControl(e.KeyChar) = False Then
e.Handled = True
End If
Else
e.Handled = True
End If
Catch ex As Exception
ShowException(ex.Message, MESSAGEBOX_TITLE, ex)
End Try
End Sub
This code allow numbers only and you can enter only number between 1 to 10.
You can use the :not
filter selector:
$('foo:not(".someClass")')
Or not()
method:
$('foo').not(".someClass")
More Info:
For me, the only way on SQL 2008 R2 was this :
EXEC sp_configure 'Show Advanced Options', 1
RECONFIGURE **WITH OVERRIDE**
EXEC sp_configure 'xp_cmdshell', 1
RECONFIGURE **WITH OVERRIDE**
The problem is in this line:
with pattern.findall(row) as f:
You are using the with
statement. It requires an object with __enter__
and __exit__
methods. But pattern.findall
returns a list
, with
tries to store the __exit__
method, but it can't find it, and raises an error. Just use
f = pattern.findall(row)
instead.
LENGTH()
does return the string length (just verified). I suppose that your data is padded with blanks - try
SELECT typ, LENGTH(TRIM(t1.typ))
FROM AUTA_VIEW t1;
instead.
As OraNob
mentioned, another cause could be that CHAR
is used in which case LENGTH()
would also return the column width, not the string length. However, the TRIM()
approach also works in this case.
sed -n '16224,16482p' < dump.sql
Content-Type: application/json
is just the content header. The content header is just information about the type of returned data, ex::JSON,image(png,jpg,etc..),html.
Keep in mind, that JSON in JavaScript is an array or object. If you want to see all the data, use console.log instead of alert:
alert(response.text); // Will alert "[object Object]" string
console.log(response.text); // Will log all data objects
If you want to alert the original JSON content as a string, then add single quotation marks ('):
echo "'" . json_encode(array('text' => 'omrele')) . "'";
// alert(response.text) will alert {"text":"omrele"}
Do not use double quotes. It will confuse JavaScript, because JSON uses double quotes on each value and key:
echo '<script>var returndata=';
echo '"' . json_encode(array('text' => 'omrele')) . '"';
echo ';</script>';
// It will return the wrong JavaScript code:
<script>var returndata="{"text":"omrele"}";</script>
Here's the calling order:
app.config()
app.run()
app.controller()
Here's a simple demo where you can watch each one executing (and experiment if you'd like).
From Angular's module docs:
Run blocks - get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time.
Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the services have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.
One situation where run blocks are used is during authentications.
From the documentation:
In order to execute a command and have it not hang your PHP script while
it runs, the program you run must not output back to PHP. To do this,
redirect both stdout and stderr to /dev/null, then background it.
> /dev/null 2>&1 &
In order to execute a command and have
it spawned off as another process that
is not dependent on the Apache thread
to keep running (will not die if
somebody cancels the page) run this:
exec('bash -c "exec nohup setsid your_command > /dev/null 2>&1 &"');
I got this error when I tried to set a column as unique when there was already duplicate data in the column OR if you try to add a column and set it as unique when there is already data in the table.
I had a table with 5 rows and I tried to add a unique column and it failed because all 5 of those rows would be empty and thus not unique.
I created the column without the unique index set, then populated the data then set it as unique and everything worked.
The keys are not shuffled or renumbered. The unset()
key is simply removed and the others remain.
$a = array(1,2,3,4,5);
unset($a[2]);
print_r($a);
Array
(
[0] => 1
[1] => 2
[3] => 4
[4] => 5
)
Setting export SSL_CERT_FILE=/path/file.crt
should do the job.
your problem might not be related to any local or global scope for that matter just the server delay between the "success" function executing and the time you are trying to take out data from your variable.
chances are you are trying to print the contents of the variable before the ajax "success" function fires.
If you want one line:
list_of_dict = [{} for i in range(list_len)]
declare @interval tinyint
set @interval = 30
select dateadd(minute,(datediff(minute,0,[DateInsert])/@interval)*@interval,0), sum(Value_Transaction)
from Transactions
group by dateadd(minute,(datediff(minute,0,[DateInsert])/@interval)*@interval,0)
--ORACLE SQL EXAMPLE
SELECT
SYSDATE
,TO_DATE(SUBSTR(LAST_DAY(ADD_MONTHS(SYSDATE, -1)),1,10),'YYYY-MM-DD')
FROM DUAL
The legacy solution, before 1.6, was to use .attr
and handle the returned value as a bool
. The main problem is that the returned type of .attr
has changed to string
, and therefore the comparison with == true
is broken (see http://jsfiddle.net/2vene/1/ (and switch the jquery-version)).
With 1.6 .prop
was introduced, which returns a bool
.
Nevertheless, I suggest to use .is()
, as the returned type is intrinsically bool
, like:
$('#dropUnit').is(':disabled');
$('#dropUnit').is(':enabled');
Furthermore .is()
is much more natural (in terms of "natural language") and adds more conditions than a simple attribute-comparison (eg: .is(':last')
, .is(':visible')
, ... please see documentation on selectors).
Another option is to use a ToggleButton with null background and a custom button.
Bellow an example that includes a selector to the text color as well.
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/toggle_selector"
android:background="@null"
android:paddingLeft="10dp"
android:layout_centerHorizontal="true"
android:gravity="center"
android:textColor="@drawable/toggle_text"
android:textOn="My on state"
android:textOff="My off state" />
toggle_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_checked="true"
android:drawable="@drawable/state_on" />
<item
android:drawable="@drawable/state_off" />
</selector>
toggle_text.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_checked="true"
android:color="@color/app_color" />
<item
android:color="@android:color/darker_gray" />
</selector>
The need for pointers in C language is described here
The basic idea is that many limitations in the language (like using arrays, strings and modifying multiple variables in functions) could be removed by manipulating with the memory location of the data. To overcome these limitations, pointers were introduced in C.
Further, it is also seen that using pointers, you can run your code faster and save memory in cases where you are passing big data types (like a structure with many fields) to a function. Making a copy of such data types before passing would take time and would consume memory. This is another reason why programmers prefer pointers for big data types.
PS: Please refer the link provided for detailed explanation with sample code.
Regex for remove white space
\s+
var str = "Visit Microsoft!";
var res = str.replace(/\s+/g, "");
console.log(res);
_x000D_
or
[ ]+
var str = "Visit Microsoft!";
var res = str.replace(/[ ]+/g, "");
console.log(res);
_x000D_
Remove all white space at begin of string
^[ ]+
var str = " Visit Microsoft!";
var res = str.replace(/^[ ]+/g, "");
console.log(res);
_x000D_
remove all white space at end of string
[ ]+$
var str = "Visit Microsoft! ";
var res = str.replace(/[ ]+$/g, "");
console.log(res);
_x000D_
Without using any libraries:
std::string YourClass::Uppercase(const std::string & Text)
{
std::string UppperCaseString;
UppperCaseString.reserve(Text.size());
for (std::string::const_iterator it=Text.begin(); it<Text.end(); ++it)
{
UppperCaseString.push_back(((0x60 < *it) && (*it < 0x7B)) ? (*it - static_cast<char>(0x20)) : *it);
}
return UppperCaseString;
}
I'd suggest following a few debugging steps.
First run the query directly against the DB. Confirm it is bringing results back. Even with something as simple as this you can find you've made a mistake, or the table is empty, or somesuch oddity.
If the above is ok, then try looping and echoing out the contents of $row just directly into the HTML to see what you've getting back in the mysql_query - see if it matches what you got directly in the DB.
If your data is output onto the page, then look at what's going wrong in your HTML formatting.
However, if nothing is output from $row
, then figure out why the mysql_query isn't working e.g. does the user have permission to query that DB, do you have an open DB connection, can the webserver connect to the DB etc [something on these lines can often be a gotcha]
Changing your query slightly to
$sql = mysql_query("SELECT username FROM users") or die(mysql_error());
may help to highlight any errors: php manual
I prefer going the long route. These are the checks I follow to avoid using a try-except clause -
Here, DATA
is the suspect variable -
DATA is not None and isinstance(DATA, pd.DataFrame) and not DATA.empty
intent.getAction().equals(SMS_RECEIVED)
I have tried it out successfully.
Well, by IP is faster.
Basically, when you call by server name, it is converted to original IP.
But it would be difficult to memorize an IP, for this reason the domain name was created.
Personally I use http://localhost
instead of http://127.0.0.1
or http://username
.
You may refer to: How to deal with "refusing to merge unrelated histories" error:
$ git pull --allow-unrelated-histories
$ git push -f origin master
I tried some of the supplied answers but none of them seemed to work. Then I tried this:
new webpack.ProvidePlugin({
'window.jQuery' : 'jquery',
'window.$' : 'jquery',
'jQuery' : 'jquery',
'$' : 'jquery'
});
Seems to work no matter which version I'm using
Here's some succinct Powershell code to apply new permissions to a folder by modifying it's existing ACL (Access Control List).
# Get the ACL for an existing folder
$existingAcl = Get-Acl -Path 'C:\DemoFolder'
# Set the permissions that you want to apply to the folder
$permissions = $env:username, 'Read,Modify', 'ContainerInherit,ObjectInherit', 'None', 'Allow'
# Create a new FileSystemAccessRule object
$rule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $permissions
# Modify the existing ACL to include the new rule
$existingAcl.SetAccessRule($rule)
# Apply the modified access rule to the folder
$existingAcl | Set-Acl -Path 'C:\DemoFolder'
Each of the values in the $permissions
variable list pertain to the parameters of this constructor for the FileSystemAccessRule class.
Courtesy of this page.