For those looking for a solution. If you accidentally made pip
requirements with pip list
instead of pip freeze
, and want to convert into pip freeze format. I wrote this R script to do so.
library(tidyverse)
pip_list = read_lines("requirements.txt")
pip_freeze = pip_list %>%
str_replace_all(" \\(", "==") %>%
str_replace_all("\\)$", "")
pip_freeze %>% write_lines("requirements.txt")
Normally, you'd get an RST if you do a close which doesn't linger (i.e. in which data can be discarded by the stack if it hasn't been sent and ACK'd) and a normal FIN if you allow the close to linger (i.e. the close waits for the data in transit to be ACK'd).
Perhaps all you need to do is set your socket to linger so that you remove the race condition between a non lingering close done on the socket and the ACKs arriving?
If anyone else simply wants to display a black image as a background, here e.g. for 500x500 px:
import cv2
import numpy as np
black_screen = np.zeros([500,500,3])
cv2.imshow("Simple_black", black_screen)
cv2.waitKey(0)
You don't need to convert your dates to timestamp before the sorting, but it's a good idea though because it will take more time to sort without it.
$data = array(
array(
"title" => "Another title",
"date" => "Fri, 17 Jun 2011 08:55:57 +0200"
),
array(
"title" => "My title",
"date" => "Mon, 16 Jun 2010 06:55:57 +0200"
)
);
function sortFunction( $a, $b ) {
return strtotime($a["date"]) - strtotime($b["date"]);
}
usort($data, "sortFunction");
var_dump($data);
By default Bootstrap javascript files are included just before the closing body tag
<script src="vendors/jquery-1.9.1.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="vendors/easypiechart/jquery.easy-pie-chart.js"></script>
<script src="assets/scripts.js"></script>
</body>
I took these javascript files into the head section right before the body tag and I wrote a small function to call the modal popup:
<script src="vendors/jquery-1.9.1.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="vendors/easypiechart/jquery.easy-pie-chart.js"></script>
<script src="assets/scripts.js"></script>
<script type="text/javascript">
function openModal() {
$('#myModal').modal('show');
}
</script>
</head>
<body>
then I could call the modal popup from code-behind with the following:
protected void lbEdit_Click(object sender, EventArgs e) {
ScriptManager.RegisterStartupScript(this,this.GetType(),"Pop", "openModal();", true);
}
Since there are several methods presented here, I wanted to figure out which one was fastest. Using Ruby 1.9.3p362:
irb(main):001:0> require 'benchmark'
=> true
irb(main):002:0> Benchmark.realtime { 1.upto(10000000) { "foobar"[/\Afoo/] }}
=> 12.477248
irb(main):003:0> Benchmark.realtime { 1.upto(10000000) { "foobar" =~ /\Afoo/ }}
=> 9.593959
irb(main):004:0> Benchmark.realtime { 1.upto(10000000) { "foobar"["foo"] }}
=> 9.086909
irb(main):005:0> Benchmark.realtime { 1.upto(10000000) { "foobar".start_with?("foo") }}
=> 6.973697
So it looks like start_with?
ist the fastest of the bunch.
Updated results with Ruby 2.2.2p95 and a newer machine:
require 'benchmark'
Benchmark.bm do |x|
x.report('regex[]') { 10000000.times { "foobar"[/\Afoo/] }}
x.report('regex') { 10000000.times { "foobar" =~ /\Afoo/ }}
x.report('[]') { 10000000.times { "foobar"["foo"] }}
x.report('start_with') { 10000000.times { "foobar".start_with?("foo") }}
end
user system total real
regex[] 4.020000 0.000000 4.020000 ( 4.024469)
regex 3.160000 0.000000 3.160000 ( 3.159543)
[] 2.930000 0.000000 2.930000 ( 2.931889)
start_with 2.010000 0.000000 2.010000 ( 2.008162)
In fact,I get into this trouble not long ago,and it's really really easy to fix,you actually do nothing wrong if you setup the "android.intent.action.BOOT_COMPLETED"
permission and intent-filter.
Be attention that if you On Android 4.X,you have to run the broadcast listener before you start service on boot,that means,you have to add an activity first,once your broadcast receiver running,your app should function as you expected,however,on Android 4.X,I haven't found a way to start the service on boot without any activity,I think google did that for security reasons.
Try this:
UPDATE test
SET
field = 1
WHERE id = 123 and condition
var bottom = $('#bottom').position().top + $('#bottom').height();
This ought to do the trick: just limit the result to 1 row; if a row comes back the $lectureName
is Assigned, otherwise it's Available.
function checkLectureStatus($lectureName)
{
$con = connectvar();
mysql_select_db("mydatabase", $con);
$result = mysql_query(
"SELECT * FROM preditors_assigned WHERE lecture_name='$lectureName' LIMIT 1");
if(mysql_fetch_array($result) !== false)
return 'Assigned';
return 'Available';
}
Python 3's range
type works just like Python 2's xrange
. I'm not sure why you're seeing a slowdown, since the iterator returned by your xrange
function is exactly what you'd get if you iterated over range
directly.
I'm not able to reproduce the slowdown on my system. Here's how I tested:
Python 2, with xrange
:
Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import timeit
>>> timeit.timeit("[x for x in xrange(1000000) if x%4]",number=100)
18.631936646865853
Python 3, with range
is a tiny bit faster:
Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:57:17) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import timeit
>>> timeit.timeit("[x for x in range(1000000) if x%4]",number=100)
17.31399508687869
I recently learned that Python 3's range
type has some other neat features, such as support for slicing: range(10,100,2)[5:25:5]
is range(20, 60, 10)
!
You could use the :after
pseudo-selector to achieve this, though I am unsure of the backward compatibility of that selector.
body {
background: #000000
}
body:after {
content:'';
position: fixed;
height: 100%;
width: 50%;
left: 50%;
background: #116699
}
I have used this to have two different gradients on a page background.
ES6 1-liner
// :: splitAt = number => Array<any>|string => Array<Array<any>|string>_x000D_
const splitAt = index => x => [x.slice(0, index), x.slice(index)]_x000D_
_x000D_
console.log(_x000D_
splitAt(1)('foo'), // ["f", "oo"]_x000D_
splitAt(2)([1, 2, 3, 4]) // [[1, 2], [3, 4]]_x000D_
)_x000D_
_x000D_
public static string textDataSource = "Data Source=localhost;Initial Catalog=TEST_C;User ID=sa;Password=P@ssw0rd";
public static DataSet LoaderDataSet(string StrSql)
{
SqlConnection cnn;
SqlDataAdapter dad;
DataSet dts = new DataSet();
cnn = new SqlConnection(textDataSource);
dad = new SqlDataAdapter(StrSql, cnn);
try
{
cnn.Open();
dad.Fill(dts);
cnn.Close();
return dts;
}
catch (Exception)
{
return dts;
}
finally
{
dad.Dispose();
dts = null;
cnn = null;
}
}
Hadley Wickham
dplyr
packages is always a saver in case of data wrangling.
To add the desired division as a third variable I would use mutate()
d <- mutate(d, new = min / count2.freq)
/*
public class UserDAO {
public boolean insertUser(UserBean u) {
boolean flag = false;
MySqlConnection msq = new MySqlConnection();
try {
String sql = "insert into regis values(?,?,?,?,?)";
Connection connection = msq.getConnection();
PreparedStatement statement = null;
statement = (PreparedStatement) connection.prepareStatement(sql);
statement.setString(1, u.getname());
statement.setString(2, u.getlname());
statement.setString(3, u.getemail());
statement.setString(4, u.getusername());
statement.setString(5, u.getpasswords());
statement.executeUpdate();
flag = true;
} catch (Exception e) {
} finally {
return flag;
}
}
public String userValidate(UserBean u) {
String login = "";
MySqlConnection msq = new MySqlConnection();
try {
String email = u.getemail();
String Pass = u.getpasswords();
String sql = "SELECT name FROM regis WHERE email=? and passwords=?";
com.mysql.jdbc.Connection connection = msq.getConnection();
com.mysql.jdbc.PreparedStatement statement = null;
ResultSet rs = null;
statement = (com.mysql.jdbc.PreparedStatement) connection.prepareStatement(sql);
statement.setString(1, email);
statement.setString(2, Pass);
rs = statement.executeQuery();
if (rs.next()) {
login = rs.getString("name");
} else {
login = "false";
}
} catch (Exception e) {
} finally {
return login;
}
}
public boolean getmessage(UserBean u) {
boolean flag = false;
MySqlConnection msq = new MySqlConnection();
try {
String sql = "insert into feedback values(?,?)";
Connection connection = msq.getConnection();
PreparedStatement statement = null;
statement = (PreparedStatement) connection.prepareStatement(sql);
statement.setString(1, u.getemail());
statement.setString(2, u.getfeedback());
statement.executeUpdate();
flag = true;
} catch (Exception e) {
} finally {
return flag;
}
}
public boolean insertOrder(cartbean u) {
boolean flag = false;
MySqlConnection msq = new MySqlConnection();
try {
String sql = "insert into cart (product_id, email, Tprice, quantity) values (?,?,2000,?)";
Connection connection = msq.getConnection();
PreparedStatement statement = null;
statement = (PreparedStatement) connection.prepareStatement(sql);
statement.setString(1, u.getpid());
statement.setString(2, u.getemail());
statement.setString(3, u.getquantity());
statement.executeUpdate();
flag = true;
} catch (Exception e) {
System.out.print("hi");
} finally {
return flag;
}
}
}
Which Mac version are you using? try these paths
/System/Library/Frameworks/JavaVM.framework/ OR
/usr/libexec/java_home
This link might help - How To Set $JAVA_HOME Environment Variable On Mac OS X
You can use -
Ternary oprator to check wheather value set by POST/GET or not somthing like this
$value1 = $_POST['value1'] = isset($_POST['value1']) ? $_POST['value1'] : '';
$value2 = $_POST['value2'] = isset($_POST['value2']) ? $_POST['value2'] : '';
$value3 = $_POST['value3'] = isset($_POST['value3']) ? $_POST['value3'] : '';
$value4 = $_POST['value4'] = isset($_POST['value4']) ? $_POST['value4'] : '';
In addition to Michael's answer, consider a second way: adding linterOptions.exclude to tslint.json
For example, you may have tslint.json
with following lines:
{
"linterOptions": {
"exclude": [
"someDirectory/*.d.ts"
]
}
}
Here is a JS Function to this:
This function is needed because Chrome doesn't accept a base64 encoded string as value for applicationServerKey in pushManager.subscribe yet https://bugs.chromium.org/p/chromium/issues/detail?id=802280
function urlBase64ToUint8Array(base64String) {
var padding = '='.repeat((4 - base64String.length % 4) % 4);
var base64 = (base64String + padding)
.replace(/\-/g, '+')
.replace(/_/g, '/');
var rawData = window.atob(base64);
var outputArray = new Uint8Array(rawData.length);
for (var i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
This error sometimes occurs. The files becomes corrupt. A quick solution thats works for me, is:
With that you force to get the actual files
good luck with that!
You have two ways to do this, I'll call it dirty way and clean way:
1. The dirty way
Create a box from your current virtual environment, using vagrant package
command:
http://docs.vagrantup.com/v2/cli/package.html
Then copy the box to the other pc, add it using vagrant box add
and run it using vagrant up
as usual.
Keep in mind that files in your working directory (the one with the Vagrantfile
) are shared when the virtual machine boots, so you need to copy it to the other pc as well.
2. The clean way
Theoretically it should never be necessary to do export/import with Vagrant. If you have the foresight to use provisioning for configuring the virtual environment (chef, puppet, ansible), and a version control system like git for your working directory, copying an environment would be at this point simple as running:
git clone <your_repo>
vagrant up
$scope.item = {
"id": "3",
"name": "ALL",
};
$scope.CategoryLst = [
{ id: '1', name: 'MD' },
{ id: '2', name: 'CRNA' },
{ id: '3', name: 'ALL' }];
<select ng-model="item.id" ng-selected="3" ng-options="i.id as i.name for i in CategoryLst"></select>
at least pip3 also works without "=", however, instead of "http" you might need "https"
Final command, which worked for me:
sudo pip3 install --proxy https://{proxy}:{port} {BINARY}
You are placing your result in the RETURN
value instead of in the passed @r
value.
From MSDN
(RETURN) Is the integer value that is returned. Stored procedures can return an integer value to a calling procedure or an application.
ALTER procedure S_Comp(@str1 varchar(20),@r varchar(100) out) as
declare @str2 varchar(100)
set @str2 ='welcome to sql server. Sql server is a product of Microsoft'
if(PATINDEX('%'+@str1 +'%',@str2)>0)
SELECT @r = @str1+' present in the string'
else
SELECT @r = @str1+' not present'
DECLARE @r VARCHAR(100)
EXEC S_Comp 'Test', @r OUTPUT
SELECT @r
Both the verifyNoMoreInteractions()
and verifyZeroInteractions()
method internally have the same implementation as:
public static transient void verifyNoMoreInteractions(Object mocks[])
{
MOCKITO_CORE.verifyNoMoreInteractions(mocks);
}
public static transient void verifyZeroInteractions(Object mocks[])
{
MOCKITO_CORE.verifyNoMoreInteractions(mocks);
}
so we can use any one of them on mock object or array of mock objects to check that no methods have been called using mock objects.
And you can combine same events/functions in this way:
$("table.planning_grid").on({
mouseenter: function() {
// Handle mouseenter...
},
mouseleave: function() {
// Handle mouseleave...
},
'click blur paste' : function() {
// Handle click...
}
}, "input");
I have the same problem with collection warning for a field that is set from 0 to 1. All columns collections was the same. We try to change collections again but nothing fix this issue.
At the end we update the field to NULL
and after that we update to 1 and this overcomes the collection problem.
To be honest I just use:
select convert(nvarchar(max), GETDATE(), 112)
which gives YYYYMMDD
and minus one from it.
Or more correctly
select convert(nvarchar(max), GETDATE(), 112) - 1
for yesterdays date.
Replace Getdate()
with your value OrderDate
select convert(nvarchar (max),OrderDate,112)-1 AS SubtractDate FROM Orders
should do it.
I would recommend creating a HashMap
from set A, and then iterating through set B and checking if any element of B is in A. This would run in O(|A|+|B|)
time (as there would be no collisions), whereas retainAll(Collection<?> c)
must run in O(|A|*|B|)
time.
#printing the variable 'Total:' in a format that looks like this '9,348.237'
print ('Total:', '{:7,.3f}'.format(zum1))
where the '{:7,.3f}' es the number of spaces for formatting the number in this case is a million with 3 decimal points. Then you add the '.format(zum1). The zum1 is tha variable that has the big number for the sum of all number in my particular program. Variable can be anything that you decide to use.
I had the same problem,
<body id="body">
Add an ID tag to the body:
$('#body').attr('class',json.class); // My class comes from Ajax/JSON, but change it to whatever you require.
Then switch the class for the body's using the id. This has been tested in Chrome, Internet Explorer, and Safari.
Download and install Python 3.6 and then change the system path environment variable to that of python 3.6 and delete the python 3.7 path system environment variable. Restart pc for results.
You must use invoke and delegate
private delegate void MyLabelDelegate();
label1.Invoke( new MyLabelDelegate(){ label1.Text += 1; });
No, it is not RESTful. The only reason why you should be putting a verb (force_delete
) into the URI is if you would need to overload GET/POST methods in an environment where PUT/DELETE methods are not available. Judging from your use of the DELETE method, this is not the case.
HTTP error code 409/Conflict
should be used for situations where there is a conflict which prevents the RESTful service to perform the operation, but there is still a chance that the user might be able to resolve the conflict himself. A pre-deletion confirmation (where there are no real conflicts which would prevent deletion) is not a conflict per se, as nothing prevents the API from performing the requested operation.
As Alex said (I don't know who downvoted him, he is correct), this should be handled in the UI, because a RESTful service as such just processes requests and should be therefore stateless (i.e. it must not rely on confirmations by holding any server-side information about of a request).
Two examples how to do this in UI would be to:
(*) Please note that HTML versions prior to 5 do not support PUT and DELETE HTTP methods natively, however most modern browsers can do these two methods via AJAX calls. See this thread for details about cross-browser support.
Update (based on additional investigation and discussions):
The scenario where the service would require the force_delete=true
flag to be present violates the uniform interface as defined in Roy Fielding's dissertation. Also, as per HTTP RFC, the DELETE method may be overridden on the origin server (client), implying that this is not done on the target server (service).
So once the service receives a DELETE request, it should process it without needing any additional confirmation (regardless if the service actually performs the operation).
If you are on Linux, you just need to fill the OpenCV_DIR variable with the path of opencv (containing the OpenCVConfig.cmake file)
export OpenCV_DIR=<path_of_opencv>
@user544079
Even though it is very old and irrelevant now, I am replying to help people like me! it should be like this:
<form method="post" action="mailto:$emailID?subject=$MySubject &message= $MyMessageText">
Here $emailID, $MySubject, $MyMessageText are variables which you assign from a FORM or a DATABASE Table or just you can assign values in your code itself. Alternatively you can put the code like this (normally it is not used):
<form method="post" action="mailto:[email protected]?subject=New Registration Alert &message= New Registration requires your approval">
They are HTTP request libraries...
I end up with the same doubt but the table in this post makes me go with isomorphic-fetch
. Which is fetch
but works with NodeJS.
http://andrewhfarmer.com/ajax-libraries/
The link above is dead The same table is here: https://www.javascriptstuff.com/ajax-libraries/
Try this:
#!/bin/bash
# usage: watch [-n integer] COMMAND
case $# in
0)
echo "Usage $0 [-n int] COMMAND"
;;
*)
sleep=2;
;;
esac
if [ "$1" == "-n" ]; then
sleep=$2
shift; shift
fi
while :;
do
clear;
echo "$(date) every ${sleep}s $@"; echo
$@;
sleep $sleep;
done
You can only add folders or jar files to a class loader. So if you have a single class file, you need to put it into the appropriate folder structure first.
Here is a rather ugly hack that adds to the SystemClassLoader at runtime:
import java.io.IOException;
import java.io.File;
import java.net.URLClassLoader;
import java.net.URL;
import java.lang.reflect.Method;
public class ClassPathHacker {
private static final Class[] parameters = new Class[]{URL.class};
public static void addFile(String s) throws IOException {
File f = new File(s);
addFile(f);
}//end method
public static void addFile(File f) throws IOException {
addURL(f.toURL());
}//end method
public static void addURL(URL u) throws IOException {
URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
Class sysclass = URLClassLoader.class;
try {
Method method = sysclass.getDeclaredMethod("addURL", parameters);
method.setAccessible(true);
method.invoke(sysloader, new Object[]{u});
} catch (Throwable t) {
t.printStackTrace();
throw new IOException("Error, could not add URL to system classloader");
}//end try catch
}//end method
}//end class
The reflection is necessary to access the protected method addURL
. This could fail if there is a SecurityManager.
Ok,
I'm using windows 7 ultimate and WAMP 2.4 server The tmp folder was missing, so I created one and this solved my problem. Check the php.ini file for the correct path: session.save_path
In addition to setting USB connection/storage mode to "Camera (PTP)", I also had to enable developer mode, which has been hidden since 4.2.
This works in browser and nodejs Live browser demo
const cpFetch= require('cp-fetch');
const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=3s';
const chain = cpFetch(url, {timeout: 10000})
.then(response => response.json())
.then(data => console.log(`Done: `, data), err => console.log(`Error: `, err))
setTimeout(()=> chain.cancel(), 1000); // abort the request after 1000ms
It's because there can only be one definition of A::a
that all the translation units use.
If you performed static int a = 3;
in a class in a header included in all a translation units then you'd get multiple definitions. Therefore, non out-of-line definition of a static is forcibly made a compiler error.
Using static inline
or static const
remedies this. static inline
only concretises the symbol if it is used in the translation unit and ensures the linker only selects and leaves one copy if it's defined in multiple translation units due to it being in a comdat group. const
at file scope makes the compiler never emit a symbol because it's always substituted immediately in the code unless extern
is used, which is not permitted in a class.
One thing to note is static inline int b;
is treated as a definition whereas static const int b
or static const A b;
are still treated as a declaration and must be defined out-of-line if you don't define it inside the class. Interestingly static constexpr A b;
is treated as a definition, whereas static constexpr int b;
is an error and must have an initialiser (this is because they now become definitions and like any const/constexpr definition at file scope, they require an initialiser which an int doesn't have but a class type does because it has an implicit = A()
when it is a definition -- clang allows this but gcc requires you to explicitly initialise or it is an error. This is not a problem with inline instead). static const A b = A();
is not allowed and must be constexpr
or inline
in order to permit an initialiser for a static object with class type i.e to make a static member of class type more than a declaration. So yes in certain situations A a;
is not the same as explicitly initialising A a = A();
(the former can be a declaration but if only a declaration is allowed for that type then the latter is an error. The latter can only be used on a definition. constexpr
makes it a definition). If you use constexpr
and specify a default constructor then the constructor will need to be constexpr
#include<iostream>
struct A
{
int b =2;
mutable int c = 3; //if this member is included in the class then const A will have a full .data symbol emitted for it on -O0 and so will B because it contains A.
static const int a = 3;
};
struct B {
A b;
static constexpr A c; //needs to be constexpr or inline and doesn't emit a symbol for A a mutable member on any optimisation level
};
const A a;
const B b;
int main()
{
std::cout << a.b << b.b.b;
return 0;
}
A static member is an outright file scope declaration extern int A::a;
(which can only be made in the class and out of line definitions must refer to a static member in a class and must be definitions and cannot contain extern) whereas a non-static member is part of the complete type definition of a class and have the same rules as file scope declarations without extern
. They are implicitly definitions. So int i[]; int i[5];
is a redefinition whereas static int i[]; int A::i[5];
isn't but unlike 2 externs, the compiler will still detect a duplicate member if you do static int i[]; static int i[5];
in the class.
There are several ways to write output from a Visual Studio unit test in C#:
Confirmed in Visual Studio 2013 Professional.
string str = Properties.Settings.Default.myConnectionString;
Starting with Java 5.0 you can specify the type of element in the container:
Collections.<Foo>emptyList()
I concur with the other responses that for cases where you want to return an empty list that stays empty, you should use this approach.
I have read that while the underlying chips are essentially the same, the design of the board is different.
Gamers want performance, and tend to favor overclocking and other things to get high frame rates but which maybe burn out the hardware occasionally.
Businesses want reliability, and tend to favor underclocking so they can be sure that their people can keep working.
Also, I have read that the quadro boards use ECC memory.
If you don't know what ECC memory is about: it's a [relatively] well known fact that sometimes memory "flips bits (experiences errors)". This does not happen too often, but is an unavoidable consequence of the underlying physics of the memory cards and the world we live in. ECC memory adds a small percentage to the cost and a small penalty to the performance and has enough redundancy to correct occasional errors and to detect (but not correct) somewhat rarer errors. Gamers don't care about that kind of accuracy because for gamers those are just very rare visual glitches. Companies do care about that kind of accuracy because those glitches would wind up as glitches in their products or else would require more double or triple checking (which winds up being a 2x or 3x performance penalty for some part of their business).
Another issue I have read about has to do with hooking up the graphics card to third party hardware. In other words: sending the images to another card or to another machine instead of to the screen. Most gamers are just using canned software that doesn't have any use for such capabilities. Companies that use that kind of thing get orders of magnitude performance gains from the more direct connections.
If you already know the list of the possible varible names then try creating a new Object(iconObj) whose properties name are same as object names, Here in below example, iconLib variable will hold two string values , either 'ZondIcons' or 'MaterialIcons'. propertyName is the property of ZondIcons or MaterialsIcon object.
const iconObj = {
ZondIcons,
MaterialIcons,
}
const objValue = iconObj[iconLib][propertyName]
A simple addClass and removeClass will do the trick on what you need..
$('#change').on('click', function() {
$('div').each(function() {
if($(this).hasClass('active')) {
$(this).removeClass('active');
} else {
$(this).addClass('active');
}
});
});
Seee fiddle
I recommend you to learn jquery first before using.
In Visual Studio 2008 and Visual Studio 2005 at least, you can specify changes to environment variables in the project settings.
Open your project. Go to Project -> Properties... Under Configuration Properties -> Debugging, edit the 'Environment' value to set environment variables.
For example, if you want to add the directory "c:\foo\bin" to the path when debugging your application, set the 'Environment' value to "PATH=%PATH%;c:\foo\bin".
1800 INFORMATION is more or less correct, but there are a few issues I wanted to correct.
boost::shared_mutex _access;
void reader()
{
boost::shared_lock< boost::shared_mutex > lock(_access);
// do work here, without anyone having exclusive access
}
void conditional_writer()
{
boost::upgrade_lock< boost::shared_mutex > lock(_access);
// do work here, without anyone having exclusive access
if (something) {
boost::upgrade_to_unique_lock< boost::shared_mutex > uniqueLock(lock);
// do work here, but now you have exclusive access
}
// do more work here, without anyone having exclusive access
}
void unconditional_writer()
{
boost::unique_lock< boost::shared_mutex > lock(_access);
// do work here, with exclusive access
}
Also Note, unlike a shared_lock, only a single thread can acquire an upgrade_lock at one time, even when it isn't upgraded (which I thought was awkward when I ran into it). So, if all your readers are conditional writers, you need to find another solution.
I would use underscore and take care of empty strings too:
var my_object = { a:undefined, b:2, c:4, d:undefined, k: null, p: false, s: '', z: 0 };_x000D_
_x000D_
var result =_.omit(my_object, function(value) {_x000D_
return _.isUndefined(value) || _.isNull(value) || value === '';_x000D_
});_x000D_
_x000D_
console.log(result); //Object {b: 2, c: 4, p: false, z: 0}
_x000D_
If the above answers don't work, try:
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
>>> for line in s.splitlines():
... line = line.strip()
... if not line:continue
... ary.append(line.split(":"))
...
>>> ary
[['Name', ' John Smith'], ['Home', ' Anytown USA'], ['Misc', ' Data with spaces'
]]
>>> dict(ary)
{'Home': ' Anytown USA', 'Misc': ' Data with spaces', 'Name': ' John Smith'}
>>>
I suggest Freewall
. It is a cross-browser and responsive jQuery plugin to help you create many types of grid layouts: flexible layouts, images layouts, nested grid layouts, metro style layouts, pinterest like layouts ... with nice CSS3 animation effects and call back events. Freewall is all-in-one solution for creating dynamic grid layouts for desktop, mobile, and tablet.
Home page and document: also found here
.
You say you're using:
time.asctime(time.localtime(date_in_seconds_from_bash))
where date_in_seconds_from_bash
is presumably the output of date +%s
.
The time.localtime
function, as the name implies, gives you local time.
If you want UTC, use time.gmtime()
rather than time.localtime()
.
As JamesNoonan33's answer says, the output of date +%s
is timezone invariant, so date +%s
is exactly equivalent to date -u %s
. It prints the number of seconds since the "epoch", which is 1970-01-01 00:00:00 UTC
. The output you show in your question is entirely consistent with that:
date -u
Thu Jul 3 07:28:20 UTC 2014
date +%s
1404372514 # 14 seconds after "date -u" command
date -u +%s
1404372515 # 15 seconds after "date -u" command
As discussed somewhat in the question comments, this is one way you could do it:
<input ... ng-model="$parent.storeDefault" value="{{location.id}}">
The above assumes that each location has a field (e.g., id) that holds a unique value.
Note that $parent.storeDefault is used because ng-repeat creates a child scope, and we want to manipulate the storeDefault parameter on the parent scope.
You can KILL the processid.
mysql> show full processlist;
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| Id | User | Host | db | Command | Time | State | Info |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| 1193777 | TestUser12 | 192.168.1.11:3775 | www | Sleep | 25946 | | NULL |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
mysql> kill 1193777;
But:
Or you configure your mysql-server by setting a shorter timeout on wait_timeout
and interactive_timeout
mysql> show variables like "%timeout%";
+--------------------------+-------+
| Variable_name | Value |
+--------------------------+-------+
| connect_timeout | 5 |
| delayed_insert_timeout | 300 |
| innodb_lock_wait_timeout | 50 |
| interactive_timeout | 28800 |
| net_read_timeout | 30 |
| net_write_timeout | 60 |
| slave_net_timeout | 3600 |
| table_lock_wait_timeout | 50 |
| wait_timeout | 28800 |
+--------------------------+-------+
9 rows in set (0.00 sec)
Set with:
set global wait_timeout=3;
set global interactive_timeout=3;
(and also set in your configuration file, for when your server restarts)
But you're treating the symptoms instead of the underlying cause - why are the connections open? If the PHP script finished, shouldn't they close? Make sure your webserver is not using connection pooling...
Actually, in Python 3 the module imp
is marked as DEPRECATED. Well, at least that's true for 3.4.
Instead the reload
function from the importlib
module should be used:
https://docs.python.org/3/library/importlib.html#importlib.reload
But be aware that this library had some API-changes with the last two minor versions.
As far as I can tell, the command is correct, ASSUMING your input file is a valid gzipped tar file. Your output says that it isn't. If you downloaded the file from the internet, you probably didn't get the entire file, try again.
Without more knowledge of the source of your file, nobody here is going to be able to give you a concrete solution, just educated guesses.
@HostListener
is a decorator for the callback/event handler method, so remove the ;
at the end of this line:
@HostListener('click', ['$event.target']);
Here's a working plunker that I generated by copying the code from the API docs, but I put the onClick()
method on the same line for clarity:
import {Component, HostListener, Directive} from 'angular2/core';
@Directive({selector: 'button[counting]'})
class CountClicks {
numberOfClicks = 0;
@HostListener('click', ['$event.target']) onClick(btn) {
console.log("button", btn, "number of clicks:", this.numberOfClicks++);
}
}
@Component({
selector: 'my-app',
template: `<button counting>Increment</button>`,
directives: [CountClicks]
})
export class AppComponent {
constructor() { console.clear(); }
}
Host binding can also be used to listen to global events:
To listen to global events, a target must be added to the event name. The target can be window, document or body (reference)
@HostListener('document:keyup', ['$event'])
handleKeyboardEvent(kbdEvent: KeyboardEvent) { ... }
Another option is to use JavaConfig. Assuming that all stages are already registered as spring beans you just have to:
@Autowired
private List<Stage> stages;
and spring will automatically inject them into this list. If you need to preserve order (upper solution doesn't do that) you can do it in that way:
@Configuration
public class MyConfiguration {
@Autowired
private Stage1 stage1;
@Autowired
private Stage2 stage2;
@Bean
public List<Stage> stages() {
return Lists.newArrayList(stage1, stage2);
}
}
The other solution to preserve order is use a @Order
annotation on beans. Then list will contain beans ordered by ascending annotation value.
@Bean
@Order(1)
public Stage stage1() {
return new Stage1();
}
@Bean
@Order(2)
public Stage stage2() {
return new Stage2();
}
First check path Specified for User Settings file: in Settings -> Build,Execution,Development -> Build Tools -> Maven . The field should have path of the settings.xml of your maven. Also the settings.xml should have correct path of remote repository.
This is the right, cross-browser way to do it :
<input type="text" value="Enter Your Name" onfocus="if(this.value == 'Enter Your Name') { this.value = ''; } " onblur="if(this.value == '') { this.value = 'Enter Your Name'; } " />
foreach (DataGridViewRow row in GridView2.Rows)
{
if ( ! row.IsNewRow)
{
for (int i = 0; i < GridView2.Columns.Count; i++)
{
String header = GridView2.Columns[i].HeaderText;
String cellText = Convert.ToString(row.Cells[i].Value);
}
}
}
Here Before Iterating for cell Values need to check for NewRow.
TextViewPlus.java:
public class TextViewPlus extends TextView {
private static final String TAG = "TextView";
public TextViewPlus(Context context) {
super(context);
}
public TextViewPlus(Context context, AttributeSet attrs) {
super(context, attrs);
setCustomFont(context, attrs);
}
public TextViewPlus(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setCustomFont(context, attrs);
}
private void setCustomFont(Context ctx, AttributeSet attrs) {
TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.TextViewPlus);
String customFont = a.getString(R.styleable.TextViewPlus_customFont);
setCustomFont(ctx, customFont);
a.recycle();
}
public boolean setCustomFont(Context ctx, String asset) {
Typeface typeface = null;
try {
typeface = Typeface.createFromAsset(ctx.getAssets(), asset);
} catch (Exception e) {
Log.e(TAG, "Unable to load typeface: "+e.getMessage());
return false;
}
setTypeface(typeface);
return true;
}
}
attrs.xml: (Where to place res/values)
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="TextViewPlus">
<attr name="customFont" format="string"/>
</declare-styleable>
</resources>
How to use:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:foo="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.mypackage.TextViewPlus
android:id="@+id/textViewPlus1"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:text="@string/showingOffTheNewTypeface"
foo:customFont="my_font_name_regular.otf">
</com.mypackage.TextViewPlus>
</LinearLayout>
Hope this will help you.
Centerlized Model: You can use it from any where!
You just need to call Below Format From your function to this class
DataSet ds = new DataSet();
SqlParameter[] p = new SqlParameter[1];
string Query = "Describe Query Information/either sp, text or TableDirect";
DbConnectionHelper dbh = new DbConnectionHelper ();
ds = dbh. DBConnection("Here you use your Table Name", p , string Query, CommandType.StoredProcedure);
That's it. it's perfect method.
public class DbConnectionHelper {
public DataSet DBConnection(string TableName, SqlParameter[] p, string Query, CommandType cmdText) {
string connString = @ "your connection string here";
//Object Declaration
DataSet ds = new DataSet();
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter sda = new SqlDataAdapter();
try {
//Get Connection string and Make Connection
con.ConnectionString = connString; //Get the Connection String
if (con.State == ConnectionState.Closed) {
con.Open(); //Connection Open
}
if (cmdText == CommandType.StoredProcedure) //Type : Stored Procedure
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = Query;
if (p.Length > 0) // If Any parameter is there means, we need to add.
{
for (int i = 0; i < p.Length; i++) {
cmd.Parameters.Add(p[i]);
}
}
}
if (cmdText == CommandType.Text) // Type : Text
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = Query;
}
if (cmdText == CommandType.TableDirect) //Type: Table Direct
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = Query;
}
cmd.Connection = con; //Get Connection in Command
sda.SelectCommand = cmd; // Select Command From Command to SqlDataAdaptor
sda.Fill(ds, TableName); // Execute Query and Get Result into DataSet
con.Close(); //Connection Close
} catch (Exception ex) {
throw ex; //Here you need to handle Exception
}
return ds;
}
}
I don't think you can make VS wrap at 80 columns (I'd find that terribly annoying) but you can insert a visual guideline at 80 columns so you know when is a good time to insert a newline.
Details on inserting a guideline at 80 characters for 3 different versions of visual studio.
I hope the following will work for you.
<select class="form-control"
ng-model="selectedOption"
ng-options="option.name + ' (' + (option.price | currency:'USD$') + ')' for option in options">
</select>
Reproducing tim_yates answer on current hardware and adding leftShift() and concat() method to check the finding:
'String leftShift' {
foo << bar << baz
}
'String concat' {
foo.concat(bar)
.concat(baz)
.toString()
}
The outcome shows concat() to be the faster solution for a pure String, but if you can handle GString somewhere else, GString template is still ahead, while honorable mention should go to leftShift() (bitwise operator) and StringBuffer() with initial allocation:
Environment
===========
* Groovy: 2.4.8
* JVM: OpenJDK 64-Bit Server VM (25.191-b12, Oracle Corporation)
* JRE: 1.8.0_191
* Total Memory: 238 MB
* Maximum Memory: 3504 MB
* OS: Linux (4.19.13-300.fc29.x86_64, amd64)
Options
=======
* Warm Up: Auto (- 60 sec)
* CPU Time Measurement: On
user system cpu real
String adder 453 7 460 469
String leftShift 287 2 289 295
String concat 169 1 170 173
GString template 24 0 24 24
Readable GString template 32 0 32 32
GString template toString 400 0 400 406
Readable GString template toString 412 0 412 419
StringBuilder 325 3 328 334
StringBuffer 390 1 391 398
StringBuffer with Allocation 259 1 260 265
Just crop the string:
var date = new Date("2013-03-10T02:00:00Z");
date.toISOString().substring(0, 10);
Or if you need only date out of string.
var strDate = "2013-03-10T02:00:00Z";
strDate.substring(0, 10);
You could use SwiftString (https://github.com/amayne/SwiftString) to do this.
"string".length // 6
DISCLAIMER: I wrote this extension
Just for completeness and those unaware XSL 1 has choose for multiple conditions.
<xsl:choose>
<xsl:when test="expression">
... some output ...
</xsl:when>
<xsl:when test="another-expression">
... some output ...
</xsl:when>
<xsl:otherwise>
... some output ....
</xsl:otherwise>
</xsl:choose>
<-
does assignment in the current environment.
When you're inside a function R creates a new environment for you. By default it includes everything from the environment in which it was created so you can use those variables as well but anything new you create will not get written to the global environment.
In most cases <<-
will assign to variables already in the global environment or create a variable in the global environment even if you're inside a function. However, it isn't quite as straightforward as that. What it does is checks the parent environment for a variable with the name of interest. If it doesn't find it in your parent environment it goes to the parent of the parent environment (at the time the function was created) and looks there. It continues upward to the global environment and if it isn't found in the global environment it will assign the variable in the global environment.
This might illustrate what is going on.
bar <- "global"
foo <- function(){
bar <- "in foo"
baz <- function(){
bar <- "in baz - before <<-"
bar <<- "in baz - after <<-"
print(bar)
}
print(bar)
baz()
print(bar)
}
> bar
[1] "global"
> foo()
[1] "in foo"
[1] "in baz - before <<-"
[1] "in baz - after <<-"
> bar
[1] "global"
The first time we print bar we haven't called foo
yet so it should still be global - this makes sense. The second time we print it's inside of foo
before calling baz
so the value "in foo" makes sense. The following is where we see what <<-
is actually doing. The next value printed is "in baz - before <<-" even though the print statement comes after the <<-
. This is because <<-
doesn't look in the current environment (unless you're in the global environment in which case <<-
acts like <-
). So inside of baz
the value of bar stays as "in baz - before <<-". Once we call baz
the copy of bar inside of foo
gets changed to "in baz" but as we can see the global bar
is unchanged. This is because the copy of bar
that is defined inside of foo
is in the parent environment when we created baz
so this is the first copy of bar
that <<-
sees and thus the copy it assigns to. So <<-
isn't just directly assigning to the global environment.
<<-
is tricky and I wouldn't recommend using it if you can avoid it. If you really want to assign to the global environment you can use the assign function and tell it explicitly that you want to assign globally.
Now I change the <<-
to an assign statement and we can see what effect that has:
bar <- "global"
foo <- function(){
bar <- "in foo"
baz <- function(){
assign("bar", "in baz", envir = .GlobalEnv)
}
print(bar)
baz()
print(bar)
}
bar
#[1] "global"
foo()
#[1] "in foo"
#[1] "in foo"
bar
#[1] "in baz"
So both times we print bar inside of foo
the value is "in foo" even after calling baz
. This is because assign
never even considered the copy of bar
inside of foo because we told it exactly where to look. However, this time the value of bar in the global environment was changed because we explicitly assigned there.
Now you also asked about creating local variables and you can do that fairly easily as well without creating a function... We just need to use the local
function.
bar <- "global"
# local will create a new environment for us to play in
local({
bar <- "local"
print(bar)
})
#[1] "local"
bar
#[1] "global"
If your Object is complex I'd suggest to Serialize/XML/JSON it and save those contents to the SD card. You can find additional info on how to save to external storage here: http://developer.android.com/guide/topics/data/data-storage.html#filesExternal
I found a pretty good and simple tutorial about this issue. I think it works great (and though it supports IE, I just tell my clients to use other browsers):
CSS background transparency without affecting child elements, through RGBa and filters
From there you can add gradient support, etc.
Both choices refer to what algorithm the identity provider uses to sign the JWT. Signing is a cryptographic operation that generates a "signature" (part of the JWT) that the recipient of the token can validate to ensure that the token has not been tampered with.
RS256 (RSA Signature with SHA-256) is an asymmetric algorithm, and it uses a public/private key pair: the identity provider has a private (secret) key used to generate the signature, and the consumer of the JWT gets a public key to validate the signature. Since the public key, as opposed to the private key, doesn't need to be kept secured, most identity providers make it easily available for consumers to obtain and use (usually through a metadata URL).
HS256 (HMAC with SHA-256), on the other hand, involves a combination of a hashing function and one (secret) key that is shared between the two parties used to generate the hash that will serve as the signature. Since the same key is used both to generate the signature and to validate it, care must be taken to ensure that the key is not compromised.
If you will be developing the application consuming the JWTs, you can safely use HS256, because you will have control on who uses the secret keys. If, on the other hand, you don't have control over the client, or you have no way of securing a secret key, RS256 will be a better fit, since the consumer only needs to know the public (shared) key.
Since the public key is usually made available from metadata endpoints, clients can be programmed to retrieve the public key automatically. If this is the case (as it is with the .Net Core libraries), you will have less work to do on configuration (the libraries will fetch the public key from the server). Symmetric keys, on the other hand, need to be exchanged out of band (ensuring a secure communication channel), and manually updated if there is a signing key rollover.
Auth0 provides metadata endpoints for the OIDC, SAML and WS-Fed protocols, where the public keys can be retrieved. You can see those endpoints under the "Advanced Settings" of a client.
The OIDC metadata endpoint, for example, takes the form of https://{account domain}/.well-known/openid-configuration
. If you browse to that URL, you will see a JSON object with a reference to https://{account domain}/.well-known/jwks.json
, which contains the public key (or keys) of the account.
If you look at the RS256 samples, you will see that you don't need to configure the public key anywhere: it's retrieved automatically by the framework.
There is a known problem with Java and glibc >= 2.10 (includes Ubuntu >= 10.04, RHEL >= 6).
The cure is to set this env. variable:
export MALLOC_ARENA_MAX=4
If you are running Tomcat, you can add this to TOMCAT_HOME/bin/setenv.sh
file.
For Docker, add this to Dockerfile
ENV MALLOC_ARENA_MAX=4
There is an IBM article about setting MALLOC_ARENA_MAX https://www.ibm.com/developerworks/community/blogs/kevgrig/entry/linux_glibc_2_10_rhel_6_malloc_may_show_excessive_virtual_memory_usage?lang=en
resident memory has been known to creep in a manner similar to a memory leak or memory fragmentation.
There is also an open JDK bug JDK-8193521 "glibc wastes memory with default configuration"
search for MALLOC_ARENA_MAX on Google or SO for more references.
You might want to tune also other malloc options to optimize for low fragmentation of allocated memory:
# tune glibc memory allocation, optimize for low fragmentation
# limit the number of arenas
export MALLOC_ARENA_MAX=2
# disable dynamic mmap threshold, see M_MMAP_THRESHOLD in "man mallopt"
export MALLOC_MMAP_THRESHOLD_=131072
export MALLOC_TRIM_THRESHOLD_=131072
export MALLOC_TOP_PAD_=131072
export MALLOC_MMAP_MAX_=65536
I tested the ByteBuffer method against plain bitwise operations but the latter is significantly faster.
public static byte[] longToBytes(long l) {
byte[] result = new byte[8];
for (int i = 7; i >= 0; i--) {
result[i] = (byte)(l & 0xFF);
l >>= 8;
}
return result;
}
public static long bytesToLong(final byte[] b) {
long result = 0;
for (int i = 0; i < 8; i++) {
result <<= 8;
result |= (b[i] & 0xFF);
}
return result;
}
For Java 8+ we can use the static variables that were added:
public static byte[] longToBytes(long l) {
byte[] result = new byte[Long.BYTES];
for (int i = Long.BYTES - 1; i >= 0; i--) {
result[i] = (byte)(l & 0xFF);
l >>= Byte.SIZE;
}
return result;
}
public static long bytesToLong(final byte[] b) {
long result = 0;
for (int i = 0; i < Long.BYTES; i++) {
result <<= Byte.SIZE;
result |= (b[i] & 0xFF);
}
return result;
}
Here is an illustration of your first import cycle problem.
project/controllers/account
^ \
/ \
/ \
/ \/
project/components/mux <--- project/controllers/base
As you can see with my bad ASCII chart is that you are creating an import cycle when project/components/mux
imports project/controllers/account
. Since Go does not support circular dependencies you get the import cycle not allowed
error during compile time.
If you're using an IntelliJ editor, under
You can type in anything, for instance console:false
, and it will add that to the list (.jshintrc) as well - as a global.
This works for me. Get last value of the column A in Google sheet:
=index(A:A,max(row(A:A)*(A:A<>"")))
(It also skips blank rows in between if any)
As Dudley mentioned in his answer this is possible with the drop-shadow CSS filter for webkit, SVG for Firefox and DirectX filters for Internet Explorer 9-.
One step further is to inline the SVG, eliminating the extra request:
.shadowed {
-webkit-filter: drop-shadow(12px 12px 25px rgba(0,0,0,0.5));
filter: url("data:image/svg+xml;utf8,<svg height='0' xmlns='http://www.w3.org/2000/svg'><filter id='drop-shadow'><feGaussianBlur in='SourceAlpha' stdDeviation='4'/><feOffset dx='12' dy='12' result='offsetblur'/><feFlood flood-color='rgba(0,0,0,0.5)'/><feComposite in2='offsetblur' operator='in'/><feMerge><feMergeNode/><feMergeNode in='SourceGraphic'/></feMerge></filter></svg>#drop-shadow");
-ms-filter: "progid:DXImageTransform.Microsoft.Dropshadow(OffX=12, OffY=12, Color='#444')";
filter: "progid:DXImageTransform.Microsoft.Dropshadow(OffX=12, OffY=12, Color='#444')";
}
Basically yes, JSON is just a javascript literal representation of your value so what you said is correct.
You can find a pretty clear and good explanation of JSON notation on http://json.org/
I'm getting OpenJDK 8 from the official Debian repositories, rather than some random PPA or non-free Oracle binary. Here's how I did it:
sudo apt-get install debian-keyring debian-archive-keyring
Make /etc/apt/sources.list.d/debian-jessie-backports.list
:
deb http://httpredir.debian.org/debian/ jessie-backports main
Make /etc/apt/preferences.d/debian-jessie-backports
:
Package: *
Pin: release o=Debian,a=jessie-backports
Pin-Priority: -200
Then finally do the install:
sudo apt-get update
sudo apt-get -t jessie-backports install openjdk-8-jdk
Well, I faced the same issue. For new users who may land at this page. Just follow their official documentation.
Install flask-cors
pip install -U flask-cors
then after app initialization, initialize flask-cors
with default arguments:
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route("/")
def helloWorld():
return "Hello, cross-origin-world!"
Just add the FormsModule
in the imports
array of app.module.ts
file,
and add import { FormsModule } from '@angular/forms';
at the top of this file...this will work.
You can do this a couple of ways.
Via the "Solution Explorer"
Via the "Package Manager Console"
Install-Package Newtonsoft.Json
For more info on how to use the "Package Manager Console" check out the nuget docs.
I had the problem that windows was blocking it from running (Windows 10 Pro). Right click icon> properties> in the bottom right corner it might tell you "Windows has blocked the functionality........" next to it there is a check box labeled "Unblock"> uncheck the box> apply> option to block goes away and then you can run it.
simplifily, use:
pip install -r requirement.txt
it can install all listed in requirement file.
If you need to distniguish between a click, longpress and a scroll use GestureDetector
Activity implements GestureDetector.OnGestureListener
then create detector in onCreate for example
mDetector = new GestureDetectorCompat(getActivity().getApplicationContext(),this);
then optionally setOnTouchListener on your View (for example webview) where
onTouch(View v, MotionEvent event) {
return mDetector.onTouchEvent(event);
}
and now you can use Override onScroll, onFling, showPress( detect long press) or onSingleTapUp (detect a click)
!pwd
import os
os.chdir('/content/drive/My Drive/Colab Notebooks/Data')
!pwd
view this answer for detailed explaination https://stackoverflow.com/a/61636734/11535267
What do you mean by impacts? Content will flow around a float. That's how they work.
If you want it to appear above your design, try setting:
z-index: 10;
position: absolute;
right: 0;
top: 0;
Try to run dos2unix
on your windows imported files first
For Windows/WSL/Cygwin etc users:
Make sure that your line endings are standard Unix line feeds, i.e. \n
(LF) only.
Using Windows line endings \r\n
(CRLF) line endings will break the command line break.
This is because having \
at the end of a line with Windows line ending translates to
\
\r
\n
.
As Mark correctly explains above:
The line-continuation will fail if you have whitespace after the backslash and before the newline.
This includes not just space () or tabs (
\t
) but also the carriage return (\r
).
SQL Server is not case sensitive. SELECT * FROM SomeTable
is the same as SeLeCT * frOM soMetaBLe
.
Meh too slow. Here's my example anyway :)
http://jsfiddle.net/cqDES/
$(function() {
$('select').change(function() {
var val = $(this).val();
if (val) {
$('div:not(#div' + val + ')').slideUp();
$('#div' + val).slideDown();
} else {
$('div').slideDown();
}
});
});
In my experience the plugins worked with http but not with the latest httpClient. Also, configuring the CORS respsonse headers on the server wasn't really an option. So, I created a proxy.conf.json file to act as a proxy server.
Read more about this here: https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md
below is my prox.conf.json file
{
"/posts": {
"target": "https://example.com",
"secure": true,
"pathRewrite": {
"^/posts": ""
},
"changeOrigin": true
}
}
I placed the proxy.conf.json file right next the the package.json file in the same directory
then I modified the start command in the package.json file like below
"start": "ng serve --proxy-config proxy.conf.json"
now, the http call from my app component is as follows
return this._http.get('/posts/pictures?method=GetPictures')
.subscribe((returnedStuff) => {
console.log(returnedStuff);
});
Lastly to run my app, I'd have to use npm start or ng serve --proxy-config proxy.conf.json
You can use unescapeJava
from org.apache.commons.text.StringEscapeUtils
like below
str = "hello\r\njava\r\nbook";
StringEscapeUtils.unescapeJava(str);
It’s doing integer division. You can make one of the numbers a Float
by adding .0
:
9.0 / 5 #=> 1.8
9 / 5.0 #=> 1.8
One simple way using subplots
:
import matplotlib.pyplot as plt
fig, axes = plt.subplots(3, 4, sharex=True, sharey=True)
# add a big axes, hide frame
fig.add_subplot(111, frameon=False)
# hide tick and tick label of the big axes
plt.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False)
plt.grid(False)
plt.xlabel("common X")
plt.ylabel("common Y")
Some of the webservices require you to place request data and metadata separately. For example a remote function may expect that the signed metadata string is included in a URI, while the data is posted in a HTTP-body.
The POST request may semantically look like this:
POST /?AuthId=YOURKEY&Action=WebServiceAction&Signature=rcLXfkPldrYm04 HTTP/1.1
Content-Type: text/tab-separated-values; charset=iso-8859-1
Content-Length: []
Host: webservices.domain.com
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: identity
User-Agent: Mozilla/3.0 (compatible; Indy Library)
name id
John G12N
Sarah J87M
Bob N33Y
This approach logically combines QueryString and Body-Post using a single Content-Type
which is a "parsing-instruction" for a web-server.
Please note: HTTP/1.1 is wrapped with the #32
(space) on the left and with #10
(Line feed) on the right.
The easisest way to get a posted json string, for example, is to read the contents of 'php://input' and then decode it. For example i had a simple Zend route:
'save-json' => array(
'type' => 'Zend\Mvc\Router\Http\Segment',
'options' => array(
'route' => '/save-json/',
'defaults' => array(
'controller' => 'CDB\Controller\Index',
'action' => 'save-json',
),
),
),
and i wanted to post data to it using Angular's $http.post. The post was fine but the retrive method in Zend
$this->params()->fromPost('paramname');
didn't get anything in this case. So my solution was, after trying all kinds of methods like $_POST and the other methods stated above, to read from 'php://':
$content = file_get_contents('php://input');
print_r(json_decode($content));
I got my json array in the end. Hope this helps.
If you're encoding a string to put in a URL component (a querystring parameter), you should call encodeURIComponent
.
If you're encoding an existing URL, call encodeURI
.
You need a dict
:
my_dict = {'cheese': 'cake'}
Example code (from the docs):
>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True
You can read more about dictionaries here.
You miss the from
clause
SELECT * from TCCAWZTXD.TCC_COIL_DEMODATA WHERE CURRENT_INSERTTIME BETWEEN(CURRENT_TIMESTAMP)-5 minutes AND CURRENT_TIMESTAMP
If you are trying to install it on a windows machine you need to have a 64-bit version of python 3.5. This is the only way to actually install it. From the website:
TensorFlow supports only 64-bit Python 3.5 on Windows. We have tested the pip packages with the following distributions of Python:
Python 3.5 from Anaconda
Python 3.5 from python.org.
You can download the proper version of python from here (make sure you grab one of the ones that says "Windows x86-64")
You should now be able to install with pip install tensorflow
or python -m pip install tensorflow
(make sure that you are using the right pip, from python3, if you have both python2 and python3 installed)
Remember to install Anaconda 3-5.2.0 as the latest version which is 3-5.3.0 have python version 3.7 which is not supported by Tensorflow.
Try:
git add -A
Warning: Starting with git 2.0 (mid 2013), this will always stage files on the whole working tree.
If you want to stage files under the current path of your working tree, you need to use:
git add -A .
Also see: Difference of git add -A
and git add .
I think you are looking for:
window.location = 'http://someUrl.com';
It's not jQuery; it's pure JavaScript.
If you are thinking about using floating-point to help with integer arithmetics, you have to be careful.
I usually try to avoid FP calculations whenever possible.
Floating-point operations are not exact. You can never know for sure what will (int)(Math.log(65536)/Math.log(2))
evaluate to. For example, Math.ceil(Math.log(1<<29) / Math.log(2))
is 30 on my PC where mathematically it should be exactly 29. I didn't find a value for x where (int)(Math.log(x)/Math.log(2))
fails (just because there are only 32 "dangerous" values), but it does not mean that it will work the same way on any PC.
The usual trick here is using "epsilon" when rounding. Like (int)(Math.log(x)/Math.log(2)+1e-10)
should never fail. The choice of this "epsilon" is not a trivial task.
More demonstration, using a more general task - trying to implement int log(int x, int base)
:
The testing code:
static int pow(int base, int power) {
int result = 1;
for (int i = 0; i < power; i++)
result *= base;
return result;
}
private static void test(int base, int pow) {
int x = pow(base, pow);
if (pow != log(x, base))
System.out.println(String.format("error at %d^%d", base, pow));
if(pow!=0 && (pow-1) != log(x-1, base))
System.out.println(String.format("error at %d^%d-1", base, pow));
}
public static void main(String[] args) {
for (int base = 2; base < 500; base++) {
int maxPow = (int) (Math.log(Integer.MAX_VALUE) / Math.log(base));
for (int pow = 0; pow <= maxPow; pow++) {
test(base, pow);
}
}
}
If we use the most straight-forward implementation of logarithm,
static int log(int x, int base)
{
return (int) (Math.log(x) / Math.log(base));
}
this prints:
error at 3^5
error at 3^10
error at 3^13
error at 3^15
error at 3^17
error at 9^5
error at 10^3
error at 10^6
error at 10^9
error at 11^7
error at 12^7
...
To completely get rid of errors I had to add epsilon which is between 1e-11 and 1e-14. Could you have told this before testing? I definitely could not.
In addirion to the good answers here, specifically Robert Lujo's.
I want to say in my case I've been deliberately trying to statically compile a version of ffmpeg. All the required dependencies and what else heretofore required, I've done static compilation.
When I ran ./configure
for the ffmpeg process I didnt notice --enable-shared
was on the commandline. Removing it and running ./configure
is only then I was able to compile correctly (All 56 mbs of an ffmpeg binary). Check that out as well if your intention is static compilation
Putty doesn't use openssh key files - there is a utility in putty suite to convert them.
edit: it is called puttygen
You can override the default css rules with this:
.table tbody tr > td.success {
background-color: #dff0d8 !important;
}
.table tbody tr > td.error {
background-color: #f2dede !important;
}
.table tbody tr > td.warning {
background-color: #fcf8e3 !important;
}
.table tbody tr > td.info {
background-color: #d9edf7 !important;
}
.table-hover tbody tr:hover > td.success {
background-color: #d0e9c6 !important;
}
.table-hover tbody tr:hover > td.error {
background-color: #ebcccc !important;
}
.table-hover tbody tr:hover > td.warning {
background-color: #faf2cc !important;
}
.table-hover tbody tr:hover > td.info {
background-color: #c4e3f3 !important;
}
!important
is needed as bootstrap actually colours the cells individually (afaik it's not possible to just apply background-color to a tr). I couldn't find any colour variables in my version of bootstrap but that's the basic idea anyway.
Please be careful not to overwrite the ";secure" cookie flag in https-sessions. This flag prevents the browser from sending the cookie over an unencrypted http connection, basically rendering the use of https for legit requests pointless.
private void rewriteCookieToHeader(HttpServletRequest request, HttpServletResponse response) {
if (response.containsHeader("SET-COOKIE")) {
String sessionid = request.getSession().getId();
String contextPath = request.getContextPath();
String secure = "";
if (request.isSecure()) {
secure = "; Secure";
}
response.setHeader("SET-COOKIE", "JSESSIONID=" + sessionid
+ "; Path=" + contextPath + "; HttpOnly" + secure);
}
}
This is a very interesting question! As a float requires some bits to store the exponent (=bits_for_exponent
) any floating point number greater than 2**(float_size - bits_for_exponent)
will always be an integral value! At the other extreme a float with a negative exponent will give one of 1
, 0
or -1
. This makes the discussion of integer range versus float range moot because these functions will simply return the original number whenever the number is outside the range of the integer type. The python functions are wrappers of the C
function and so this is really a deficiency of the C
functions where they should have returned an integer and forced the programer to do the range/NaN
/Inf
check before calling ceil/floor.
Thus the logical answer is the only time these functions are useful they would return a value within integer range and so the fact they return a float is a mistake and you are very smart for realizing this!
Use BOOST_BINARY (Yes, you can use it in C).
#include <boost/utility/binary.hpp>
...
int bin = BOOST_BINARY(110101);
This macro is expanded to an octal literal during preprocessing.
It is not necessary to have two routes.
Simply add
(/*)?
at the end of yourpath
string.For example,
app.get('/hello/world(/*)?' /* ... */)
Here is a fully working example, feel free to copy and paste this into a .js file to run with node, and play with it in a browser (or curl):
const app = require('express')()
// will be able to match all of the following
const test1 = 'http://localhost:3000/hello/world'
const test2 = 'http://localhost:3000/hello/world/'
const test3 = 'http://localhost:3000/hello/world/with/more/stuff'
// but fail at this one
const failTest = 'http://localhost:3000/foo/world'
app.get('/hello/world(/*)?', (req, res) => res.send(`
This will match at example endpoints: <br><br>
<pre><a href="${test1}">${test1}</a></pre>
<pre><a href="${test2}">${test2}</a></pre>
<pre><a href="${test3}">${test3}</a></pre>
<br><br> Will NOT match at: <pre><a href="${failTest}">${failTest}</a></pre>
`))
app.listen(3000, () => console.log('Check this out in a browser at http://localhost:3000/hello/world!'))
Here is the code I use in my C++ app.
Positive points :
Negative points :
// Inspired from http://stackoverflow.com/a/15281070/1529139
// and http://stackoverflow.com/q/40059902/1529139
bool signalCtrl(DWORD dwProcessId, DWORD dwCtrlEvent)
{
bool success = false;
DWORD thisConsoleId = GetCurrentProcessId();
// Leave current console if it exists
// (otherwise AttachConsole will return ERROR_ACCESS_DENIED)
bool consoleDetached = (FreeConsole() != FALSE);
if (AttachConsole(dwProcessId) != FALSE)
{
// Add a fake Ctrl-C handler for avoid instant kill is this console
// WARNING: do not revert it or current program will be also killed
SetConsoleCtrlHandler(nullptr, true);
success = (GenerateConsoleCtrlEvent(dwCtrlEvent, 0) != FALSE);
FreeConsole();
}
if (consoleDetached)
{
// Create a new console if previous was deleted by OS
if (AttachConsole(thisConsoleId) == FALSE)
{
int errorCode = GetLastError();
if (errorCode == 31) // 31=ERROR_GEN_FAILURE
{
AllocConsole();
}
}
}
return success;
}
Usage example :
DWORD dwProcessId = ...;
if (signalCtrl(dwProcessId, CTRL_C_EVENT))
{
cout << "Signal sent" << endl;
}
For the extension method fans:
public static bool RegexStartsWith(this string str, params string[] patterns)
{
return patterns.Any(pattern =>
Regex.Match(str, "^("+pattern+")").Success);
}
Usage
var answer = str.RegexStartsWith("mailto","ftp","joe");
//or
var answer2 = str.RegexStartsWith("mailto|ftp|joe");
//or
bool startsWithWhiteSpace = " does this start with space or tab?".RegexStartsWith(@"\s");
I'm not a Java developer so unfortunatly I can't comment on your code directly however I found this in an Oracle FAQ regarding the form of a connection string
jdbc:oracle:<drivertype>:<username/password>@<database>
From the Oracle JDBC FAQ
http://www.oracle.com/technetwork/database/enterprise-edition/jdbc-faq-090281.html#05_03
Hope that helps
In my case it was an issue of the PHP version.
The .phar file I was using was not compatible with PHP 5.3.9. Switching interpreter to PHP 7 did fix it.
I can provide two ways,
a.jsp,
<html>
<script language="javascript" type="text/javascript">
function call(){
var name = "xyz";
window.location.replace("a.jsp?name="+name);
}
</script>
<input type="button" value="Get" onclick='call()'>
<%
String name=request.getParameter("name");
if(name!=null){
out.println(name);
}
%>
</html>
b.jsp,
<script>
var v="xyz";
</script>
<%
String st="<script>document.writeln(v)</script>";
out.println("value="+st);
%>
Don't use quotation in a field name or table name inside the query.
After fetching an object you need to access object attributes/properties (in your case id) by attributes/properties name.
One note: please use mysqli_* or PDO since mysql_* deprecated. Here it is using mysqli:
session_start();
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = new mysqli('localhost', 'username', 'password', 'db_name');
$link->set_charset('utf8mb4'); // always set the charset
$name = $_GET["username"];
$stmt = $link->prepare("SELECT id FROM Users WHERE username=? limit 1");
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
$value = $result->fetch_object();
$_SESSION['myid'] = $value->id;
Bonus tips: Use limit 1 for this type of scenario, it will save execution time :)
I would have your main thread pass a callback method to your first thread, and when it's done, it will invoke the callback method on the mainthread, which can launch the second thread. This keeps your main thread from hanging while its waiting for a Join or Waithandle. Passing methods as delegates is a useful thing to learn with C# anyway.
Yes, this is confusing...
According to this blog post, it looks like this is an omission from WPF.
To make it work you need to use a style:
<Border Name="ClearButtonBorder" Grid.Column="1" CornerRadius="0,3,3,0">
<Border.Style>
<Style>
<Setter Property="Border.Background" Value="Blue"/>
<Style.Triggers>
<Trigger Property="Border.IsMouseOver" Value="True">
<Setter Property="Border.Background" Value="Green" />
</Trigger>
</Style.Triggers>
</Style>
</Border.Style>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="X" />
</Border>
I guess this problem isn't that common as most people tend to factor out this sort of thing into a style, so it can be used on multiple controls.
In this simple example you can just put synchronized
as a modifier after public
in both method signatures.
More complex scenarios require other stuff.
key
is a function that will be called to transform the collection's items before they are compared. The parameter passed to key
must be something that is callable.
The use of lambda
creates an anonymous function (which is callable). In the case of sorted
the callable only takes one parameters. Python's lambda
is pretty simple. It can only do and return one thing really.
The syntax of lambda
is the word lambda
followed by the list of parameter names then a single block of code. The parameter list and code block are delineated by colon. This is similar to other constructs in python as well such as while
, for
, if
and so on. They are all statements that typically have a code block. Lambda is just another instance of a statement with a code block.
We can compare the use of lambda with that of def to create a function.
adder_lambda = lambda parameter1,parameter2: parameter1+parameter2
def adder_regular(parameter1, parameter2): return parameter1+parameter2
lambda just gives us a way of doing this without assigning a name. Which makes it great for using as a parameter to a function.
variable
is used twice here because on the left hand of the colon it is the name of a parameter and on the right hand side it is being used in the code block to compute something.
It may be helpful to think about strong and weak references in terms of balloons.
A balloon will not fly away as long as at least one person is holding on to a string attached to it. The number of people holding strings is the retain count. When no one is holding on to a string, the ballon will fly away (dealloc). Many people can have strings to that same balloon. You can get/set properties and call methods on the referenced object with both strong and weak references.
A strong reference is like holding on to a string to that balloon. As long as you are holding on to a string attached to the balloon, it will not fly away.
A weak reference is like looking at the balloon. You can see it, access it's properties, call it's methods, but you have no string to that balloon. If everyone holding onto the string lets go, the balloon flies away, and you cannot access it anymore.
you can use:
adb shell su -c "your command here"
only rooted devices with su works.
If you have a copy of backup of SQL Server setup then you could add features (Management Tools Basic/Complete) as you requested.
Please use the below steps in Windows machine:
Use Below Code:
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
if isNetworkAvailable() returns true
then internet connection available, otherwise internet connection not available
Here need to add below uses-permission in your application Manifest file
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
If you need just a left margin, you can try this:
UItextField *textField = [[UITextField alloc] initWithFrame:...];
UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, textField.frame.size.height)];
leftView.backgroundColor = textField.backgroundColor;
textField.leftView = leftView;
textField.leftViewMode = UITextFieldViewModeAlways;
It works for me. I hope this may help.
you may forgot to wrap your object with $()
var tableChild = children[i];
tableChild.val("my Value");// this is wrong
and the ccorrect one is
$(tableChild).val("my Value");// this is correct
Short answer is : to prevent pollution of the Global (or higher) scope.
IIFE (Immediately Invoked Function Expressions) is the best practice for writing scripts as plug-ins, add-ons, user scripts or whatever scripts are expected to work with other people's scripts. This ensures that any variable you define does not give undesired effects on other scripts.
This is the other way to write IIFE expression. I personally prefer this following method:
void function() {
console.log('boo!');
// expected output: "boo!"
}();
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void
From the example above it is very clear that IIFE can also affect efficiency and performance, because the function that is expected to be run only once will be executed once and then dumped into the void for good. This means that function or method declaration does not remain in memory.
I know the question is a few years old now, but expanding on Ivella's last idea, this bash script estimates the line count of a big file within seconds or less by measuring the size of one line and extrapolating from it:
#!/bin/bash
head -2 $1 | tail -1 > $1_oneline
filesize=$(du -b $1 | cut -f -1)
linesize=$(du -b $1_oneline | cut -f -1)
rm $1_oneline
echo $(expr $filesize / $linesize)
If you name this script lines.sh
, you can call lines.sh bigfile.txt
to get the estimated number of lines. In my case (about 6 GB, export from database), the deviation from the true line count was only 3%, but ran about 1000 times faster. By the way, I used the second, not first, line as the basis, because the first line had column names and the actual data started in the second line.
class of my button is "input-addon btn btn-default fileinput-exists"
below code helped me
document.querySelector('.input-addon.btn.btn-default.fileinput-exists').click();
but I want to click second button, I have two buttons in my screen so I used querySelectorAll
var elem = document.querySelectorAll('.input-addon.btn.btn-default.fileinput-exists');
elem[1].click();
here elem[1] is the second button object that I want to click.
In Spring Boot 2 the spring.http.multipart
changed to spring.servlet.multipart
Your command is completely incorrect. The output format is not rawvideo
and you don't need the bitstream filter h264_mp4toannexb
which is used when you want to convert the h264
contained in an mp4
to the Annex B
format used by MPEG-TS
for example. What you want to use instead is the aac_adtstoasc
for the AAC
streams.
ffmpeg -i http://.../playlist.m3u8 -c copy -bsf:a aac_adtstoasc output.mp4
I found another free site that will constantly ping your site called Unidler
Same as pingdom, but doesnt need to log in.
Based off Simon McKenzie's answer to this question, I'd suggest using a pair of methods like this:
public static void ZipFolder(string sourceFolder, string zipFile)
{
if (!System.IO.Directory.Exists(sourceFolder))
throw new ArgumentException("sourceDirectory");
byte[] zipHeader = new byte[] { 80, 75, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
using (System.IO.FileStream fs = System.IO.File.Create(zipFile))
{
fs.Write(zipHeader, 0, zipHeader.Length);
}
dynamic shellApplication = Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application"));
dynamic source = shellApplication.NameSpace(sourceFolder);
dynamic destination = shellApplication.NameSpace(zipFile);
destination.CopyHere(source.Items(), 20);
}
public static void UnzipFile(string zipFile, string targetFolder)
{
if (!System.IO.Directory.Exists(targetFolder))
System.IO.Directory.CreateDirectory(targetFolder);
dynamic shellApplication = Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application"));
dynamic compressedFolderContents = shellApplication.NameSpace(zipFile).Items;
dynamic destinationFolder = shellApplication.NameSpace(targetFolder);
destinationFolder.CopyHere(compressedFolderContents);
}
}
You can use ALTER
command to modify the table schema.
The syntax for modifying the column size is
ALTER table table_name modify COLUMN column_name varchar (size);
.hover()
function accepts two function arguments, one for mouseenter
event and one for mouseleave
event.
There are many methods to do this using constraint widget of the activity.xml page of android studio.
Two most common methods are:
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
start.set(2010, 7, 23);
end.set(2010, 8, 26);
Date startDate = start.getTime();
Date endDate = end.getTime();
long startTime = startDate.getTime();
long endTime = endDate.getTime();
long diffTime = endTime - startTime;
long diffDays = diffTime / (1000 * 60 * 60 * 24);
DateFormat dateFormat = DateFormat.getDateInstance();
System.out.println("The difference between "+
dateFormat.format(startDate)+" and "+
dateFormat.format(endDate)+" is "+
diffDays+" days.");
This will not work when crossing daylight savings time (or leap seconds) as orange80 pointed out and might as well not give the expected results when using different times of day. Using JodaTime might be easier for correct results, as the only correct way with plain Java before 8 I know is to use Calendar's add and before/after methods to check and adjust the calculation:
start.add(Calendar.DAY_OF_MONTH, (int)diffDays);
while (start.before(end)) {
start.add(Calendar.DAY_OF_MONTH, 1);
diffDays++;
}
while (start.after(end)) {
start.add(Calendar.DAY_OF_MONTH, -1);
diffDays--;
}
Here's what I use:
<logger name="org.hibernate">
<level value="warn"/>
</logger>
<logger name="org.hibernate.SQL">
<level value="warn"/>
</logger>
<logger name="org.hibernate.type">
<level value="warn"/>
</logger>
<root>
<priority value="info"/>
<appender-ref ref="C1"/>
</root>
Obviously, I don't like to see Hibernate messages ;) -- set the level to "debug" to get the output.
You actually do not want to get the path to your main class. According to your example you want to get the current working directory, i.e. directory where your program started. In this case you can just say new File(".").getAbsolutePath()
I had a similar issues once. I deleted the primary key from TABLE A but when I was trying to delete the foreign key column from table B I was shown the above same error.
You can't drop the foreign key using the column name and to bypass this in PHPMyAdmin or with MySQL, first remove the foreign key constraint before renaming or deleting the attribute.
Here is the split function I use:
--
-- split function
-- s : string to split
-- del : delimiter
-- i : index requested
--
DROP FUNCTION IF EXISTS SPLIT_STRING;
DELIMITER $
CREATE FUNCTION
SPLIT_STRING ( s VARCHAR(1024) , del CHAR(1) , i INT)
RETURNS VARCHAR(1024)
DETERMINISTIC -- always returns same results for same input parameters
BEGIN
DECLARE n INT ;
-- get max number of items
SET n = LENGTH(s) - LENGTH(REPLACE(s, del, '')) + 1;
IF i > n THEN
RETURN NULL ;
ELSE
RETURN SUBSTRING_INDEX(SUBSTRING_INDEX(s, del, i) , del , -1 ) ;
END IF;
END
$
DELIMITER ;
SET @agg = "G1;G2;G3;G4;" ;
SELECT SPLIT_STRING(@agg,';',1) ;
SELECT SPLIT_STRING(@agg,';',2) ;
SELECT SPLIT_STRING(@agg,';',3) ;
SELECT SPLIT_STRING(@agg,';',4) ;
SELECT SPLIT_STRING(@agg,';',5) ;
SELECT SPLIT_STRING(@agg,';',6) ;
Yes, there is a problem with pointers. Very likely you're using one that's not initialized properly, but it's also possible that you're messing up your memory management with double frees or some such.
To avoid uninitialized pointers as local variables, try declaring them as late as possible, preferably (and this isn't always possible) when they can be initialized with a meaningful value. Convince yourself that they will have a value before they're being used, by examining the code. If you have difficulty with that, initialize them to a null pointer constant (usually written as NULL
or 0
) and check them.
To avoid uninitialized pointers as member values, make sure they're initialized properly in the constructor, and handled properly in copy constructors and assignment operators. Don't rely on an init
function for memory management, although you can for other initialization.
If your class doesn't need copy constructors or assignment operators, you can declare them as private member functions and never define them. That will cause a compiler error if they're explicitly or implicitly used.
Use smart pointers when applicable. The big advantage here is that, if you stick to them and use them consistently, you can completely avoid writing delete
and nothing will be double-deleted.
Use C++ strings and container classes whenever possible, instead of C-style strings and arrays. Consider using .at(i)
rather than [i]
, because that will force bounds checking. See if your compiler or library can be set to check bounds on [i]
, at least in debug mode. Segmentation faults can be caused by buffer overruns that write garbage over perfectly good pointers.
Doing those things will considerably reduce the likelihood of segmentation faults and other memory problems. They will doubtless fail to fix everything, and that's why you should use valgrind now and then when you don't have problems, and valgrind and gdb when you do.
Is it somewhere else?
Apache! - it has both gcd and lcm, so cool!
However, due to profoundness of their implementation, it's slower compared to simple hand-written version (if it matters).
How do you format an
unsigned long long int
usingprintf
?
Since C99 use an "ll"
(ell-ell) before the conversion specifiers o,u,x,X
.
In addition to base 10 options in many answers, there are base 16 and base 8 options:
Choices include
unsigned long long num = 285212672;
printf("Base 10: %llu\n", num);
num += 0xFFF; // For more interesting hex/octal output.
printf("Base 16: %llX\n", num); // Use uppercase A-F
printf("Base 16: %llx\n", num); // Use lowercase a-f
printf("Base 8: %llo\n", num);
puts("or 0x,0X prefix");
printf("Base 16: %#llX %#llX\n", num, 0ull); // When non-zero, print leading 0x
printf("Base 16: %#llx %#llx\n", num, 0ull);
printf("Base 16: 0x%llX\n", num); // My hex fave: lower case prefix, with A-F
Output
Base 10: 285212672
Base 16: 11000FFF
Base 16: 11000fff
Base 8: 2100007777
or 0x,0X prefix
Base 16: 0X11000FFF 0
Base 16: 0x11000fff 0
Base 16: 0x11000FFF
Just building on what others have said. I found that the following works quite well.
public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> input, string queryString)
{
if (string.IsNullOrEmpty(queryString))
return input;
int i = 0;
foreach (string propname in queryString.Split(','))
{
var subContent = propname.Split('|');
if (Convert.ToInt32(subContent[1].Trim()) == 0)
{
if (i == 0)
input = input.OrderBy(x => GetPropertyValue(x, subContent[0].Trim()));
else
input = ((IOrderedEnumerable<T>)input).ThenBy(x => GetPropertyValue(x, subContent[0].Trim()));
}
else
{
if (i == 0)
input = input.OrderByDescending(x => GetPropertyValue(x, subContent[0].Trim()));
else
input = ((IOrderedEnumerable<T>)input).ThenByDescending(x => GetPropertyValue(x, subContent[0].Trim()));
}
i++;
}
return input;
}
/"(?:[^"\\]|\\.)*"/
Works in The Regex Coach and PCRE Workbench.
Example of test in JavaScript:
var s = ' function(){ return " Is big \\"problem\\", \\no? "; }';_x000D_
var m = s.match(/"(?:[^"\\]|\\.)*"/);_x000D_
if (m != null)_x000D_
alert(m);
_x000D_
If you are fortunate enough to be running Python 3.4+, you can use pathlib
:
>>> from pathlib import Path
>>> dirname = '/home/reports'
>>> filename = 'daily'
>>> suffix = '.pdf'
>>> Path(dirname, filename).with_suffix(suffix)
PosixPath('/home/reports/daily.pdf')
Create a method and call it to close the JFrame, for example:
public void CloseJframe(){
super.dispose();
}
The OP needed to cast as string outside the {% set ... %}
.
But if that not your case you can do:
{% set curYear = 2013 | string() %}
Note that you need the parenthesis on that jinja filter.
If you're concatenating 2 variables, you can also use the ~
custom operator.
There is an api in Express.
res.sendFile
app.get('/report/:chart_id/:user_id', function (req, res) {
// res.sendFile(filepath);
});
Basically, it depends on the TableModel that you are using for your JTable. If you are using the DefaultTableModel
then you can do it in two ways:
DefaultTableModel dm = (DefaultTableModel)table.getModel();
dm.getDataVector().removeAllElements();
dm.fireTableDataChanged(); // notifies the JTable that the model has changed
or
DefaultTableModel dm = (DefaultTableModel)table.getModel();
while(dm.getRowCount() > 0)
{
dm.removeRow(0);
}
See the JavaDoc of DefaultTableModel for more details
Method #1. Here is the simple function to test if the string contains HTML data:
function isHTML(str) {
var a = document.createElement('div');
a.innerHTML = str;
for (var c = a.childNodes, i = c.length; i--; ) {
if (c[i].nodeType == 1) return true;
}
return false;
}
The idea is to allow browser DOM parser to decide if provided string looks like an HTML or not. As you can see it simply checks for ELEMENT_NODE
(nodeType
of 1).
I made a couple of tests and looks like it works:
isHTML('<a>this is a string</a>') // true
isHTML('this is a string') // false
isHTML('this is a <b>string</b>') // true
This solution will properly detect HTML string, however it has side effect that img/vide/etc. tags will start downloading resource once parsed in innerHTML.
Method #2. Another method uses DOMParser and doesn't have loading resources side effects:
function isHTML(str) {
var doc = new DOMParser().parseFromString(str, "text/html");
return Array.from(doc.body.childNodes).some(node => node.nodeType === 1);
}
Notes:
1. Array.from
is ES2015 method, can be replaced with [].slice.call(doc.body.childNodes)
.
2. Arrow function in some
call can be replaced with usual anonymous function.
Or you can insert raw sql part to conditions so I have 'conditions'=>array('Member.id NOT IN (SELECT Membership.member_id FROM memberships AS Membership)')
I had problems with collations as I had most of the tables with Modern_Spanish_CI_AS
, but a few, which I had inherited or copied from another Database, had SQL_Latin1_General_CP1_CI_AS
collation.
In my case, the easiest way to solve the problem has been as follows:
I hope this helps other users.
You can have a list of lists. Convert your tuple of tuples to a list of lists using:
level1 = [list(row) for row in level1]
or
level1 = map(list, level1)
and modify them accordingly.
But a numpy array is cooler.
For a good quality x264 encoding of 1060i, done by a computer, not a mobile device, not in real time, you could use a bitrate at about 5 MBps. That means 2250 MB/hour of encoded material. Recommend you deinterlace the footage and compress as progressive.
I will did this:
df = df.apply(lambda x: x.str.strip()).replace('', np.nan)
or
df = df.apply(lambda x: x.str.strip() if isinstance(x, str) else x).replace('', np.nan)
You can strip all str, then replace empty str with np.nan
.
Yes, right click the project. Click Run as
then Run Configurations
. You can change the parameters passed to the JVM in the Arguments
tab in the VM Arguments
box.
That configuration can then be used as the default when running the project.
Wrote the below function that allows me to quickly check to see if an index exists; works just like OBJECT_ID.
CREATE FUNCTION INDEX_OBJECT_ID (
@tableName VARCHAR(128),
@indexName VARCHAR(128)
)
RETURNS INT
AS
BEGIN
DECLARE @objectId INT
SELECT @objectId = i.object_id
FROM sys.indexes i
WHERE i.object_id = OBJECT_ID(@tableName)
AND i.name = @indexName
RETURN @objectId
END
GO
EDIT: This just returns the OBJECT_ID of the table, but it will be NULL if the index doesn't exist. I suppose you could set this to return index_id, but that isn't super useful.
This only work below IE 11 version.
var ie_version = parseInt(window.navigator.userAgent.substring(window.navigator.userAgent.indexOf("MSIE ") + 5, window.navigator.userAgent.indexOf(".", window.navigator.userAgent.indexOf("MSIE "))));
console.log("version number",ie_version);
The difference between a tuple and a class is that a tuple has no property names. This is almost never a good thing, and I would only use a tuple when the arguments are fairly meaningless like in an abstract math formula Eg. abstract calculus over 5,6,7 dimensions might take a tuple for the coordinates.
~/.gradle/gradle.properties:
mavenUser=admin
mavenPassword=admin123
build.gradle:
...
authentication(userName: mavenUser, password: mavenPassword)
Use waitpid() like this:
pid_t childPid; // the child process that the execution will soon run inside of.
childPid = fork();
if(childPid == 0) // fork succeeded
{
// Do something
exit(0);
}
else if(childPid < 0) // fork failed
{
// log the error
}
else // Main (parent) process after fork succeeds
{
int returnStatus;
waitpid(childPid, &returnStatus, 0); // Parent process waits here for child to terminate.
if (returnStatus == 0) // Verify child process terminated without error.
{
printf("The child process terminated normally.");
}
if (returnStatus == 1)
{
printf("The child process terminated with an error!.");
}
}
Is there any way to dump the call stack in a running process in C or C++ every time a certain function is called?
You can use a macro function instead of return statement in the specific function.
For example, instead of using return,
int foo(...)
{
if (error happened)
return -1;
... do something ...
return 0
}
You can use a macro function.
#include "c-callstack.h"
int foo(...)
{
if (error happened)
NL_RETURN(-1);
... do something ...
NL_RETURN(0);
}
Whenever an error happens in a function, you will see Java-style call stack as shown below.
Error(code:-1) at : so_topless_ranking_server (sample.c:23)
Error(code:-1) at : nanolat_database (sample.c:31)
Error(code:-1) at : nanolat_message_queue (sample.c:39)
Error(code:-1) at : main (sample.c:47)
Full source code is available here.
async
is used for binding to Observables and Promises, but it seems like you're binding to a regular object. You can just remove both async
keywords and it should probably work.
You will have to hand code it, SQL Profiler reveals the following.
SMSE executes quite a long string of queries when it generates the statement.
The following query (or something along its lines) is used to extract the text:
SELECT
NULL AS [Text],
ISNULL(smsp.definition, ssmsp.definition) AS [Definition]
FROM
sys.all_objects AS sp
LEFT OUTER JOIN sys.sql_modules AS smsp ON smsp.object_id = sp.object_id
LEFT OUTER JOIN sys.system_sql_modules AS ssmsp ON ssmsp.object_id = sp.object_id
WHERE
(sp.type = N'P' OR sp.type = N'RF' OR sp.type='PC')and(sp.name=N'#test___________________________________________________________________________________________________________________00003EE1' and SCHEMA_NAME(sp.schema_id)=N'dbo')
It returns the pure CREATE which is then substituted with ALTER in code somewhere.
The SET ANSI NULL stuff and the GO statements and dates are all prepended to this.
Go with sp_helptext, its simpler ...
In AngularJS you can redirect your form (on submit) to other page by using window.location.href='';
like below:
postData(email){
if (email=='undefined') {
this.Utils.showToast('Invalid Email');
} else {
var origin = 'Dubai';
this.download.postEmail(email, origin).then(data => {
...
});
window.location.href = "https://www.thesoftdesign.com/";
}
}
Simply try this:
window.location.href = "https://www.thesoftdesign.com/";
You don't need to calculate anything, and probably shouldn't:
<!DOCTYPE html>
<head>
<style type="text/css">
body {background: blue; height:100%;}
header {background: red; height: 20px; width:100%}
h1 {font-size:1.2em; margin:0; padding:0;
height: 30px; font-weight: bold; background:yellow}
.theCalcDiv {background-color:green; padding-bottom: 100%}
</style>
</head>
<body>
<header>Some nav stuff here</header>
<h1>This is the heading</h1>
<div class="theCalcDiv">This blocks needs to have a CSS calc() height of 100% - the height of the other elements.
</div>
I stuck it all together for brevity.
I know it's an old post ... but it may be useful for someone ... in a "functional" way ...
import Data.List
safeIndex :: [a] -> Int -> Maybe a
safeIndex xs i
| (i> -1) && (length xs > i) = Just (xs!!i)
| otherwise = Nothing
Umair R's answer is mostly the right move to solve the problem, as this error used to be caused by the missing links between opencv libs and the programme. so there is the need to specify the ld_libraty_path configuration. ps. the usual library path is suppose to be:
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib
I have tried this and it worked well.
In my case, this error message shown when I don't added optional property to constructor.
struct Event: Identifiable, Codable {
var id: String
var summary: String
var description: String?
// also has other props...
init(id: String, summary: String, description: String?){
self.id = id
self.summary = summary
self.description = description
}
}
// skip pass description
// It show message "Type of expression is ambiguous without more context"
Event(
id: "1",
summary: "summary",
)
// pass description explicity pass nil to description
Event(
id: "1",
summary: "summary",
description: nil
)
but it looks always not occured.
I test in my playground this code, it show warning about more concrete
var str = "Hello, playground"
struct User {
var id: String
var name: String?
init(id: String, name: String?) {
self.id = id
self.name = name
}
}
User(id: "hoge") // Missing argument for parameter 'name' in call
The fact that the first digit has to be in the range 5-9
only applies in case of two digits. So, check for that in the case of 2 digits, and allow any more digits directly:
^([5-9]\d|\d{3,})$
This regexp has beginning/ending anchors to make sure you're checking all digits, and the string actually represents a number. The |
means "or", so either [5-9]\d
or any number with 3 or more digits. \d
is simply a shortcut for [0-9]
.
Edit: To disallow numbers like 001
:
^([5-9]\d|[1-9]\d{2,})$
This forces the first digit to be not a zero in the case of 3 or more digits.
If you need to run such search only once then you can probably go with any of the scripts already shown in other answers. But otherwise, I’d recommend using ApexSQL Search for this. It’s a free SSMS addin and it really saved me a lot of time.
Before running any of the scripts you should customize it based on the data type you want to search. If you know you are searching for datetime column then there is no need to search through nvarchar columns. This will speed up all of the queries above.
Try this:
DateTime Date = DateTime.Now.AddHours(-DateTime.Now.Hour).AddMinutes(-DateTime.Now.Minute)
.AddSeconds(-DateTime.Now.Second);
Output will be like:
07/29/2015 00:00:00
I had the same problem a month ago on Windows 10. Whenever I tried to access http://localhost/ it led me to the IIS page. I tried removing the IIS feature from windows features. Once I was sure it was gone, I tried running XAMPP, but it still did not work. I did not want to mess with the configuration files. But from this, I was quite sure it had something to do with my web browser. So, deleted the cache from the web browser I was using (Google Chrome).
To do so, I went to:
Chrome > Settings > Show Advanced Settings > Privacy > Clear browsing data > Clear Cached images and files.
Its almost the same process for any web browsers. Right after that, I was able to run XAMPP without any problem!
Hope it helps!
Following things are not mentioned in the existing answers : Buffer size configuration HTTP Header and Nesting.
Buffer size configuration for ob_start :
ob_start(null, 4096); // Once the buffer size exceeds 4096 bytes, PHP automatically executes flush, ie. the buffer is emptied and sent out.
The above code improve server performance as PHP will send bigger chunks of data, for example, 4KB (wihout ob_start call, php will send each echo to the browser).
If you start buffering without the chunk size (ie. a simple ob_start()), then the page will be sent once at the end of the script.
Output buffering does not affect the HTTP headers, they are processed in different way. However, due to buffering you can send the headers even after the output was sent, because it is still in the buffer.
ob_start(); // turns on output buffering
$foo->bar(); // all output goes only to buffer
ob_clean(); // delete the contents of the buffer, but remains buffering active
$foo->render(); // output goes to buffer
ob_flush(); // send buffer output
$none = ob_get_contents(); // buffer content is now an empty string
ob_end_clean(); // turn off output buffering
Nicely explained here : https://phpfashion.com/everything-about-output-buffering-in-php
<style>
p{border: 1px solid red}
div{border: 5px solid blue}
Call me Ishmael.
Call me Ishmael.
Just don't call me late for dinner.
The C++ spec doesn't say exactly what algorithm you must use for the STL containers. It does, however, put certain constraints on their performance, which rules out the use of hash tables for map
and other associative containers. (They're most commonly implemented with red/black trees.) These constraints require better worst-case performance for these containers than hash tables can deliver.
Many people really do want hash tables, however, so hash-based STL associative containers have been a common extension for years. Consequently, they added unordered_map
and such to later versions of the C++ standard.
Use arrays:
{
"number": ["1", "2", "3"],
"alphabet": ["a", "b", "c"]
}
You can the access the different values from their position in the array. Counting starts at left of array at 0. myJsonObject["number"][0] == 1
or myJsonObject["alphabet"][2] == 'c'
They are not bad, but actually helpful. I had a huge problem some time ago where I had to embed my twitter feed and it just wouldn't let md do it on the same page, so I set it on a different page, and put it in as an iframe.
They are also good because all browsers (and phone browsers) support them. They can not be considered a bad practice, as long as you use them correctly.
I was running into the problem where i had the json with some common keys. I wanted to group all the values having the same key. After some surfing I found hashmap package. Which is really helpful.
To group the element with the same key, I used multi(key:*, value:*, key2:*, value2:*, ...)
.
This package is somewhat similar to Java Hashmap collection, but not as powerful as Java Hashmap.
I'm surprised that there are no answers with a straightforward idiomatic React solution at the moment I'm writing. So here's the one (compare the size and complexity to others):
class P extends React.Component {
state = { foo : "" };
render(){
const { foo } = this.state;
return (
<div>
<C1 value={ foo } onChange={ x => this.setState({ foo : x })} />
<C2 value={ foo } />
</div>
)
}
}
const C1 = ({ value, onChange }) => (
<input type="text"
value={ value }
onChange={ e => onChange( e.target.value ) } />
);
const C2 = ({ value }) => (
<div>Reacting on value change: { value }</div>
);
I'm setting the state of a parent element from a child element. This seems to betray the design principle of React: single-direction data flow.
Any controlled input
(idiomatic way of working with forms in React) updates the parent state in its onChange
callback and still doesn't betray anything.
Look carefully at C1 component, for instance. Do you see any significant difference in the way how C1
and built-in input
component handle the state changes? You should not, because there is none. Lifting up the state and passing down value/onChange pairs is idiomatic for raw React. Not usage of refs, as some answers suggest.
Just as a reference, here is an example of how to convert between String
and char[]
with a dynamic length -
// Define
String str = "This is my string";
// Length (with one extra character for the null terminator)
int str_len = str.length() + 1;
// Prepare the character array (the buffer)
char char_array[str_len];
// Copy it over
str.toCharArray(char_array, str_len);
Yes, this is painfully obtuse for something as simple as a type conversion, but sadly it's the easiest way.
#access a {
border-bottom: 2px solid #fff;
color: #eee;
display: block;
line-height: 3.333em;
padding: 0 10px 0 20px;
text-decoration: none;
}
I see that you had used line-height but you gave it to <a>
tag instead of <ul>
Try this:
#access ul {line-height:3.333em;}
You wouldn't need to play with margins then.
No need to hack your editor, or switch editors.
Instead we can come up with a script to watch your development directories and chmod files as they're created. This is what I've done in the attached bash script. You probably want to read through the comments and edit the 'config' section as fits your needs, then I would suggest putting it in your $HOME/bin/ directory and adding its execution to your $HOME/.login or similar file. Or you can just run it from the terminal.
This script does require inotifywait, which comes in the inotify-tools package on Ubuntu,
sudo apt-get install inotify-tools
Suggestions/edits/improvements are welcome.
#!/usr/bin/env bash
# --- usage --- #
# Depends: 'inotifywait' available in inotify-tools on Ubuntu
#
# Edit the 'config' section below to reflect your working directory, WORK_DIR,
# and your watched directories, WATCH_DIR. Each directory in WATCH_DIR will
# be logged by inotify and this script will 'chmod +x' any new files created
# therein. If SUBDIRS is 'TRUE' this script will watch WATCH_DIRS recursively.
# I recommend adding this script to your $HOME/.login or similar to have it
# run whenever you log into a shell, eg 'echo "watchdirs.sh &" >> ~/.login'.
# This script will only allow one instance of itself to run at a time.
# --- config --- #
WORK_DIR="$HOME/path/to/devel" # top working directory (for cleanliness?)
WATCH_DIRS=" \
$WORK_DIR/dirA \
$WORK_DIR/dirC \
" # list of directories to watch
SUBDIRS="TRUE" # watch subdirectories too
NOTIFY_ARGS="-e create -q" # watch for create events, non-verbose
# --- script starts here --- #
# probably don't need to edit beyond this point
# kill all previous instances of myself
SCRIPT="bash.*`basename $0`"
MATCHES=`ps ax | egrep $SCRIPT | grep -v grep | awk '{print $1}' | grep -v $$`
kill $MATCHES >& /dev/null
# set recursive notifications (for subdirectories)
if [ "$SUBDIRS" = "TRUE" ] ; then
RECURSE="-r"
else
RECURSE=""
fi
while true ; do
# grab an event
EVENT=`inotifywait $RECURSE $NOTIFY_ARGS $WATCH_DIRS`
# parse the event into DIR, TAGS, FILE
OLDIFS=$IFS ; IFS=" " ; set -- $EVENT
E_DIR=$1
E_TAGS=$2
E_FILE=$3
IFS=$OLDIFS
# skip if it's not a file event or already executable (unlikely)
if [ ! -f "$E_DIR$E_FILE" ] || [ -x "$E_DIR$E_FILE" ] ; then
continue
fi
# set file executable
chmod +x $E_DIR$E_FILE
done
You can call Stored Procedure like this inside Stored Procedure B.
CREATE PROCEDURE spA
@myDate DATETIME
AS
EXEC spB @myDate
RETURN 0