If you try a lot of these answers out on different resolutions, computers with multiple monitors, etc. you may find that they don't work reliably. This is because you need to use a transform to get the mouse position relative to the current screen, not the entire viewing area which consists of all your monitors. Something like this...(where "this" is a WPF window).
var transform = PresentationSource.FromVisual(this).CompositionTarget.TransformFromDevice;
var mouse = transform.Transform(GetMousePosition());
public System.Windows.Point GetMousePosition()
{
var point = Forms.Control.MousePosition;
return new Point(point.X, point.Y);
}
Just use the float style. Put your google map iframe in a div class, and the paragraph in another div class, then apply the following CSS styles to those div classes(don't forget to clear the blocks after float effect, to not make the blocks trouble below them):
css
.google_map{
width:55%;
margin-right:2%;
float: left;
}
.google_map iframe{
width:100%;
}
.paragraph {
width:42%;
float: left;
}
.clearfix{
clear:both
}
html
<div class="google_map">
<iframe></iframe>
</div>
<div class="paragraph">
<p></p>
</div>
<div class="clearfix"></div>
With Help from here
function get_result(some_value) {
var ret_val = {};
$.ajax({
url: '/some/url/to/fetch/from',
type: 'GET',
data: {'some_key': some_value},
async: false,
dataType: 'json'
}).done(function (response) {
ret_val = response;
}).fail(function (jqXHR, textStatus, errorThrown) {
ret_val = null;
});
return ret_val;
}
Hope this helps someone somewhere a bit.
I came across this post while looking to solve a similar problem. I was trying to find the age of an animal in units of Years, Months, Weeks, and Days. Those values are then displayed in SpinEdits where the user can manually change the values to find/estimate a birth date. When my form was passed a birth date from a month with less than 31 days, the value calculated was 1 day off. I based my solution off of Ic's answer above.
Main calculation method that is called after my form loads.
birthDateDisplay.Text = birthDate.ToString("MM/dd/yyyy");
DateTime currentDate = DateTime.Now;
Int32 numOfDays = 0;
Int32 numOfWeeks = 0;
Int32 numOfMonths = 0;
Int32 numOfYears = 0;
// changed code to follow this model http://stackoverflow.com/posts/1083990/revisions
//years
TimeSpan diff = currentDate - birthDate;
numOfYears = diff.Days / 366;
DateTime workingDate = birthDate.AddYears(numOfYears);
while (workingDate.AddYears(1) <= currentDate)
{
workingDate = workingDate.AddYears(1);
numOfYears++;
}
//months
diff = currentDate - workingDate;
numOfMonths = diff.Days / 31;
workingDate = workingDate.AddMonths(numOfMonths);
while (workingDate.AddMonths(1) <= currentDate)
{
workingDate = workingDate.AddMonths(1);
numOfMonths++;
}
//weeks and days
diff = currentDate - workingDate;
numOfWeeks = diff.Days / 7; //weeks always have 7 days
// if bday month is same as current month and bday day is after current day, the date is off by 1 day
if(DateTime.Now.Month == birthDate.Month && DateTime.Now.Day < birthDate.Day)
numOfDays = diff.Days % 7 + 1;
else
numOfDays = diff.Days % 7;
// If the there are fewer than 31 days in the birth month, the date calculated is 1 off
// Dont need to add a day for the first day of the month
int daysInMonth = 0;
if ((daysInMonth = DateTime.DaysInMonth(birthDate.Year, birthDate.Month)) != 31 && birthDate.Day != 1)
{
startDateforCalc = DateTime.Now.Date.AddDays(31 - daysInMonth);
// Need to add 1 more day if it is a leap year and Feb 29th is the date
if (DateTime.IsLeapYear(birthDate.Year) && birthDate.Day == 29)
startDateforCalc = startDateforCalc.AddDays(1);
}
yearsSpinEdit.Value = numOfYears;
monthsSpinEdit.Value = numOfMonths;
weeksSpinEdit.Value = numOfWeeks;
daysSpinEdit.Value = numOfDays;
And then, in my spinEdit_EditValueChanged event handler, I calculate the new birth date starting from my startDateforCalc based on the values in the spin edits. (SpinEdits are constrained to only allow >=0)
birthDate = startDateforCalc.Date.AddYears(-((Int32)yearsSpinEdit.Value)).AddMonths(-((Int32)monthsSpinEdit.Value)).AddDays(-(7 * ((Int32)weeksSpinEdit.Value) + ((Int32)daysSpinEdit.Value)));
birthDateDisplay.Text = birthDate.ToString("MM/dd/yyyy");
I know its not the prettiest solution, but it seems to be working for me for all month lengths and years.
Using both is an important part of application delivery testing. I am only beginning to get involved with Docker and thinking very hard about an application team that has terrible complexity in building and delivering its software. Think of a classic Phoenix Project / Continuous Delivery situation.
The thinking goes something like this:
This seems to be the logical extension of Mitchell's statement that Vagrant is for development combined with Farley/Humbles thinking in Continuous Delivery. If I, as a developer, can shrink the feedback loop on integration testing and application delivery, higher quality and better work environments will follow.
The fact that as a developer I am constantly and consistently delivering containers to the VM and testing the application more holistically means that production releases will be further simplified.
So I see Vagrant evolving as a way of leveraging some of the awesome consequences Docker will have for app deployment.
Adding a few more points to Jason's Answer :
For taking all user provided arguments : user_args = sys.argv[1:]
Consider the sys.argv as a list of strings as (mentioned by Jason). So all the list manipulations will apply here. This is called "List Slicing". For more info visit here.
The syntax is like this : list[start:end:step]. If you omit start, it will default to 0, and if you omit end, it will default to length of list.
Suppose you only want to take all the arguments after 3rd argument, then :
user_args = sys.argv[3:]
Suppose you only want the first two arguments, then :
user_args = sys.argv[0:2] or user_args = sys.argv[:2]
Suppose you want arguments 2 to 4 :
user_args = sys.argv[2:4]
Suppose you want the last argument (last argument is always -1, so what is happening here is we start the count from back. So start is last, no end, no step) :
user_args = sys.argv[-1]
Suppose you want the second last argument :
user_args = sys.argv[-2]
Suppose you want the last two arguments :
user_args = sys.argv[-2:]
Suppose you want the last two arguments. Here, start is -2, that is second last item and then to the end (denoted by ":") :
user_args = sys.argv[-2:]
Suppose you want the everything except last two arguments. Here, start is 0 (by default), and end is second last item :
user_args = sys.argv[:-2]
Suppose you want the arguments in reverse order :
user_args = sys.argv[::-1]
Hope this helps.
Thank you for posting the realWidth function above, it really helped me. Based on "realWidth" function above, I wrote, a CSS reset, (reason described below).
function getUnvisibleDimensions(obj) {
if ($(obj).length == 0) {
return false;
}
var clone = obj.clone();
clone.css({
visibility:'hidden',
width : '',
height: '',
maxWidth : '',
maxHeight: ''
});
$('body').append(clone);
var width = clone.outerWidth(),
height = clone.outerHeight();
clone.remove();
return {w:width, h:height};
}
"realWidth" gets the width of an existing tag. I tested this with some image tags. The problem was, when the image has given CSS dimension per width (or max-width), you will never get the real dimension of that image. Perhaps, the img has "max-width: 100%", the "realWidth" function clone it and append it to the body. If the original size of the image is bigger than the body, then you get the size of the body and not the real size of that image.
Change
private void Form1_Load(object sender, EventArgs e)
{
CERas.CERAS = new CERas.CERAS();
}
to
private void Form1_Load(object sender, EventArgs e)
{
CERas.CERAS c = new CERas.CERAS();
}
Or if you wish to use it later again
change it to
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WinApp_WMI2
{
public partial class Form1 : Form
{
CERas.CERAS m_CERAS;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
m_CERAS = new CERas.CERAS();
}
}
}
Suppose your application has package name as com.company.myproject
. Then you can set the logging level for classes inside your project as given below in application.properties files
logging.level.com.company.myproject = DEBUG
logging.level.org.springframework.web = DEBUG
and logging.level.org.hibernate = DEBUG
will set logging level for classes of Spring framework web and Hibernate only.
For setting the logging file location use
logging.file = /home/ubuntu/myproject.log
Coming here from first Google hit:
You can turn off the behavior AND and warning by exporting GIT_DISCOVERY_ACROSS_FILESYSTEM=1
.
On heroku, if you heroku config:set GIT_DISCOVERY_ACROSS_FILESYSTEM=1
the warning will go away.
It's probably because you are building a gem from source and the gemspec shells out to git
, like many do today. So, you'll still get the warning fatal: Not a git repository (or any of the parent directories): .git
but addressing that is for another day :)
My answer is a duplicate of: - comment GIT_DISCOVERY_ACROSS_FILESYSTEM problem when working with terminal and MacFusion
Google already published a guide on optimization of PHP and the conclusion was:
No getter and setter Optimizing PHP
And no, you must not use magic methods. For PHP, Magic Method are evil. Why?
PHP is not Java, C++, or C#. PHP is different and plays with different roles.
Problems with the stack frames could indicate stack corruption (a truely horrible beast), optimisation, or mixing frameworks such as C/C++/C#/Delphi and other craziness as that - there is no absolute standard with respect to stack frames. (Some languages do not even have them!).
So, I suggest getting slightly annoyed with the stack frame issues, ignoring it, and then just use Remy's answer.
A pure javascript solution (without jQuery
):
const SEARCH_DELAY = 100; // in ms
// it may run indefinitely. TODO: make it cancellable, using Promise's `reject`
function waitForElementToBeAdded(cssSelector) {
return new Promise((resolve) => {
const interval = setInterval(() => {
if (element = document.querySelector(cssSelector)) {
clearInterval(interval);
resolve(element);
}
}, SEARCH_DELAY);
});
}
console.log(await waitForElementToBeAdded('#main'));
I followed clone45's answer all the way to the end. A great article! Since I needed the FTP access to install plug-ins to one of my wordpress sites, I changed the home directory to /var/www/mysitename. Then I continued to add my ftp user to the apache(or www) group like this:
sudo usermod -a -G apache myftpuser
After this I still saw this error on WP's plugin installation page: "Unable to locate WordPress Content directory (wp-content)". Searched and found this solution on a wp.org Q&A session: https://wordpress.org/support/topic/unable-to-locate-wordpress-content-directory-wp-content and added the following to the end of wp-config.php:
if(is_admin()) {
add_filter('filesystem_method', create_function('$a', 'return "direct";' ));
define( 'FS_CHMOD_DIR', 0751 );
}
After this my WP plugin was installed successfully.
You may also try standard sql un-pivoting method by using a sequence of logic with the following code.. The following code has 3 steps:
remove any null combinations ( if exists, table expression can be fully avoided if there are strictly no null values in base table)
select *
from
(
select name, subject,
case subject
when 'Maths' then maths
when 'Science' then science
when 'English' then english
end as Marks
from studentmarks
Cross Join (values('Maths'),('Science'),('English')) AS Subjct(Subject)
)as D
where marks is not null;
@blytung Has a nice function to replace that function
<?php
$url = "http://www.example.org/";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$contents = curl_exec($ch);
if (curl_errno($ch)) {
echo curl_error($ch);
echo "\n<br />";
$contents = '';
} else {
curl_close($ch);
}
if (!is_string($contents) || !strlen($contents)) {
echo "Failed to get contents.";
$contents = '';
}
echo $contents;
?>
Another way, without using a single cast.
(For people who use JPA 2.0, where no casting is allowed)
select col from yourtable
order by length(col),col
EDIT: only works for positive integers
Assuming SQL Server 2000, the following StackOverflow question should address your problem.
If using SQL Server 2005/2008, you can use the following code (taken from here):
select cast(replace(cast(myntext as nvarchar(max)),'find','replace') as ntext)
from myntexttable
If you want to format the output on your own, simply add another loop (foreach) to iterate through the contents of the current row:
while ($row = mysql_fetch_array($result)) {
foreach ($row as $columnName => $columnData) {
echo 'Column name: ' . $columnName . ' Column data: ' . $columnData . '<br />';
}
}
Or if you don't care about the formatting, use the print_r function recommended in the previous answers.
while ($row = mysql_fetch_array($result)) {
echo '<pre>';
print_r ($row);
echo '</pre>';
}
print_r() prints only the keys and values of the array, opposed to var_dump() whichs also prints the types of the data in the array, i.e. String, int, double, and so on. If you do care about the data types - use var_dump() over print_r().
If you don't need the code to be portable to old unices, you can use clock_gettime(), which will give you the time in nanoseconds (if your processor supports that resolution). It's POSIX, but from 2001.
Really it comes down to what you want the query to do. If you mean an exact match then use =. If you mean a fuzzier match, then use LIKE. Saying what you mean is usually a good policy with code.
The poor mans compromise solution is to use a simplistic multi signature approach.
For Example the DBA sets the applications database password to a 50 character random string. TAKqWskc4ncvKaJTyDcgAHq82X7tX6GfK2fc386bmNw3muknjU
He or she give half the password to the application developer who then hard codes it into the java binary.
private String pass1 = "TAKqWskc4ncvKaJTyDcgAHq82"
The other half of the password is passed as a command line argument. the DBA gives pass2 to the system support or admin person who either enters it a application start time or puts it into the automated application start up script.
java -jar /myapplication.jar -pass2 X7tX6GfK2fc386bmNw3muknjU
When the application starts it uses pass1 + pass2 and connects to the database.
This solution has many advantages with out the downfalls mentioned.
You can safely put half the password in a command line arguments as reading it wont help you much unless you are the developer who has the other half of the password.
The DBA can also still change the second half of the password and the developer need not have to re-deploy the application.
The source code can also be semi public as reading it and the password will not give you application access.
You can further improve the situation by adding restrictions on the IP address ranges the database will accept connections from.
The documentation says that these two methods are equivalent:
StreamReader.Close: This implementation of Close calls the Dispose method passing a true value.
StreamWriter.Close: This implementation of Close calls the Dispose method passing a true value.
Stream.Close: This method calls Dispose, specifying true to release all resources.
So, both of these are equally valid:
/* Option 1, implicitly calling Dispose */
using (StreamWriter writer = new StreamWriter(filename)) {
// do something
}
/* Option 2, explicitly calling Close */
StreamWriter writer = new StreamWriter(filename)
try {
// do something
}
finally {
writer.Close();
}
Personally, I would stick with the first option, since it contains less "noise".
Note that I don't recommend a fixed IP for containers in Docker unless you're doing something that allows routing from outside to the inside of your container network (e.g. macvlan). DNS is already there for service discovery inside of the container network and supports container scaling. And outside the container network, you should use exposed ports on the host. With that disclaimer, here's the compose file you want:
version: '2'
services:
mysql:
container_name: mysql
image: mysql:latest
restart: always
environment:
- MYSQL_ROOT_PASSWORD=root
ports:
- "3306:3306"
networks:
vpcbr:
ipv4_address: 10.5.0.5
apigw-tomcat:
container_name: apigw-tomcat
build: tomcat/.
ports:
- "8080:8080"
- "8009:8009"
networks:
vpcbr:
ipv4_address: 10.5.0.6
depends_on:
- mysql
networks:
vpcbr:
driver: bridge
ipam:
config:
- subnet: 10.5.0.0/16
gateway: 10.5.0.1
A very easy solution to this problem is to do this.
<ul>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'index.php'){echo 'current'; }else { echo ''; } ?>"><a href="index.php">Home</a></li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'portfolio.php'){echo 'current'; }else { echo ''; } ?>"><a href="portfolio.php">Portfolio</a></li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'services.php'){echo 'current'; }else { echo ''; } ?>"><a href="services.php">Services</a></li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'contact.php'){echo 'current'; }else { echo ''; } ?>"><a href="contact.php">Contact</a></li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'links.php'){echo 'current'; }else { echo ''; } ?>"><a href="links.php">Links</a></li>
</ul>
Which will output
<ul>
<li class="current"><a href="index.php">Home</a></li>
<li class=""><a href="portfolio.php">Portfolio</a></li>
<li class=""><a href="services.php">Services</a></li>
<li class=""><a href="contact.php">Contact</a></li>
<li class=""><a href="links.php">Links</a></li>
</ul>
Just for completeness, another way is std::string(&v[0])
(although you need to ensure your string is null-terminated and std::string(v.data())
is generally to be preferred.
The difference is that you can use the former technique to pass the vector to functions that want to modify the buffer, which you cannot do with .data().
use myString.c_str()
if you want a c-like string (const char*
) to use with printf
thanks
First of all, your selector is overkill. I suggest using a class or ID selector like my example below. Once you've corrected your selector, simply use jQuery's .each() to iterate through the collection:
ID Selector:
$('#mytable td').each(function() {
var cellText = $(this).html();
});
Class Selector:
$('.myTableClass td').each(function() {
var cellText = $(this).html();
});
Additional Information:
Take a look at jQuery's selector docs.
Case 1 : Yes, this works fine.
Case 2 : This will fail with the error ORA-01441 : cannot decrease column length because some value is too big.
Share and enjoy.
You will certainly have to use both STR_TO_DATE
to convert your date to a MySQL standard date format, and UNIX_TIMESTAMP
to get the timestamp from it.
Given the format of your date, something like
UNIX_TIMESTAMP(STR_TO_DATE(Sales.SalesDate, '%M %e %Y %h:%i%p'))
Will gives you a valid timestamp. Look the STR_TO_DATE
documentation to have more information on the format string.
The "input" tag doesn't support rows and cols attributes. This is why the best alternative is to use a textarea with rows and cols attributes. You can still add a "name" attribute and also there is a useful "wrap" attribute which can serve pretty well in various situations.
Error:
sony@sony-VPCEH25EN:~$ java --version
Picked up JAVA_TOOL_OPTIONS: -javaagent:/usr/share/java/jayatanaag.jar
Unrecognized option: --version
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
Solution: Remove extra hyphen '-'
sony@sony-VPCEH25EN:~$ java -version
Picked up JAVA_TOOL_OPTIONS: -javaagent:/usr/share/java/jayatanaag.jar
java version "1.8.0_101"
Java(TM) SE Runtime Environment (build 1.8.0_101-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.101-b13, mixed mode)
You can also look at the jquery FormatCurrency plugin (of which I am the author); it has support for multiple locales as well, but may have the overhead of the currency support that you don't need.
$(this).formatCurrency({ symbol: '', roundToDecimalPlace: 0 });
If you are storing metadata in a tag use data attributes eg.
<li id="song1" data-value="song1.ogg"><button onclick="updateSource()">Item1</button></li>
Now use the attribute to get the name of the song
var audio = document.getElementById('audio');
audio.src='audio/ogg/' + document.getElementById('song1').getAttribute('data-value');
audio.load();
X * 2 = 1 bit shift left
X / 2 = 1 bit shift right
X * 3 = shift left 1 bit and then add X
This might be known by most of us, but anyway (I was puzzled my first time):
Doing :set et
(:set
expandtabs) does not change the tabs already existing in the file, one has to do :retab
.
For example:
:set et
:retab
and the tabs in the file are replaced by enough spaces. To have tabs back simply do:
:set noet
:retab
While I like the class decorator from Oz123, you could also do the following, which uses an explicit class wrapper and __new__ with a class Factory method returning the class within a closure:
class B(object):
def __new__(cls, val):
return cls.factory(val)
@classmethod
def factory(cls, val):
private = {'var': 'test'}
class InnerB(object):
def __init__(self):
self.variable = val
pass
@property
def var(self):
return private['var']
return InnerB()
BeautifulSoup(text, features="html.parser").text
For the people who were seeking deep info in my answer, sorry.
I'll explain it.
Beautifulsoup is a widely use python package that helps the user (developer) to interact with HTML within python.
The above like just take all the HTML text (text
) and cast it to Beautifulsoup object - that means behind the sense its parses everything up (Every HTML tag within the given text)
Once done so, we just request all the text from within the HTML object.
If you are running on Linux OS,there might be case where your npm remote server is not running. Open another terminal (with project directory) and run this command sudo npm start or sudo react-native start before doing sudo react-native run-android
I had the same problem; here are the commands to fix it:
sudo ln -s /usr/local/bin/node /usr/bin/node
sudo ln -s /usr/local/lib/node /usr/lib/node
sudo ln -s /usr/local/bin/npm /usr/bin/npm
sudo ln -s /usr/local/bin/node-waf /usr/bin/node-waf
I found this helpful...
http://www.cmake.org/pipermail/cmake/2011-June/045222.html
From their example:
ADD_LIBRARY(boost_unit_test_framework STATIC IMPORTED)
SET_TARGET_PROPERTIES(boost_unit_test_framework PROPERTIES IMPORTED_LOCATION /usr/lib/libboost_unit_test_framework.a)
TARGET_LINK_LIBRARIES(mytarget A boost_unit_test_framework C)
Under Project->Properties->Debug, you should see a box for Command line arguments (This is in C# 2010, but it should basically be the same place)
Here is a possible solution:
def download_list_s3_folder(my_bucket,my_folder):
import boto3
s3 = boto3.client('s3')
response = s3.list_objects_v2(
Bucket=my_bucket,
Prefix=my_folder,
MaxKeys=1000)
return [item["Key"] for item in response['Contents']]
function Parent() {_x000D_
const [Name, setName] = useState("");_x000D_
getChildChange = getChildChange.bind(this);_x000D_
function getChildChange(value) {_x000D_
setName(value);_x000D_
}_x000D_
_x000D_
return <div> {Name} :_x000D_
<Child getChildChange={getChildChange} ></Child>_x000D_
</div>_x000D_
}_x000D_
_x000D_
function Child(props) {_x000D_
const [Name, setName] = useState("");_x000D_
handleChange = handleChange.bind(this);_x000D_
collectState = collectState.bind(this);_x000D_
_x000D_
function handleChange(ele) {_x000D_
setName(ele.target.value);_x000D_
}_x000D_
_x000D_
function collectState() {_x000D_
return Name;_x000D_
}_x000D_
_x000D_
useEffect(() => {_x000D_
props.getChildChange(collectState());_x000D_
});_x000D_
_x000D_
return (<div>_x000D_
<input onChange={handleChange} value={Name}></input>_x000D_
</div>);_x000D_
}
_x000D_
useEffect
act as componentDidMount, componentDidUpdate, so after updating state it will work
You are getting Floating point exception because Number % i
, when i
is 0
:
int Is_Prime( int Number ){
int i ;
for( i = 0 ; i < Number / 2 ; i++ ){
if( Number % i != 0 ) return -1 ;
}
return Number ;
}
Just start the loop at i = 2
. Since i = 1
in Number % i
it always be equal to zero, since Number is a int.
You can use SilverLight to launch an application from the browser (this will work only on IE and Firefox, newer versions of chrome don't support this)
Example code here
Building off both @Marc and @jessica solutions - This is the solution that I use:
li {
position:relative;
}
li:before {
content:'';
display: block;
position: absolute;
width: 6px;
height:6px;
border-radius:6px;
left: -20px;
top: .5em;
background-color: #000;
}
I use em
for font sizes so if you set your top
value to be .5em
it will always be placed to the mid point of your first line of text. I used left:-20px
because that is the default position of bullets in browsers: parent padding/2
I did it with an ajax post and then returned using a data url:
$(document).ready(function () {
var exportClick = function () {
$.ajax({
url: "/api/test.php",
type: "POST",
dataType: "text",
data: {
action: "getCSV",
filter: "name = 'smith'",
},
success: function(data) {
var w = window.open('data:text/csv;charset=utf-8,' + encodeURIComponent(data));
w.focus();
},
error: function () {
alert('Problem getting data');
},
});
}
});
A float
generally has about 7 digits of precision, regardless of the position of the decimal point. So if you want 5 digits of precision after the decimal, you'll need to limit the range of the numbers to less than somewhere around +/-100.
check out
http://www.thesitewizard.com/general/set-cron-job.shtml
for the specifics of setting your crontab directives.
45 10 * * *
will run in the 10th hour, 45th minute of every day.
for midnight... maybe
0 0 * * *
Apparently this will not work for negative values, but it will for positive numbers.
Use isdigit()
if userinput.isdigit():
#do stuff
Do you really want the result to come up in an input box? If not, consider a table with borders set to other than transparent and use
document.getElementById('sum').innerHTML = sum;
Use String#trim()
method or String allRemoved = myString.replaceAll("^\\s+|\\s+$", "")
for trim both the end.
For left trim:
String leftRemoved = myString.replaceAll("^\\s+", "");
For right trim:
String rightRemoved = myString.replaceAll("\\s+$", "");
I would checkout the remote file from the "master" (the remote/origin repository) like this:
git checkout master <FileWithPath>
Example: git checkout master components/indexTest.html
Here is the way I do it:
@Entity
public class ServerInstanceSeq
{
@Id //mysql bigint(20)
@SequenceGenerator(name="ServerInstanceIdSeqName", sequenceName="ServerInstanceIdSeq", allocationSize=20)
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="ServerInstanceIdSeqName")
public Long id;
}
ServerInstanceSeq sis = new ServerInstanceSeq();
session.beginTransaction();
session.save(sis);
session.getTransaction().commit();
System.out.println("sis.id after save: "+sis.id);
Check here DEMO http://jsfiddle.net/yeyene/Uhm2J/
function getData() {
$.getJSON('Get/GetData?no=1', function (responseText) {
//Load some data from the server
})
};
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
alert("bottom!");
// getData();
}
});
dictionary's setdefault is a good way to update an existing dict entry if it's there, or create a new one if it's not all in one go:
Looping style:
# This is our sample data
data = [("Milter", "Miller", 4), ("Milter", "Miler", 4), ("Milter", "Malter", 2)]
# dictionary we want for the result
dictionary = {}
# loop that makes it work
for realName, falseName, position in data:
dictionary.setdefault(realName, {})[falseName] = position
dictionary now equals:
{'Milter': {'Malter': 2, 'Miler': 4, 'Miller': 4}}
For Linux & Mac
keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android
If you're using IntelliJ 13 with SVN 1.8, you have to install SVN command line client. Please see more information here:
Unlike its earlier versions, Subversion 1.8 support uses the native command line client instead of SVNKit to run commands. This approach is more flexible and makes the support of upcoming versions much easier. Now, IntelliJ IDEA offers different integration options for each specific Subversion:
1.6 – SVNKit only
1.7 – SVNKit and command line client
1.8 – Command line client only
You can use tail
:
$ foo="1234567890"
$ echo -n $foo | tail -c 3
890
A somewhat roundabout way to get the last three characters would be to say:
echo $foo | rev | cut -c1-3 | rev
In case that the array contains objects for example if favouriteFoods
is an array of objects of the following:
{
name: 'Sushi',
type: 'Japanese'
}
you can use the following query:
PersonModel.find({"favouriteFoods.name": "Sushi"});
Well, you can't. Internal classes can't be visible outside of their assembly, so no explicit way to access it directly -AFAIK of course. The only way is to use runtime late-binding via reflection, then you can invoke methods and properties from the internal class indirectly.
This answer comes late but summarizes the concept involved in the "table not mapped" exception(in order to help those who come across this problem since its very common for hibernate newbies). This error can appear due to many reasons but the target is to address the most common one that is faced by a number of novice hibernate developers to save them hours of research. I am using my own example for a simple demonstration below.
The exception:
org.hibernate.hql.internal.ast.QuerySyntaxException: subscriber is not mapped [ from subscriber]
In simple words, this very usual exception only tells that the query is wrong in the below code.
Session session = this.sessionFactory.getCurrentSession();
List<Subscriber> personsList = session.createQuery(" from subscriber").list();
This is how my POJO class is declared:
@Entity
@Table(name = "subscriber")
public class Subscriber
But the query syntax "from subscriber" is correct and the table subscriber
exists. Which brings me to a key point:
and how its explained here
HQL works with persistent objects and their properties not with the database tables and columns.
Since the above query is an HQL one, the subscriber
is supposed to be an entity name not a table name. Since I have my table subscriber
mapped with the entity Subscriber
. My problem solves if I change the code to this:
Session session = this.sessionFactory.getCurrentSession();
List<Subscriber> personsList = session.createQuery(" from Subscriber").list();
Just to keep you from getting confused. Please note that HQL is case sensitive in a number of cases. Otherwise it would have worked in my case.
Keywords like SELECT , FROM and WHERE etc. are not case sensitive but properties like table and column names are case sensitive in HQL.
https://www.tutorialspoint.com/hibernate/hibernate_query_language.htm
To further understand how hibernate mapping works, please read this
(I presume you are aware that using UDP(User Datagram Protocol) does not guarantee delivery, checks for duplicates and congestion control and will just answer your question).
In your server this line:
var data = udpServer.Receive(ref groupEP);
re-assigns groupEP
from what you had to a the address you receive something on.
This line:
udpServer.Send(new byte[] { 1 }, 1);
Will not work since you have not specified who to send the data to. (It works on your client because you called connect which means send will always be sent to the end point you connected to, of course we don't want that on the server as we could have many clients). I would:
UdpClient udpServer = new UdpClient(UDP_LISTEN_PORT);
while (true)
{
var remoteEP = new IPEndPoint(IPAddress.Any, 11000);
var data = udpServer.Receive(ref remoteEP);
udpServer.Send(new byte[] { 1 }, 1, remoteEP); // if data is received reply letting the client know that we got his data
}
Also if you have server and client on the same machine you should have them on different ports.
For python 2
pip install numpy --upgrade
You would also needed to upgrade your tables as well for updated version of numpy. so,
pip install tables --upgrade
For python 3
pip3 install numpy --upgrade
Similarly, the tables for python3 :-
pip3 install tables --upgrade
You need to check which python version are you using. pip for python 2.7+ or pip3 for python 3+
Note: I see that someone (not @unutbu) changed the referenced answer so that it no longer uses vars()['Foo']
— so the primary point of my post no longer applies.
FWIW, here's what I meant about @unutbu's answer only working with locally defined classes — and that using eval()
instead of vars()
would make it work with any accessible class, not only those defined in the current scope.
For those who dislike using eval()
, a way is also shown to avoid it.
First here's a concrete example demonstrating the potential problem with using vars()
:
class Foo(object): pass
class Bar(Foo): pass
class Baz(Foo): pass
class Bing(Bar): pass
# unutbu's approach
def all_subclasses(cls):
return cls.__subclasses__() + [g for s in cls.__subclasses__()
for g in all_subclasses(s)]
print(all_subclasses(vars()['Foo'])) # Fine because Foo is in scope
# -> [<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>]
def func(): # won't work because Foo class is not locally defined
print(all_subclasses(vars()['Foo']))
try:
func() # not OK because Foo is not local to func()
except Exception as e:
print('calling func() raised exception: {!r}'.format(e))
# -> calling func() raised exception: KeyError('Foo',)
print(all_subclasses(eval('Foo'))) # OK
# -> [<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>]
# using eval('xxx') instead of vars()['xxx']
def func2():
print(all_subclasses(eval('Foo')))
func2() # Works
# -> [<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>]
This could be improved by moving the eval('ClassName')
down into the function defined, which makes using it easier without loss of the additional generality gained by using eval()
which unlike vars()
is not context-sensitive:
# easier to use version
def all_subclasses2(classname):
direct_subclasses = eval(classname).__subclasses__()
return direct_subclasses + [g for s in direct_subclasses
for g in all_subclasses2(s.__name__)]
# pass 'xxx' instead of eval('xxx')
def func_ez():
print(all_subclasses2('Foo')) # simpler
func_ez()
# -> [<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>]
Lastly, it's possible, and perhaps even important in some cases, to avoid using eval()
for security reasons, so here's a version without it:
def get_all_subclasses(cls):
""" Generator of all a class's subclasses. """
try:
for subclass in cls.__subclasses__():
yield subclass
for subclass in get_all_subclasses(subclass):
yield subclass
except TypeError:
return
def all_subclasses3(classname):
for cls in get_all_subclasses(object): # object is base of all new-style classes.
if cls.__name__.split('.')[-1] == classname:
break
else:
raise ValueError('class %s not found' % classname)
direct_subclasses = cls.__subclasses__()
return direct_subclasses + [g for s in direct_subclasses
for g in all_subclasses3(s.__name__)]
# no eval('xxx')
def func3():
print(all_subclasses3('Foo'))
func3() # Also works
# -> [<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>]
what you could do, is put an if statement around everything inside the loop that you want kept away from the 50. e.g.
for i in range(0, len(list)):
if i != 50:
x= listRow(list, i)
for j in range (#0 to len(list) not including x#)
in my case i was using compile sdk 23
and build tools 25.0.0
just changed compile sdk
to 25 and done..
I am using this simple one line code for years without a problem (it requires jQuery):
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
function ap(x,y) {$("#" + y).load(x);};
function af(x,y) {$("#" + x ).ajaxSubmit({target: '#' + y});return false;};
</script>
Here ap() means an Ajax page and af() means an Ajax form. In a form, simply calling af() function will post the form to the URL and load the response on the desired HTML element.
<form id="form_id">
...
<input type="button" onclick="af('form_id','load_response_id')"/>
</form>
<div id="load_response_id">this is where response will be loaded</div>
This is a development storage
part of Tomas M answer for Chrome. We must add listener
window.addEventListener("storage", (e)=> { console.log(e) } );
Load/save item in storage not runt this event - we MUST trigger it manually by
window.dispatchEvent( new Event('storage') ); // THIS IS IMPORTANT ON CHROME
and now, all open tab-s will receive event
None of the current answers worked for my version of this error. I'm using the desktop version of Ubuntu 18. The following two commands fixed the issue.
sudo snap connect docker:home :home
sudo snap start docker
I won't address the READ UNCOMMITTED
argument, just your original question.
Yes, you need WITH(NOLOCK)
on each table of the join. No, your queries are not the same.
Try this exercise. Begin a transaction and insert a row into table1 and table2. Don't commit or rollback the transaction yet. At this point your first query will return successfully and include the uncommitted rows; your second query won't return because table2 doesn't have the WITH(NOLOCK)
hint on it.
You can use jquery function.
<form name='add'>
<input type='text' name='stud_name' id="stud_name" value=""/>
Age: <select name='age' id="age">
<option value='1' stud_name='sre'>23</option>
<option value='2' stud_name='sam'>24</option>
<option value='5' stud_name='john'>25</option>
</select>
<input type='submit' name='submit'/>
</form>
jquery code :
<script type="text/javascript" src="jquery.js"></script>
<script>
$(function() {
$("#age").change(function(){
var option = $('option:selected', this).attr('stud_name');
$('#stud_name').val(option);
});
});
</script>
//More Efficiently
public class Multiples {
public static void main(String[]args) {
int j = 5;
System.out.println(j % 4 == 0);
}
}
You can use the one above with one caveat:
IF EXISTS(
SELECT 1 FROM sys.foreign_keys
WHERE parent_object_id = OBJECT_ID(N'dbo.TableName')
AND name = 'CONSTRAINTNAME'
)
BEGIN
ALTER TABLE TableName DROP CONSTRAINT CONSTRAINTNAME
END
Need to use the name = [Constraint name]
since a table may have multiple foreign keys and still not have the foreign key being checked for
The problem I was having with the rewrite is that some .htaccess files for Codeigniter, etc come with
RewriteBase /
Which doesn't seem to work in MAMP...at least for me.
This is slighly more OS independent way:
# do this init somewhere
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
font = pygame.font.Font(pygame.font.get_default_font(), 36)
# now print the text
text_surface = font.render('Hello world', antialias=True, color=(0, 0, 0))
screen.blit(text_surface, dest=(0,0))
Try array_merge.
$array1 = array('Item 1');
$array2 = array('Item 2');
$array3 = array_merge($array1, $array2);
I think its because you are not assigning a key to either, so they both have key of 0, and the + does not re-index, so its trying to over write it.
I was at the pgopen today benchmarks are way faster than mongodb, I believe it was around 500% faster for selects. Pretty much everything was faster at least by at 200% when contrasted with mongodb, than one exception right now is a update which requires completely rewriting the entire json column something mongodb handles better.
The gin indexing on on jsonb sounds amazing.
Also postgres will persist types of jsonb internally and basically match this with types such as numeric, text, boolean etc.
Joins will also be possible using jsonb
Add PLv8 for stored procedures and this will basically be a dream come true for node.js developers.
Being it's stored as binary jsonb will also strip all whitespace, change the ordering of properties and remove duplicate properties using the last occurance of the property.
Besides the index when querying against a jsonb column contrasted to a json column postgres doesn't have to actually run the functionality to convert the text to json on every row which will likely save a vast amount of time alone.
Last year, I took Prof: Andrew Ng’s online machine learning course. His recommendation was:
Training: 60%
Cross validation: 20%
Testing: 20%
Resolved: wp-config.php setting
I had a similar problem. I got the install.php after moving files and creating a new database. It seems the install screen shows up it there is problem finding the correct database tables.
I fixed the problem by changing the following settings to be correct:
// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', 'HikeforLife_dev11');
/** MySQL database username */
define('DB_USER', 'HikeforLife_dev11');
$table_prefix = 'wphk_';
I'm surprised nobody mentioned the command php artisan route:list
, which gives a list of all registered app routes (including Auth::routes()
and Passport::routes()
if registered)
use range, or DateDiff function
select * from test
where date between '03/19/2014' and '03/19/2014 23:59:59'
or
select * from test
where datediff(day, date, '03/19/2014') = 0
Other options are:
If you have control over the database schema, and you don't need the time data, take it out.
or, if you must keep it, add a computed column attribute that has the time portion of the date value stripped off...
Alter table Test
Add DateOnly As
DateAdd(day, datediff(day, 0, date), 0)
or, in more recent versions of SQL Server...
Alter table Test
Add DateOnly As
Cast(DateAdd(day, datediff(day, 0, date), 0) as Date)
then, you can write your query as simply:
select * from test
where DateOnly = '03/19/2014'
I would like to expand on the Windows solution. Using IDLE with Python 2.7.5, When I run this code from file Expts.py:
import subprocess
r = subprocess.check_output('cmd.exe dir',shell=False)
print r
...in the Python Shell, I ONLY get the output corresponding to "cmd.exe"; the "dir" part is ignored. HOWEVER, when I add a switch such as /K or /C ...
import subprocess
r = subprocess.check_output('cmd.exe /K dir',shell=False)
print r
...then in the Python Shell, I get all that I expect including the directory listing. Woohoo !
Now, if I try any of those same things in DOS Python command window, without the switch, or with the /K switch, it appears to make the window hang because it is running a subprocess cmd.exe and it awaiting further input - type 'exit' then hit [enter] to release. But with the /K switch it works perfectly and returns you to the python prompt. Allrightee then.
Went a step further...I thought this was cool...When I instead do this in Expts.py:
import subprocess
r = subprocess.call("cmd.exe dir",shell=False)
print r
...a new DOS window pops open and remains there displaying only the results of "cmd.exe" not of "dir". When I add the /C switch, the DOS window opens and closes very fast before I can see anything (as expected, because /C terminates when done). When I instead add the /K switch, the DOS window pops open and remain, AND I get all the output I expect including the directory listing.
If I try the same thing (subprocess.call instead of subprocess.check_output) from a DOS Python command window; all output is within the same window, there are no popup windows. Without the switch, again the "dir" part is ignored, AND the prompt changes from the python prompt to the DOS prompt (since a cmd.exe subprocess is running in python; again type 'exit' and you will revert to the python prompt). Adding the /K switch prints out the directory listing and changes the prompt from python to DOS since /K does not terminate the subprocess. Changing the switch to /C gives us all the output expected AND returns to the python prompt since the subprocess terminates in accordance with /C.
Sorry for the long-winded response, but I am frustrated on this board with the many terse 'answers' which at best don't work (seems because they are not tested - like Eduard F's response above mine which is missing the switch) or worse, are so terse that they don't help much at all (e.g., 'try subprocess instead of os.system' ... yeah, OK, now what ??). In contrast, I have provided solutions which I tested, and showed how there are subtle differences between them. Took a lot of time but... Hope this helps.
Without any external modules, valid for shell, works well even with '../':
my $self = `pwd`;
chomp $self;
$self .='/'.$1 if $0 =~/([^\/]*)$/; #keep the filename only
print "self=$self\n";
test:
$ /my/temp/Host$ perl ./host-mod.pl
self=/my/temp/Host/host-mod.pl
$ /my/temp/Host$ ./host-mod.pl
self=/my/temp/Host/host-mod.pl
$ /my/temp/Host$ ../Host/./host-mod.pl
self=/my/temp/Host/host-mod.pl
Syntactically, this line makes no sense:
invest(initial_amount,top_company(5,year,year+1)) = subsequent_amount
You are attempting to assign a value to a function call, as the error says. What are you trying to accomplish? If you're trying set subsequent_amount
to the value of the function call, switch the order:
subsequent_amount = invest(initial_amount,top_company(5,year,year+1))
Please add the correct mime-types to your code - at least these ones:
.jpeg -> image/jpeg
.gif -> image/gif
.png -> image/png
A list of mime-types can be found here.
Furthermore, simplify the code's logic and report an error number to help the first level support track down problems:
$allowedExts = array(
"pdf",
"doc",
"docx"
);
$allowedMimeTypes = array(
'application/msword',
'text/pdf',
'image/gif',
'image/jpeg',
'image/png'
);
$extension = end(explode(".", $_FILES["file"]["name"]));
if ( 20000 < $_FILES["file"]["size"] ) {
die( 'Please provide a smaller file [E/1].' );
}
if ( ! ( in_array($extension, $allowedExts ) ) ) {
die('Please provide another file type [E/2].');
}
if ( in_array( $_FILES["file"]["type"], $allowedMimeTypes ) )
{
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
}
else
{
die('Please provide another file type [E/3].');
}
This problem is due to the https protocol, which is why the other solution works (by switching to the non-secure protocol).
For me, the best solution was to compile the latest version of node, which includes npm
apt-get purge nodejs npm
git clone https://github.com/nodejs/node ~/local/node
cd ~/local/node
./configure
make
make install
Could also potentially use this script to use the system time in a variable
now=$(date +"%m_%d_%Y_%M:%S")
Which outputs as
12_07_2020_34:21
AlliterativeAlice's example helped me tremendously. In my case, though, the server I was talking to didn't like having single quotes around utf-8
in the content type. It failed with a generic "Server Error"
and it took hours to figure out what it didn't like:
request.ContentType = "text/xml; encoding=utf-8";
First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.
For example,
> z <- factor(letters[c(3, 2, 3, 4)])
# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d
# internal structure of factor
> unclass(z)
[1] 2 1 2 3
attr(,"levels")
[1] "b" "c" "d"
here, z
has 4 elements.
The index is 2, 1, 2, 3
in that order.
The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.
Then, as.numeric
converts simply the index part of factor into numeric.
as.character
handles the index and levels, and generates character vector expressed by its level.
?as.numeric
says that Factors are handled by the default method.
If you need placeholder like behavior. you can use this.
$("selector").data("DefaultText", SetYourDefaultTextHere);
// You can also define the DefaultText as attribute and access that using attr() function
$("selector").focus(function(){
if($(this).val() == $(this).data("DefaultText"))
$(this).val('');
});
For a new document: Settings -> Preferences -> New Document/Default Directory
-> New Document -> Format -> Windows/Mac/Unix
And for an already-open document: Edit -> EOL Conversion
Simply
For Visual Studio Code
Use ALt + Shift + F
for Visual Studio IDE
Press Ctrl + K followed by Ctrl + D
It will beautifully format the entier file.
import java.io.*;
class ss1
{
public static void main(String args[])
{
String a = new String("sample");
System.out.println("Result: ");
for(int i=0;i<a.length();i++)
{
System.out.println(a.charAt(i));
}
}
}
With pandas it can be done as:
If lakes is your DataFrame:
area_dict = lakes.to_dict('records')
Write a single function and call it for both of them.
function yourHandler(e){
alert( 'something happened!' );
}
jQuery(':input').change(yourHandler).keyup(yourHandler);
The change() and keyup() event registration functions return the original set, so they can be chained.
before you write set(XXXXX)
you have used "set" as a variable
e.g.
set = 90 #you have used "set" as an object
…
…
a = set(["Blah", "Hello"])
a = list(a)
With minor corrections:
function rearrange()
{
var windowHeight;
if (typeof window.innerWidth != 'undefined')
{
windowHeight = window.innerHeight;
}
// IE6 in standards compliant mode (i.e. with a valid doctype as the first
// line in the document)
else if (typeof document.documentElement != 'undefined'
&& typeof document.documentElement.clientWidth != 'undefined'
&& document.documentElement.clientWidth != 0)
{
windowHeight = document.documentElement.clientHeight;
}
// older versions of IE
else
{
windowHeight = document.getElementsByTagName('body')[0].clientHeight;
}
document.getElementById("foobar").style.height = (windowHeight - document.getElementById("foobar").offsetTop - 6)+ "px";
}
the default server name is your computer name, but you can use "." (Dot) instead of local server name.
another thing you should consider is maybe you installed sql server express edition. in this case you must enter ".\sqlexpress" as server name.
This seems to me the most simple and readable way of doing so:
let options = {name:"James"}
const default_options = {name:"John", surname:"Doe"}
options = Object.assign({}, default_options, options)
you can use this file (https://github.com/louisremi/background-size-polyfill “background-size polyfill”) for IE8 that is really simple to use:
.selector {
background-size: cover;
-ms-behavior: url(/backgroundsize.min.htc);
}
I'd say use hash, like this:
window.onload = function() {
if(!window.location.hash) {
window.location = window.location + '#loaded';
window.location.reload();
}
}
You can know list of all ports running in system along with its details (pid, address etc.) :
netstat -tulpn
You can know details of a particular port number by providing port number in following command :
sudo netstat -lutnp | grep -w '{port_number}'
ex: sudo netstat -lutnp | grep -w '8080' Details will be provided like this :
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
if you want to kill a process using pid then : kill -9 {PID}
if you want to kill a process using port number : fuser -n tcp {port_number}
use sudo
if you are not able to access any.
h2.text-left{
position:relative;
top:50%;
transform: translateY(-50%);
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
}
Explanation:
The top:50% style essentially pushes the header element down 50% from the top of the parent element. The translateY stylings also act in a similar manner by moving then element down 50% from the top.
Please note that this works well for headers with 1 (maybe 2) lines of text as this simply moves the top of the header element down 50% and then the rest of the content fills in below that, which means that with multiple lines of text it would appear to be slightly below vertically aligned.
A possible fix for multiple lines would be to use a percentage slightly less than 50%.
I tried all the above with v 1.8.13 to no avail.
What worked for me (on macOS) was to use the doxywizard->Expert tag to fill the USE_MD_FILE_AS_MAINPAGE
setting.
It made the following changes to my Doxyfile:
USE_MDFILE_AS_MAINPAGE = ../README.md
...
INPUT = ../README.md \
../sdk/include \
../sdk/src
Note the line termination for INPUT
, I had just been using space as a separator as specified in the documentation. AFAICT this is the only change between the not-working and working version of the Doxyfile.
In case you want to kill not all java processes but specif jars running. It will work for multiple jars as well.
wmic Path win32_process Where "CommandLine Like '%YourJarName.jar%'" Call Terminate
Else taskkill /im java.exe
will work to kill all java processes
Here are a few ways you can check if a list is empty:
a = [] #the list
1) The pretty simple pythonic way:
if not a:
print("a is empty")
In Python, empty containers such as lists,tuples,sets,dicts,variables etc are seen as False
. One could simply treat the list as a predicate (returning a Boolean value). And a True
value would indicate that it's non-empty.
2) A much explicit way: using the len()
to find the length and check if it equals to 0
:
if len(a) == 0:
print("a is empty")
3) Or comparing it to an anonymous empty list:
if a == []:
print("a is empty")
4) Another yet silly way to do is using exception
and iter()
:
try:
next(iter(a))
# list has elements
except StopIteration:
print("Error: a is empty")
Might also be interesting for you to know that you can use:
{r echo=FALSE, results='hide',message=FALSE}
a<-as.numeric(rnorm(100))
hist(a, breaks=24)
to exclude all the commands you give, all the results it spits out and all message info being spit out by R (eg. after library(ggplot) or something)
This problem can occur if you have altogether too much stuff being started when the server is started -- or if you are in debug mode and stepping through the initialization sequence. In eclipse, changing the start-timeout by 'opening' the tomcat server entry 'Servers view' tab of the Debug Perspective is convenient. In some situations it is useful to know where this setting is 'really' stored.
Tomcat reads this setting from the element in the element in the servers.xml file. This file is stored in the .metatdata/.plugins/org.eclipse.wst.server.core directory of your eclipse workspace, ie:
//.metadata/.plugins/org.eclipse.wst.server.core/servers.xml
There are other juicy configuration files for Eclipse plugins in other directories under .metadata/.plugins as well.
Here's an example of the servers.xml file, which is what is changed when you edit the tomcat server configuration through the Eclipse GUI:
Note the 'start-timeout' property that is set to a good long 1200 seconds above.
Assuming one has installed a JDK in /opt/java/jdk1.8.0_144
then:
Install the alternative for javac
$ sudo update-alternatives --install /usr/bin/javac javac /opt/java/jdk1.8.0_144/bin/javac 1
Check / update the alternatives config:
$ sudo update-alternatives --config javac
If there is only a single alternative for javac
you will get a message saying so, otherwise select the option for the new JDK.
To check everything is setup correctly then:
$ which javac
/usr/bin/javac
$ ls -l /usr/bin/javac
lrwxrwxrwx 1 root root 23 Sep 4 17:10 /usr/bin/javac -> /etc/alternatives/javac
$ ls -l /etc/alternatives/javac
lrwxrwxrwx 1 root root 32 Sep 4 17:10 /etc/alternatives/javac -> /opt/java/jdk1.8.0_144/bin/javac
And finally
$ javac -version
javac 1.8.0_144
Repeat for java, keytool, jar, etc as needed.
You could try this.
In windows go to Administrative Tools->Services And see scroll down to where it says Oracle[instanceNameHere] and see if the listener and the service itself are running. You might have to start it. You can also set it to start automatically when you right-click on it and go to properties.
The exit codes only have meaning as assigned by the script author. The Unix tradition is that exit code 0 means 'success', anything else is failure. The only way to be sure what the exit codes for a given script mean is to examine the script itself.
Since String
IS-A CharSequence
, you can pass a String
wherever you need a CharSequence
, or assign a String
to a CharSequence
:
CharSequence cs = "string";
String s = cs.toString();
foo(s); // prints "string"
public void foo(CharSequence cs) {
System.out.println(cs);
}
If you want to convert a CharSequence
to a String
, just use the toString
method that must be implemented by every concrete implementation of CharSequence
.
Hope it helps.
From the comments:
import msvcrt # built-in module
def kbfunc():
return ord(msvcrt.getch()) if msvcrt.kbhit() else 0
Thanks for the help. I ended up writing a C DLL called PyKeyboardAccess.dll and accessing the crt conio functions, exporting this routine:
#include <conio.h>
int kb_inkey () {
int rc;
int key;
key = _kbhit();
if (key == 0) {
rc = 0;
} else {
rc = _getch();
}
return rc;
}
And I access it in python using the ctypes module (built into python 2.5):
import ctypes
import time
#
# first, load the DLL
#
try:
kblib = ctypes.CDLL("PyKeyboardAccess.dll")
except:
raise ("Error Loading PyKeyboardAccess.dll")
#
# now, find our function
#
try:
kbfunc = kblib.kb_inkey
except:
raise ("Could not find the kb_inkey function in the dll!")
#
# Ok, now let's demo the capability
#
while 1:
x = kbfunc()
if x != 0:
print "Got key: %d" % x
else:
time.sleep(.01)
json_decode will return the same array that was originally encoded. For instanse, if you
$array = json_decode($json, true);
echo $array['countryId'];
OR
$obj= json_decode($json);
echo $obj->countryId;
These both will echo 84. I think json_encode and json_decode function names are self-explanatory...
Not all twitter API users are created equal - some are more equal than others.
https://dev.twitter.com/docs/streaming-api/methods
For thine not that equal they suggest creative using of other techniques. You may get more luck by using search api calls with time / id limitation
You can also try this:
bool isPrime(int number)
{
return (Enumerable.Range(1, number).Count(x => number % x == 0) == 2);
}
you can get the size of InputStream using getBytes(inputStream) of Utils.java check this following link
The only thing which worked for me is this
fetchData()
.subscribe(
(data) => {
//Called when success
},
(error) => {
//Called when error
}
).add(() => {
//Called when operation is complete (both success and error)
});
In addition to Boaz's answer ....
@UniqueConstraint
allows you to name the constraint, while @Column(unique = true)
generates a random name (e.g. UK_3u5h7y36qqa13y3mauc5xxayq
).
Sometimes it can be helpful to know what table a constraint is associated with. E.g.:
@Table(
name = "product_serial_group_mask",
uniqueConstraints = {
@UniqueConstraint(
columnNames = {"mask", "group"},
name="uk_product_serial_group_mask"
)
}
)
I needed to specify min-height
#login
display: flex
align-items: center
justify-content: center
min-height: 16em
Here's the best way to get a general File's size (works for directory and non-directory):
public static long getSize(File file) {
long size;
if (file.isDirectory()) {
size = 0;
for (File child : file.listFiles()) {
size += getSize(child);
}
} else {
size = file.length();
}
return size;
}
Edit: Note that this is probably going to be a time-consuming operation. Don't run it on the UI thread.
Also, here (taken from https://stackoverflow.com/a/5599842/1696171) is a nice way to get a user-readable String from the long returned:
public static String getReadableSize(long size) {
if(size <= 0) return "0";
final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
int digitGroups = (int) (Math.log10(size)/Math.log10(1024));
return new DecimalFormat("#,##0.#").format(size/Math.pow(1024, digitGroups))
+ " " + units[digitGroups];
}
SilverSkin and Anders are both correct. You can use parentheses to execute multiple commands. However, you have to make sure that the commands themselves (and their parameters) do not contain parentheses. cmd
greedily searches for the first closing parenthesis, instead of handling nested sets of parentheses gracefully. This may cause the rest of the command line to fail to parse, or it may cause some of the parentheses to get passed to the commands (e.g. DEL myfile.txt)
).
A workaround for this is to split the body of the loop into a separate function. Note that you probably need to jump around the function body to avoid "falling through" into it.
FOR /r %%X IN (*.txt) DO CALL :loopbody %%X
REM Don't "fall through" to :loopbody.
GOTO :EOF
:loopbody
ECHO %1
DEL %1
GOTO :EOF
For future Googlers i've a different approach to check if it's last element. It's similar to last lines in OP question.
This directly compares elements rather than just checking index numbers.
$yourset.each(function() {
var $this = $(this);
if($this[0] === $yourset.last()[0]) {
//$this is the last one
}
});
You can use istringstream
.
string s = "10";
// create an input stream with your string.
istringstream is(str);
int i;
// use is like an input stream
is >> i;
Derived from Dan Moulding's POSIX answer, this should work :
#include <time.h>
#include <math.h>
long millis(){
struct timespec _t;
clock_gettime(CLOCK_REALTIME, &_t);
return _t.tv_sec*1000 + lround(_t.tv_nsec/1.0e6);
}
Also as pointed out by David Guyon: compile with -lm
There are two ways:
Without LINQ: yourList.Sort();
With LINQ: yourList.OrderBy(x => x).ToList()
You will find more information in: https://www.dotnetperls.com/sort
There are a couple of good solutions here.
Similar to the answer from Harpal, but within the facet, so doesn't require any change to underlying data or pre-plotting manipulation:
# Change this code:
facet_grid(.~size) +
# To this code:
facet_grid(~factor(size, levels=c('50%','100%','150%','200%')))
This is flexible, and can be implemented for any variable as you change what element is faceted, no underlying change in the data required.
I can recommend make pre-init of future index value, this is very usefull in a lot of case like multi work, some export e.t.c.
just create additional User_Seq
table:
with two fields: id Uniq index
and SeqVal nvarchar(1)
and create next SP, and generated ID value from this SP and put to new User row!
CREATE procedure [dbo].[User_NextValue]
as
begin
set NOCOUNT ON
declare @existingId int = (select isnull(max(UserId)+1, 0) from dbo.User)
insert into User_Seq (SeqVal) values ('a')
declare @NewSeqValue int = scope_identity()
if @existingId > @NewSeqValue
begin
set identity_insert User_Seq on
insert into User_Seq (SeqID) values (@existingId)
set @NewSeqValue = scope_identity()
end
delete from User_Seq WITH (READPAST)
return @NewSeqValue
end
Here is a simple directive that will scroll to an element on click:
myApp.directive('scrollOnClick', function() {
return {
restrict: 'A',
link: function(scope, $elm) {
$elm.on('click', function() {
$("body").animate({scrollTop: $elm.offset().top}, "slow");
});
}
}
});
Demo: http://plnkr.co/edit/yz1EHB8ad3C59N6PzdCD?p=preview
For help creating directives, check out the videos at http://egghead.io, starting at #10 "first directive".
edit: To make it scroll to a specific element specified by a href, just check attrs.href
.
myApp.directive('scrollOnClick', function() {
return {
restrict: 'A',
link: function(scope, $elm, attrs) {
var idToScroll = attrs.href;
$elm.on('click', function() {
var $target;
if (idToScroll) {
$target = $(idToScroll);
} else {
$target = $elm;
}
$("body").animate({scrollTop: $target.offset().top}, "slow");
});
}
}
});
Then you could use it like this: <div scroll-on-click></div>
to scroll to the element clicked. Or <a scroll-on-click href="#element-id"></div>
to scroll to element with the id.
I have the same issue(in my 3-Tire level project) and I fixed it by adding/installing the EF to my main Project.
Imagine you need a function that returns 10 squared so you write a function:
function tenSquared() {return 10*10;}
Later you need 9 squared so you write another function:
function nineSquared() {return 9*9;}
Eventually you will replace all of these with a generic function:
function square(x) {return x*x;}
The exact same thinking applies for callbacks. You have a function that does something and when done calls doA:
function computeA(){
...
doA(result);
}
Later you want the exact same function to call doB instead you could duplicate the whole function:
function computeB(){
...
doB(result);
}
Or you could pass a callback function as a variable and only have to have the function once:
function compute(callback){
...
callback(result);
}
Then you just have to call compute(doA) and compute(doB).
Beyond simplifying code, it lets asynchronous code let you know it has completed by calling your arbitrary function on completion, similar to when you call someone on the phone and leave a callback number.
To create a composite unique key on table
ALTER TABLE [TableName] ADD UNIQUE ([Column1], [Column2], [column3]);
svn merge -r 854:853 l3toks.dtx
or
svn merge -c -854 l3toks.dtx
The two commands are equivalent.
For camera access use:
<key>NSCameraUsageDescription</key>
<string>Camera Access Warning</string>
You could compile and link in one command:
gcc file1.c file2.c -o myprogram
And run with:
./myprogram
But to answer the question as asked, simply pass the object files to gcc
:
gcc file1.o file2.o -o myprogram
I like this explanation: http://joelabrahamsson.com/inversion-of-control-an-introduction-with-examples-in-net/
It start simple and shows code examples as well.
The consumer, X, needs the consumed class, Y, to accomplish something. That’s all good and natural, but does X really need to know that it uses Y?
Isn’t it enough that X knows that it uses something that has the behavior, the methods, properties etc, of Y without knowing who actually implements the behavior?
By extracting an abstract definition of the behavior used by X in Y, illustrated as I below, and letting the consumer X use an instance of that instead of Y it can continue to do what it does without having to know the specifics about Y.
In the illustration above Y implements I and X uses an instance of I. While it’s quite possible that X still uses Y what’s interesting is that X doesn’t know that. It just knows that it uses something that implements I.
Read article for further info and description of benefits such as:
...
From Bootstrap 4
.carousel-item{
height: 200px;
}
.carousel-item img{
height: 200px;
}
Here's a javascript implementation that works with web-kit:
var isHovering = false;
var el = $(".elem").mouseover(function(){
isHovering = true;
spin();
}).mouseout(function(){
isHovering = false;
});
var spin = function(){
if(isHovering){
el.removeClass("spin");
setTimeout(function(){
el.addClass("spin");
setTimeout(spin, 1500);
}, 0);
}
};
spin();
JSFiddle: http://jsfiddle.net/4Vz63/161/
Barf.
I was working on same. Check below statement. Worked for me!!
SELECT * FROM [Schema].[Table] WHERE [Column] LIKE '%' + @Parameter + '%'
Simple math.
double result = ((double)number) / 100.0;
Although you may want to use decimal
rather than double
: decimal vs double! - Which one should I use and when?
There is equally formatDate
const format = 'dd/MM/yyyy';
const myDate = '2019-06-29';
const locale = 'en-US';
const formattedDate = formatDate(myDate, format, locale);
According to the API it takes as param either a date string, a Date object, or a timestamp.
Gotcha: Out of the box, only en-US
is supported.
If you need to add another locale, you need to add it and register it in you app.module, for example for Spanish:
import { registerLocaleData } from '@angular/common';
import localeES from "@angular/common/locales/es";
registerLocaleData(localeES, "es");
Don't forget to add corresponding import:
import { formatDate } from "@angular/common";
If its IIS make sure That Under your common HTTP Features
you have Static Content
turned on
I know that this is old, but I've found that (while using Pillow) opening the file by using open(fp, 'w')
and then saving the file will work. E.g:
with open(fp, 'w') as f:
result.save(f)
fp
being the file path, of course.
The way is correct, but can be improved a bit with the extended set-syntax.
set "var=xyz"
Sets the var to the content until the last quotation mark, this ensures that no "hidden" spaces are appended.
Your code would look like
set "var1=A"
set "var2=B"
set "AB=hi"
set "newvar=%var1%%var2%"
echo %newvar% is the concat of var1 and var2
echo !%newvar%! is the indirect content of newvar
Apple made it different from other major language. The current way is to call:
test1.characters.count
However, to be careful, when you say length you mean the count of characters not the count of bytes, because those two can be different when you use non-ascii characters.
For example;
"???hi".characters.count
will give you 5 but this is not the count of the bytes.
To get the real count of bytes, you need to do "???hi".lengthOfBytes(using: String.Encoding.utf8)
. This will give you 11.
With includes()
, no, but you can achieve the same thing with REGEX via test()
:
var value = /hello|hi|howdy/.test(str);
Or, if the words are coming from a dynamic source:
var words = array('hello', 'hi', 'howdy');
var value = new RegExp(words.join('|')).test(str);
The REGEX approach is a better idea because it allows you to match the words as actual words, not substrings of other words. You just need the word boundary marker \b
, so:
var str = 'hilly';
var value = str.includes('hi'); //true, even though the word 'hi' isn't found
var value = /\bhi\b/.test(str); //false - 'hi' appears but not as its own word
I know Coop has already answered this question, but here is a version which also tracks where in the document the div is, rather than relying on a static value:
Javascript
var offset = $( ".sticky-header" ).offset();
var sticky = document.getElementById("sticky-header")
$(window).scroll(function() {
if ( $('body').scrollTop() > offset.top){
$('.sticky-header').addClass('fixed');
} else {
$('.sticky-header').removeClass('fixed');
}
});
CSS
.fixed{
position: fixed;
top: 0px;
}
You need to actually define the static member somewhere (after the class definition). Try this:
class Foo { /* ... */ };
const int Foo::MEMBER;
int main() { /* ... */ }
That should get rid of the undefined reference.
I haven't used connect by prior, but a quick search shows it's used for tree structures. In SQL Server, you use common table expressions to get similar functionality.
Use case: merging default configs
If we define configs in the form of:
const defaultConf = {
prop1: 'config1',
prop2: 'config2'
}
we can define more specific configs by doing:
const moreSpecificConf = {
...defaultConf,
prop3: 'config3'
}
But if these configs contain nested structures this approach doesn't work anymore.
Therefore I wrote a function that only merges objects in the sense of { key: value, ... }
and replaces the rest.
const isObject = (val) => val === Object(val);
const merge = (...objects) =>
objects.reduce(
(obj1, obj2) => ({
...obj1,
...obj2,
...Object.keys(obj2)
.filter((key) => key in obj1 && isObject(obj1[key]) && isObject(obj2[key]))
.map((key) => ({[key]: merge(obj1[key], obj2[key])}))
.reduce((n1, n2) => ({...n1, ...n2}), {})
}),
{}
);
How about this:
SELECT DISTINCT ON (name) *
FROM messages
ORDER BY name, id DESC;
I had similar issue (on postgresql tough) and on a 1M records table. This solution takes 1.7s vs 44s produced by the one with LEFT JOIN. In my case I had to filter the corrispondant of your name field against NULL values, resulting in even better performances by 0.2 secs
gcc 4.6 supports a new feature of deleted functions, where you can write
hdealt() = delete;
to disable the default constructor.
Here the compiler has obviously seen that a default constructor can not be generated, and =delete
'd it for you.
If you add this to your meta tags:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
IE8 will render the page like IE7.
Mustache templates are, by design, very simple; the homepage even says:
Logic-less templates.
So the general approach is to do your logic in JavaScript and set a bunch of flags:
if(notified_type == "Friendship")
data.type_friendship = true;
else if(notified_type == "Other" && action == "invite")
data.type_other_invite = true;
//...
and then in your template:
{{#type_friendship}}
friendship...
{{/type_friendship}}
{{#type_other_invite}}
invite...
{{/type_other_invite}}
If you want some more advanced functionality but want to maintain most of Mustache's simplicity, you could look at Handlebars:
Handlebars provides the power necessary to let you build semantic templates effectively with no frustration.
Mustache templates are compatible with Handlebars, so you can take a Mustache template, import it into Handlebars, and start taking advantage of the extra Handlebars features.
This working on SQL_Server_2008 R2
Select *
from Product_sales
where From_date
between '2013-01-03' and '2013-01-09'
Works Fine for App Notification settings on IOS 10 (tested)
if(&UIApplicationOpenSettingsURLString != nil){
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}
I'd like to add that TypeGuards only work on strings or numbers, if you want to compare an object use instanceof
if(task.id instanceof UUID) {
//foo
}
It do nothing, just provide a common template that will be shared for it's subclass
I'm not sure what you just did there, but from what I can tell this is what you're asking for:
bookingfacilities.php
<form action="successfulbooking.php" method="post">
<input type="hidden" name="date" value="<?php echo $date; ?>">
<input type="submit" value="Submit Form">
</form>
successfulbooking.php
<?php
$date = $_POST['date'];
// add code here
?>
Not sure what you want to do with that third page(booking_now.php) too.
You will need to know something about the URLs, like do they have a specific directory or some query string element because you have to match for something. Otherwise you will have to redirect on the 404. If this is what is required then do something like this in your .htaccess:
ErrorDocument 404 /index.php
An error page redirect must be relative to root so you cannot use www.mydomain.com.
If you have a pattern to match too then use 301 instead of 302 because 301 is permanent and 302 is temporary. A 301 will get the old URLs removed from the search engines and the 302 will not.
Mod Rewrite Reference: http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html
Add this in MainActivity.
Intent intent = new Intent(getApplicationContext(), Heightimage.class);
startActivity(intent);
I turned antonio's thoughts into a specific function:
library(DescTools)
> AddMonths(as.Date('2004-01-01'), 1)
[1] "2004-02-01"
> AddMonths(as.Date('2004-01-31'), 1)
[1] "2004-02-29"
> AddMonths(as.Date('2004-03-30'), -1)
[1] "2004-02-29"
You are getting this exception because your AWS SDK is unable to load your credentials. What you should do is goto Preferences then goto AWS and add your secret key and access key. So that your project can retrieve both keys.
In Python self
is the conventional name given to the first argument of instance methods of classes, which is always the instance the method was called on:
class A(object):
def f(self):
print self
a = A()
a.f()
Will give you something like
<__main__.A object at 0x02A9ACF0>
Java 8: Use random generator isolated to the current thread: ThreadLocalRandom nextBoolean()
Like the global Random generator used by the Math class, a ThreadLocalRandom is initialized with an internally generated seed that may not otherwise be modified. When applicable, use of ThreadLocalRandom rather than shared Random objects in concurrent programs will typically encounter much less overhead and contention.
java.util.concurrent.ThreadLocalRandom.current().nextBoolean();
Kenny is right, just want to clear some things out.
border.xml
and put it in the folder res/drawable/
add the code
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="4dp" android:color="#FF00FF00" />
<solid android:color="#ffffff" />
<padding android:left="7dp" android:top="7dp"
android:right="7dp" android:bottom="0dp" />
<corners android:radius="4dp" />
</shape>
set back ground like android:background="@drawable/border"
wherever you want the border
Mine first didn't work cause i put the border.xml
in the wrong folder!
For Delete, you will need to do as per the following
axios.delete("/<your endpoint>", { data:<"payload object">})
It worked for me.
AFHTTPClient * Client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:@"http://urlname"]];
NSDictionary * parameters = [[NSMutableDictionary alloc] init];
parameters = [NSDictionary dictionaryWithObjectsAndKeys:
height, @"user[height]",
weight, @"user[weight]",
nil];
[Client setParameterEncoding:AFJSONParameterEncoding];
[Client postPath:@"users/login.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"operation hasAcceptableStatusCode: %d", [operation.response statusCode]);
NSLog(@"response string: %@ ", operation.responseString);
NSDictionary *jsonResponseDict = [operation.responseString JSONValue];
if ([[jsonResponseDict objectForKey:@"responseBody"] isKindOfClass:[NSMutableDictionary class]]) {
NSMutableDictionary *responseBody = [jsonResponseDict objectForKey:@"responseBody"];
//get the response here
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"error: %@", operation.responseString);
NSLog(@"%d",operation.response.statusCode);
}];
Hope this works.
select d.dname
,count(e.empno) as count
from dept d
left outer join emp e
on e.deptno=d.deptno
group by d.dname;
The other name of sklearn in anaconda is scikit-learn. simply open your anaconda navigator, go to the environments, select your environment, for example tensorflow or whatever you want to work with, search for scikit_learn in the list of uninstalled packages, apply it and then you can import sklearn in your jupyter.
Using:
apt HelloImpl.java -classpath /sac/tools/thirdparty/jaxws-ri/jaxws-ri-2.1.4/lib/jsr181-api.jar:.
works but it gives me another error, see new question
another solution:
add src/myproject
to $GOPATH.
Then import "mylib"
will compile.
I had this issue in my android app when grabbing an xml file the format of my link was not valid, I reformatted with the full url and it worked.
from file import function_name ######## Importing specific function
function_name() ######## Calling function
and
import file ######## Importing whole package
file.function1_name() ######## Calling function
file.function2_name() ######## Calling function
Here are the two simple ways I have understood by now and make sure your "file.py" file which you want to import as a library is present in your current directory only.
Answering this question in the content that the questioners intent was to use the solution for software licensing, the requirements are:
A Digital Signature will solve this issue as the raw data that makes the key can be signed with a private key which makes it not human readable but could be decoded if reverse engineered. But the private key is safe which means no one will be able to make licenses for your software (which is the point).
Remember you can not prevent a skilled person from removing the software locks on your product. So if they have to hack each version that is released. But you really don't want them to be able to generate new keys for your product that can be shared for all versions.
Python The PyNaCl documentation has an example of 'Digital Signature' which will suite the purpose. http://pynacl.readthedocs.org/en/latest/signing/
and of cause NaCl project to C examples
When I had this error, it went away after I my computer crashed and restarted. Try closing and reopening your IDE, if that doesn't work, try restarting your computer. I had just installed the libraries at that point without restarting pycharm when I got this error.
Never closed PyCharm first to test because my blasted computer keeps crashing randomly... working on that one, but it at least solved this problem.. little victories.. :).
For starters:
<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>
Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.
This would be the optimal solution:
<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>
It can be a way to use functions to make other functions.
In javascript:
let add = function(x){
return function(y){
return x + y
};
};
Would allow us to call it like so:
let addTen = add(10);
When this runs the 10
is passed in as x
;
let add = function(10){
return function(y){
return 10 + y
};
};
which means we are returned this function:
function(y) { return 10 + y };
So when you call
addTen();
you are really calling:
function(y) { return 10 + y };
So if you do this:
addTen(4)
it's the same as:
function(4) { return 10 + 4} // 14
So our addTen()
always adds ten to whatever we pass in. We can make similar functions in the same way:
let addTwo = add(2) // addTwo(); will add two to whatever you pass in
let addSeventy = add(70) // ... and so on...
Now the obvious follow up question is why on earth would you ever want to do that? It turns what was an eager operation x + y
into one that can be stepped through lazily, meaning we can do at least two things
1. cache expensive operations
2. achieve abstractions in the functional paradigm.
Imagine our curried function looked like this:
let doTheHardStuff = function(x) {
let z = doSomethingComputationallyExpensive(x)
return function (y){
z + y
}
}
We could call this function once, then pass around the result to be used in lots of places, meaning we only do the computationally expensive stuff once:
let finishTheJob = doTheHardStuff(10)
finishTheJob(20)
finishTheJob(30)
We can get abstractions in a similar way.
Simple, just use .set_color
>>> barlist=plt.bar([1,2,3,4], [1,2,3,4])
>>> barlist[0].set_color('r')
>>> plt.show()
For your new question, not much harder either, just need to find the bar from your axis, an example:
>>> f=plt.figure()
>>> ax=f.add_subplot(1,1,1)
>>> ax.bar([1,2,3,4], [1,2,3,4])
<Container object of 4 artists>
>>> ax.get_children()
[<matplotlib.axis.XAxis object at 0x6529850>,
<matplotlib.axis.YAxis object at 0x78460d0>,
<matplotlib.patches.Rectangle object at 0x733cc50>,
<matplotlib.patches.Rectangle object at 0x733cdd0>,
<matplotlib.patches.Rectangle object at 0x777f290>,
<matplotlib.patches.Rectangle object at 0x777f710>,
<matplotlib.text.Text object at 0x7836450>,
<matplotlib.patches.Rectangle object at 0x7836390>,
<matplotlib.spines.Spine object at 0x6529950>,
<matplotlib.spines.Spine object at 0x69aef50>,
<matplotlib.spines.Spine object at 0x69ae310>,
<matplotlib.spines.Spine object at 0x69aea50>]
>>> ax.get_children()[2].set_color('r')
#You can also try to locate the first patches.Rectangle object
#instead of direct calling the index.
If you have a complex plot and want to identify the bars first, add those:
>>> import matplotlib
>>> childrenLS=ax.get_children()
>>> barlist=filter(lambda x: isinstance(x, matplotlib.patches.Rectangle), childrenLS)
[<matplotlib.patches.Rectangle object at 0x3103650>,
<matplotlib.patches.Rectangle object at 0x3103810>,
<matplotlib.patches.Rectangle object at 0x3129850>,
<matplotlib.patches.Rectangle object at 0x3129cd0>,
<matplotlib.patches.Rectangle object at 0x3112ad0>]
You may need to handle javax.persistence.RollbackException
Well instead of checking both, you could do if(stream_resolve_include_path($folder)!==false)
. It is slower but kills two birds in one shot.
Another option is to simply ignore the E_WARNING
, not by using @mkdir(...);
(because that would simply waive all possible warnings, not just the directory already exists one), but by registering a specific error handler before doing it:
namespace com\stackoverflow;
set_error_handler(function($errno, $errm) {
if (strpos($errm,"exists") === false) throw new \Exception($errm); //or better: create your own FolderCreationException class
});
mkdir($folder);
/* possibly more mkdir instructions, which is when this becomes useful */
restore_error_handler();
We can add scroll bar even without using Canvas. I have read it in many other post we can't add vertical scroll bar in frame directly etc etc. But after doing many experiment found out way to add vertical as well as horizontal scroll bar :). Please find below code which is used to create scroll bar in treeView and frame.
f = Tkinter.Frame(self.master,width=3)
f.grid(row=2, column=0, columnspan=8, rowspan=10, pady=30, padx=30)
f.config(width=5)
self.tree = ttk.Treeview(f, selectmode="extended")
scbHDirSel =tk.Scrollbar(f, orient=Tkinter.HORIZONTAL, command=self.tree.xview)
scbVDirSel =tk.Scrollbar(f, orient=Tkinter.VERTICAL, command=self.tree.yview)
self.tree.configure(yscrollcommand=scbVDirSel.set, xscrollcommand=scbHDirSel.set)
self.tree["columns"] = (self.columnListOutput)
self.tree.column("#0", width=40)
self.tree.heading("#0", text='SrNo', anchor='w')
self.tree.grid(row=2, column=0, sticky=Tkinter.NSEW,in_=f, columnspan=10, rowspan=10)
scbVDirSel.grid(row=2, column=10, rowspan=10, sticky=Tkinter.NS, in_=f)
scbHDirSel.grid(row=14, column=0, rowspan=2, sticky=Tkinter.EW,in_=f)
f.rowconfigure(0, weight=1)
f.columnconfigure(0, weight=1)
Not the best solution, but here is what I got:
1) Annotate getter you want to initialize with this annotation:
@Retention(RetentionPolicy.RUNTIME)
public @interface Lazy {
}
2) Use this method (can be put in a generic class, or you can change T with Object class) on a object after you read it from database:
public <T> void forceLoadLazyCollections(T entity) {
Session session = getSession().openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.refresh(entity);
if (entity == null) {
throw new RuntimeException("Entity is null!");
}
for (Method m : entityClass.getMethods()) {
Lazy annotation = m.getAnnotation(Lazy.class);
if (annotation != null) {
m.setAccessible(true);
logger.debug(" method.invoke(obj, arg1, arg2,...); {} field", m.getName());
try {
Hibernate.initialize(m.invoke(entity));
}
catch (Exception e) {
logger.warn("initialization exception", e);
}
}
}
}
finally {
session.close();
}
}
I had to transfer texts from an Excel file to an xliff file. We had some texts that were originally in uppercase but those translators didn't use uppercase so I used notepad++ as intermediate to do the conversion.
Since I had the mouse in one hand (to mark in Excel and activate the different windows) I disliked the predefined shortcut (Ctrl+Shift+U) as "U" is too far away for my left hand. I first switched it to Ctrl+Shift+X which worked.
Then I realized, that you can create macros easily, so I recorded one doing:
That macro got assigned that very shortcut (Ctrl+Shift+X) and made my life easy :)
There is comma missing in your tuple.
insert the comma between the tuples as shown:
pack_size = (('1', '1'),('3', '3'),(b, b),(h, h),(d, d), (e, e),(r, r))
Do the same for all
Permanent:
UPDATE
MyTable
SET
MyColumn = UPPER(MyColumn)
Temporary:
SELECT
UPPER(MyColumn) AS MyColumn
FROM
MyTable
How to run a shell script from a Perl program
1. Using system
system($command, @arguments);
For example:
system("sh", "script.sh", "--help" ); system("sh script.sh --help");
System will execute the $command with @arguments and return to your script when finished. You may check $! for certain errors passed to the OS by the external application. Read the documentation for system for the nuances of how various invocations are slightly different.
2. Using
exec
This is very similar to the use of system, but it will terminate your script upon execution. Again, read the documentation for exec for more.
3. Using backticks or
qx//
my $output = `script.sh --option`; my $output = qx/script.sh --option/;
The backtick operator and it's equivalent
qx//
, excute the command and options inside the operator and return that commands output to STDOUT when it finishes.There are also ways to run external applications through creative use of open, but this is advanced use; read the documentation for more.
The simplest way is :
SHOW OPEN TABLES WHERE In_use > 0
You get the locked tables only of the current database.
Declaration of new variables in case statements is what causing problems. Enclosing all case
statements in {}
will limit the scope of newly declared variables to the currently executing case which solves the problem.
switch(choice)
{
case 1: {
// .......
}break;
case 2: {
// .......
}break;
case 3: {
// .......
}break;
}
Try either
sudo apt-get install php-zip
orsudo apt-get install php5.6-zip
Then, you might have to restart your web server.
sudo service apache2 restart
orsudo service nginx restart
If you are installing on centos or fedora OS then use yum in place of apt-get. example:-
sudo yum install php-zip
or
sudo yum install php5.6-zip
and
sudo service httpd restart
You can backup the git repo with git-copy . git-copy saved new project as a bare repo, it means minimum storage cost.
git copy /path/to/project /backup/project.backup
Then you can restore your project with git clone
git clone /backup/project.backup project
Swift version of Stephen Darlington's solution
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(0.1)
// other animation properties
// set view properties
UIView.commitAnimations()
It depends on the database to which you're trying to connect, the method by which you created the connection, and the version of Excel that you're using. (Also, most probably, the version of the relevant ODBC driver on your computer.)
The following examples are using SQL Server 2008 and Excel 2007, both on my local machine.
When I used the Data Connection Wizard (on the Data tab of the ribbon, in the Get External Data section, under From Other Sources), I saw the same thing that you did: the Parameters button was disabled, and adding a parameter to the query, something like select field from table where field2 = ?
, caused Excel to complain that the value for the parameter had not been specified, and the changes were not saved.
When I used Microsoft Query (same place as the Data Connection Wizard), I was able to create parameters, specify a display name for them, and enter values each time the query was run. Bringing up the Connection Properties for that connection, the Parameters... button is enabled, and the parameters can be modified and used as I think you want.
I was also able to do this with an Access database. It seems reasonable that Microsoft Query could be used to create parameterized queries hitting other types of databases, but I can't easily test that right now.
If the path is correct and the name of the image is OK, but you are still getting the error
use:
from skimage import io
img = io.imread(file_path)
instead of:
cv2.imread(file_path)
The function imread loads an image from the specified file and returns it. If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format), the function returns an empty matrix ( Mat::data==NULL ).
yum install gcc-c++
on aws ec2 (aws linux),it works