As MDN Window.history() describes :
For top-level pages you can see the list of pages in the session history, accessible via the History object, in the browser's dropdowns next to the back and forward buttons.
For security reasons the History object doesn't allow the non-privileged code to access the URLs of other pages in the session history, but it does allow it to navigate the session history.
There is no way to clear the session history or to disable the back/forward navigation from unprivileged code. The closest available solution is the location.replace() method, which replaces the current item of the session history with the provided URL.
So there is no Javascript method to clear the session history, instead, if you want to block navigating back to a certain page, you can use the location.replace() method, and pass the page link as parameter, which will not push the page to the browser's session history list. For example, there are three pages:
a.html:
<!doctype html>
<html>
<head>
<title>a.html page</title>
<meta charset="utf-8">
</head>
<body>
<p>This is <code style="color:red">a.html</code> page ! Go to <a href="b.html">b.html</a> page !</p>
</body>
</html>
b.html:
<!doctype html>
<html>
<head>
<title>b.html page</title>
<meta charset="utf-8">
</head>
<body>
<p>This is <code style="color:red">b.html</code> page ! Go to <a id="jumper" href="c.html">c.html</a> page !</p>
<script type="text/javascript">
var jumper = document.getElementById("jumper");
jumper.onclick = function(event) {
var e = event || window.event ;
if(e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = true ;
}
location.replace(this.href);
jumper = null;
}
</script>
</body>
c.html:
<!doctype html>
<html>
<head>
<title>c.html page</title>
<meta charset="utf-8">
</head>
<body>
<p>This is <code style="color:red">c.html</code> page</p>
</body>
</html>
With href link, we can navigate from a.html to b.html to c.html. In b.html, we use the location.replace(c.html)
method to navigate from b.html to c.html. Finally, we go to c.html*, and if we click the back button in the browser, we will jump to **a.html.
So this is it! Hope it helps.
Based off your code, i created this Fiddle
You need to use
var cb = document.getElementsByName('field206451')[0];
var label = document.getElementsByName('label206451')[0];
if you want to use name attributes then you have to take the index since it is a list of items, not just a single one. Everything else worked good.
Try this code.
startPoint.distanceTo(endPoint) function returns the distance between those places in meters.
Location startPoint=new Location("locationA");
startPoint.setLatitude(17.372102);
startPoint.setLongitude(78.484196);
Location endPoint=new Location("locationA");
endPoint.setLatitude(17.375775);
endPoint.setLongitude(78.469218);
double distance=startPoint.distanceTo(endPoint);
here "distance" is our required result in Meters. I hope it will work for android.
You can't subtract a list from a list.
>>> [3, 7] - [1, 2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'list' and 'list'
Simple way to do it is using numpy
:
>>> import numpy as np
>>> np.array([3, 7]) - np.array([1, 2])
array([2, 5])
You can also use list comprehension, but it will require changing code in the function:
>>> [a - b for a, b in zip([3, 7], [1, 2])]
[2, 5]
>>> import numpy as np
>>>
>>> def Naive_Gauss(Array,b):
... n = len(Array)
... for column in xrange(n-1):
... for row in xrange(column+1, n):
... xmult = Array[row][column] / Array[column][column]
... Array[row][column] = xmult
... #print Array[row][col]
... for col in xrange(0, n):
... Array[row][col] = Array[row][col] - xmult*Array[column][col]
... b[row] = b[row]-xmult*b[column]
... print Array
... print b
... return Array, b # <--- Without this, the function will return `None`.
...
>>> print Naive_Gauss(np.array([[2,3],[4,5]]),
... np.array([[6],[7]]))
[[ 2 3]
[-2 -1]]
[[ 6]
[-5]]
(array([[ 2, 3],
[-2, -1]]), array([[ 6],
[-5]]))
I find WebScarab very powerful
The xts package provides a last
function:
library(xts)
a <- 1:100
last(a)
[1] 100
Just to clarify, the reason why there is no member like contains()
in these container types is because it would open you up to writing inefficient code. Such a method would probably just do a this->find(key) != this->end()
internally, but consider what you do when the key is indeed present; in most cases you'll then want to get the element and do something with it. This means you'd have to do a second find()
, which is inefficient. It's better to use find directly, so you can cache your result, like so:
auto it = myContainer.find(key);
if (it != myContainer.end())
{
// Do something with it, no more lookup needed.
}
else
{
// Key was not present.
}
Of course, if you don't care about efficiency, you can always roll your own, but in that case you probably shouldn't be using C++... ;)
I know this topic is a bit old, but I think I did something that may be useful for someone, so I'm posting it.
I compiled suggestions from this thread's answers into a procedure:
CREATE OR REPLACE PROCEDURE create_table_if_doesnt_exist(
p_table_name VARCHAR2,
create_table_query VARCHAR2
) AUTHID CURRENT_USER IS
n NUMBER;
BEGIN
SELECT COUNT(*) INTO n FROM user_tables WHERE table_name = UPPER(p_table_name);
IF (n = 0) THEN
EXECUTE IMMEDIATE create_table_query;
END IF;
END;
You can then use it in a following way:
call create_table_if_doesnt_exist('my_table', 'CREATE TABLE my_table (
id NUMBER(19) NOT NULL PRIMARY KEY,
text VARCHAR2(4000),
modified_time TIMESTAMP
)'
);
I know that it's kinda redundant to pass table name twice, but I think that's the easiest here.
Hope somebody finds above useful :-).
myDropDown.Items.Remove(myDropDown.Items.FindByText("TextToFind"))
Most likely you don't want to deactivate this Header completely, but use SAMEORIGIN
. If you are using the Java Configs (Spring Boot
) and would like to allow the X-Frame-Options: SAMEORIGIN
, then you would need to use the following.
For older Spring Security versions:
http
.headers()
.addHeaderWriter(new XFrameOptionsHeaderWriter(XFrameOptionsHeaderWriter.XFrameOptionsMode.SAMEORIGIN))
For newer versions like Spring Security 4.0.2:
http
.headers()
.frameOptions()
.sameOrigin();
Throwing another answer into the ring, this will give you those columns and more:
SELECT col.TABLE_CATALOG AS [Database]
, col.TABLE_SCHEMA AS Owner
, col.TABLE_NAME AS TableName
, col.COLUMN_NAME AS ColumnName
, col.ORDINAL_POSITION AS OrdinalPosition
, col.COLUMN_DEFAULT AS DefaultSetting
, col.DATA_TYPE AS DataType
, col.CHARACTER_MAXIMUM_LENGTH AS MaxLength
, col.DATETIME_PRECISION AS DatePrecision
, CAST(CASE col.IS_NULLABLE
WHEN 'NO' THEN 0
ELSE 1
END AS bit)AS IsNullable
, COLUMNPROPERTY(OBJECT_ID('[' + col.TABLE_SCHEMA + '].[' + col.TABLE_NAME + ']'), col.COLUMN_NAME, 'IsIdentity')AS IsIdentity
, COLUMNPROPERTY(OBJECT_ID('[' + col.TABLE_SCHEMA + '].[' + col.TABLE_NAME + ']'), col.COLUMN_NAME, 'IsComputed')AS IsComputed
, CAST(ISNULL(pk.is_primary_key, 0)AS bit)AS IsPrimaryKey
FROM INFORMATION_SCHEMA.COLUMNS AS col
LEFT JOIN(SELECT SCHEMA_NAME(o.schema_id)AS TABLE_SCHEMA
, o.name AS TABLE_NAME
, c.name AS COLUMN_NAME
, i.is_primary_key
FROM sys.indexes AS i JOIN sys.index_columns AS ic ON i.object_id = ic.object_id
AND i.index_id = ic.index_id
JOIN sys.objects AS o ON i.object_id = o.object_id
LEFT JOIN sys.columns AS c ON ic.object_id = c.object_id
AND c.column_id = ic.column_id
WHERE i.is_primary_key = 1)AS pk ON col.TABLE_NAME = pk.TABLE_NAME
AND col.TABLE_SCHEMA = pk.TABLE_SCHEMA
AND col.COLUMN_NAME = pk.COLUMN_NAME
WHERE col.TABLE_NAME = 'YourTableName'
AND col.TABLE_SCHEMA = 'dbo'
ORDER BY col.TABLE_NAME, col.ORDINAL_POSITION;
You need to specify the column in both expressions.
SELECT * FROM transactions WHERE id NOT LIKE '1%' AND id NOT LIKE '2%'
Same issue.
I solved the problem first activating (right click mouse and select activate) from control panel (network connections) and later changing to set mode to allow (by netsh command), to finally starting the hostednetwork with other netsh command, that is:
1.- Activate (Network Connections) by right click
2.- netsh wlan set hostednetwork mode=allow
3.- netsh wlan start hosted network
Good luck mate !!!
You can call java myProg arg1 arg2 ...
:
public static void main (String args[]) {
BufferedReader in = new BufferedReader(new FileReader(args[0]));
}
Dark magic function incantation for those who want the find ... xargs ... head ...
solution above, but in easy to use function form so you don't have to think:
#define the function
find_newest_file_matching_pattern_under_directory(){
echo $(find $1 -name $2 -print0 | xargs -0 ls -1 -t | head -1)
}
#setup:
#mkdir /tmp/files_to_move
#cd /tmp/files_to_move
#touch file1.txt
#touch file2.txt
#invoke the function:
newest_file=$( find_newest_file_matching_pattern_under_directory /tmp/files_to_move/ bc* )
echo $newest_file
Prints:
file2.txt
Which is:
The filename with the oldest modified timestamp of the file under the given directory matching the given pattern.
If your design can accommodate it, avoid local time conversion all together!
I know to some this might sound insane but think about UX: users process near, relative dates (today, yesterday, next Monday) faster than absolute dates (2010.09.17, Friday Sept 17) on glance. And when you think about it more, the accuracy of timezones (and DST) is more important the closer the date is to now()
, so if you can express dates/datetimes in a relative format for +/- 1 or 2 weeks, the rest of the dates can be UTC and it wont matter too much to 95% of users.
This way you can store all dates in UTC and do the relative comparisons in UTC and simply show the user UTC dates outside of your Relative Date Threshold.
This can also apply to user input too (but generally in a more limited fashion). Selecting from a drop down that only has { Yesterday, Today, Tomorrow, Next Monday, Next Thursday } is so much simpler and easier for the user than a date picker. Date pickers are some of the most pain inducing components of form filling. Of course this will not work for all cases but you can see that it only takes a little clever design to make it very powerful.
Thanks to Evan's code sample, I was able to modify it more and get it more specific to tables starting with, specific column names AND handle specifics for constraints too. I ran that code and then copied the [CODE] column and executed it without issue.
USE [Table_Name]
GO
SELECT
TABLE_CATALOG
,TABLE_SCHEMA
,TABLE_NAME
,COLUMN_NAME
,DATA_TYPE
,'ALTER TABLE ['+TABLE_SCHEMA+'].['+TABLE_NAME+'] DROP CONSTRAINT [DEFAULT_'+TABLE_NAME+'_'+COLUMN_NAME+'];
ALTER TABLE ['+TABLE_SCHEMA+'].['+TABLE_NAME+'] ALTER COLUMN ['+COLUMN_NAME+'] datetime2 (7) NOT NULL
ALTER TABLE ['+TABLE_SCHEMA+'].['+TABLE_NAME+'] ADD CONSTRAINT [DEFAULT_'+TABLE_NAME+'_'+COLUMN_NAME+'] DEFAULT (''3/6/2018 6:47:23 PM'') FOR ['+COLUMN_NAME+'];
GO' AS '[CODE]'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE 'form_%' AND TABLE_SCHEMA = 'dbo'
AND (COLUMN_NAME = 'FormInserted' OR COLUMN_NAME = 'FormUpdated')
AND DATA_TYPE = 'datetime'
A URL must not contain a literal space. It must either be encoded using the percent-encoding or a different encoding that uses URL-safe characters (like application/x-www-form-urlencoded that uses +
instead of %20
for spaces).
But whether the statement is right or wrong depends on the interpretation: Syntactically, a URI must not contain a literal space and it must be encoded; semantically, a %20
is not a space (obviously) but it represents a space.
a = np.array([1,2,3,4,5,6,7,8,9])
b = a[(a>2) & (a<8)]
This seems to work fine:
<button onclick="location.href='mailto:[email protected]';">send mail</button>
I solved my problem using this code, is a somewhat replacement for the missing splice.
let str = "I need to remove a character from this";
let pos = str.indexOf("character")
if(pos>-1){
let result = str.slice(0, pos-2) + str.slice(pos, str.length);
console.log(result) //I need to remove character from this
}
I needed to remove a character before/after a certain word, after you get the position the string is split in two and then recomposed by flexibly removing characters using an offset along pos
mac os x don't use com numbers. you have to use something like 'ser:devicename' , 9600
In this state:
The thread is reading and processing rows for a SELECT statement, and sending data to the client.
Because operations occurring during this this state tend to perform large amounts of disk access (reads).
That's why it takes more time to complete and so is the longest-running state over the lifetime of a given query.
Today I find use parseInt()
is also a good and clean practice. A onChange(e)
example is below.
onChange(e){
this.setState({[e.target.id]: parseInt(e.target.value) ? parseInt(e.target.value) : ''})
}
parseInt()
would return NaN
if the parameter is not a number.parseInt('12a')
would return 12.If you want to present it modally, you should have something like bellow:
let vc = self.storyboard!.instantiateViewControllerWithIdentifier("YourViewControllerID")
self.showDetailViewController(vc as! YourViewControllerClassName, sender: self)
//div[@id='..' and @class='...]
should do the trick. That's selecting the div
operators that have both attributes of the required value.
It's worth using one of the online XPath testbeds to try stuff out.
some tests we did in our team show that A.class.isAssignableFrom(B.getClass())
works faster than B instanceof A
. this can be very useful if you need to check this on large number of elements.
private void Form1_Load(object sender, System.EventArgs e)
{
ToolTip toolTip1 = new ToolTip();
toolTip1.AutoPopDelay = 5000;
toolTip1.InitialDelay = 1000;
toolTip1.ReshowDelay = 500;
toolTip1.ShowAlways = true;
toolTip1.SetToolTip(this.button1, "My button1");
toolTip1.SetToolTip(this.checkBox1, "My checkBox1");
}
There's only one error:
cout.cpp:26:29: error: no match for ‘operator<<’ in ‘std::operator<< [with _Traits = std::char_traits]((* & std::cout), ((const char*)"my structure ")) << m’
This means that the compiler couldn't find a matching overload for operator<<
. The rest of the output is the compiler listing operator<<
overloads that didn't match. The third line actually says this:
cout.cpp:26:29: note: candidates are:
Another example : I use it to group Data by date. But some data don't have date. I can group it with the header "NoDate"
This is one of good articles talking about eval and how it is not an evil: http://www.nczonline.net/blog/2013/06/25/eval-isnt-evil-just-misunderstood/
I’m not saying you should go run out and start using eval() everywhere. In fact, there are very few good use cases for running eval() at all. There are definitely concerns with code clarity, debugability, and certainly performance that should not be overlooked. But you shouldn’t be afraid to use it when you have a case where eval() makes sense. Try not using it first, but don’t let anyone scare you into thinking your code is more fragile or less secure when eval() is used appropriately.
In case the file your variable holds doesn't actually exist the FOR
approach won't work. One trick you could use, if you know the length of the extension, is taking a substring:
%var:~0,-4%
the -4
means that the last 4 digits (presumably .ext) will be truncated.
For large arrays, the (excellent) answer given by @Demitri is far faster than the answer currently marked as best. I've adapted his exact algorithm in the following two ways:
The function below works whether or not the input array is sorted.
The function below returns the index of the input array corresponding to the closest value, which is somewhat more general.
Note that the function below also handles a specific edge case that would lead to a bug in the original function written by @Demitri. Otherwise, my algorithm is identical to his.
def find_idx_nearest_val(array, value):
idx_sorted = np.argsort(array)
sorted_array = np.array(array[idx_sorted])
idx = np.searchsorted(sorted_array, value, side="left")
if idx >= len(array):
idx_nearest = idx_sorted[len(array)-1]
elif idx == 0:
idx_nearest = idx_sorted[0]
else:
if abs(value - sorted_array[idx-1]) < abs(value - sorted_array[idx]):
idx_nearest = idx_sorted[idx-1]
else:
idx_nearest = idx_sorted[idx]
return idx_nearest
Instead of creating a new route for that, you could just redirect to your controller/action and pass the information via querystring. For instance:
protected void Application_Error(object sender, EventArgs e) {
Exception exception = Server.GetLastError();
Response.Clear();
HttpException httpException = exception as HttpException;
if (httpException != null) {
string action;
switch (httpException.GetHttpCode()) {
case 404:
// page not found
action = "HttpError404";
break;
case 500:
// server error
action = "HttpError500";
break;
default:
action = "General";
break;
}
// clear error on server
Server.ClearError();
Response.Redirect(String.Format("~/Error/{0}/?message={1}", action, exception.Message));
}
Then your controller will receive whatever you want:
// GET: /Error/HttpError404
public ActionResult HttpError404(string message) {
return View("SomeView", message);
}
There are some tradeoffs with your approach. Be very very careful with looping in this kind of error handling. Other thing is that since you are going through the asp.net pipeline to handle a 404, you will create a session object for all those hits. This can be an issue (performance) for heavily used systems.
if you are anything like me coming from a google search and looking to remove an html element with cool animation, then this could help you:
$(document).ready(function() {_x000D_
_x000D_
var $deleteButton = $('.deleteItem');_x000D_
_x000D_
$deleteButton.on('click', function(event) {_x000D_
_x000D_
event.preventDefault();_x000D_
_x000D_
var $button = $(this);_x000D_
_x000D_
if(confirm('Are you sure about this ?')) {_x000D_
_x000D_
var $item = $button.closest('tr.item');_x000D_
_x000D_
$item.addClass('removed-item')_x000D_
_x000D_
.one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(e) {_x000D_
_x000D_
$(this).remove();_x000D_
});_x000D_
}_x000D_
_x000D_
});_x000D_
_x000D_
});
_x000D_
/**_x000D_
* Credit to Sara Soueidan_x000D_
* @link https://github.com/SaraSoueidan/creative-list-effects/blob/master/css/styles-3.css_x000D_
*/_x000D_
_x000D_
.removed-item {_x000D_
-webkit-animation: removed-item-animation .8s cubic-bezier(.65,-0.02,.72,.29);_x000D_
-o-animation: removed-item-animation .8s cubic-bezier(.65,-0.02,.72,.29);_x000D_
animation: removed-item-animation .8s cubic-bezier(.65,-0.02,.72,.29)_x000D_
}_x000D_
_x000D_
@keyframes removed-item-animation {_x000D_
0% {_x000D_
opacity: 1;_x000D_
-webkit-transform: translateX(0);_x000D_
-ms-transform: translateX(0);_x000D_
-o-transform: translateX(0);_x000D_
transform: translateX(0)_x000D_
}_x000D_
_x000D_
30% {_x000D_
opacity: 1;_x000D_
-webkit-transform: translateX(50px);_x000D_
-ms-transform: translateX(50px);_x000D_
-o-transform: translateX(50px);_x000D_
transform: translateX(50px)_x000D_
}_x000D_
_x000D_
80% {_x000D_
opacity: 1;_x000D_
-webkit-transform: translateX(-800px);_x000D_
-ms-transform: translateX(-800px);_x000D_
-o-transform: translateX(-800px);_x000D_
transform: translateX(-800px)_x000D_
}_x000D_
_x000D_
100% {_x000D_
opacity: 0;_x000D_
-webkit-transform: translateX(-800px);_x000D_
-ms-transform: translateX(-800px);_x000D_
-o-transform: translateX(-800px);_x000D_
transform: translateX(-800px)_x000D_
}_x000D_
}_x000D_
_x000D_
@-webkit-keyframes removed-item-animation {_x000D_
0% {_x000D_
opacity: 1;_x000D_
-webkit-transform: translateX(0);_x000D_
transform: translateX(0)_x000D_
}_x000D_
_x000D_
30% {_x000D_
opacity: 1;_x000D_
-webkit-transform: translateX(50px);_x000D_
transform: translateX(50px)_x000D_
}_x000D_
_x000D_
80% {_x000D_
opacity: 1;_x000D_
-webkit-transform: translateX(-800px);_x000D_
transform: translateX(-800px)_x000D_
}_x000D_
_x000D_
100% {_x000D_
opacity: 0;_x000D_
-webkit-transform: translateX(-800px);_x000D_
transform: translateX(-800px)_x000D_
}_x000D_
}_x000D_
_x000D_
@-o-keyframes removed-item-animation {_x000D_
0% {_x000D_
opacity: 1;_x000D_
-o-transform: translateX(0);_x000D_
transform: translateX(0)_x000D_
}_x000D_
_x000D_
30% {_x000D_
opacity: 1;_x000D_
-o-transform: translateX(50px);_x000D_
transform: translateX(50px)_x000D_
}_x000D_
_x000D_
80% {_x000D_
opacity: 1;_x000D_
-o-transform: translateX(-800px);_x000D_
transform: translateX(-800px)_x000D_
}_x000D_
_x000D_
100% {_x000D_
opacity: 0;_x000D_
-o-transform: translateX(-800px);_x000D_
transform: translateX(-800px)_x000D_
}_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width">_x000D_
<title>JS Bin</title>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<table class="table table-striped table-bordered table-hover">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>id</th>_x000D_
<th>firstname</th>_x000D_
<th>lastname</th>_x000D_
<th>@twitter</th>_x000D_
<th>action</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
_x000D_
<tr class="item">_x000D_
<td>1</td>_x000D_
<td>Nour-Eddine</td>_x000D_
<td>ECH-CHEBABY</td>_x000D_
<th>@__chebaby</th>_x000D_
<td><button class="btn btn-danger deleteItem">Delete</button></td>_x000D_
</tr>_x000D_
_x000D_
<tr class="item">_x000D_
<td>2</td>_x000D_
<td>John</td>_x000D_
<td>Doe</td>_x000D_
<th>@johndoe</th>_x000D_
<td><button class="btn btn-danger deleteItem">Delete</button></td>_x000D_
</tr>_x000D_
_x000D_
<tr class="item">_x000D_
<td>3</td>_x000D_
<td>Jane</td>_x000D_
<td>Doe</td>_x000D_
<th>@janedoe</th>_x000D_
<td><button class="btn btn-danger deleteItem">Delete</button></td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
_x000D_
<script src="https://code.jquery.com/jquery.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
string saveStaff = "INSERT into student (stud_id,stud_name) " + " VALUES ('" + SI+ "', '" + SN + "');";
cmd = new SqlCommand(saveStaff,con);
cmd.ExecuteNonQuery();
This seems to be a good solution also, taken from a great blog post
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtWebKit import *
from lxml import html
#Take this class for granted.Just use result of rendering.
class Render(QWebPage):
def __init__(self, url):
self.app = QApplication(sys.argv)
QWebPage.__init__(self)
self.loadFinished.connect(self._loadFinished)
self.mainFrame().load(QUrl(url))
self.app.exec_()
def _loadFinished(self, result):
self.frame = self.mainFrame()
self.app.quit()
url = 'http://pycoders.com/archive/'
r = Render(url)
result = r.frame.toHtml()
# This step is important.Converting QString to Ascii for lxml to process
# The following returns an lxml element tree
archive_links = html.fromstring(str(result.toAscii()))
print archive_links
# The following returns an array containing the URLs
raw_links = archive_links.xpath('//div[@class="campaign"]/a/@href')
print raw_links
Using JODA:
PeriodFormatter periodFormat = new PeriodFormatterBuilder()
.minimumParsedDigits(2)
.appendHour() // 2 digits minimum
.appendSeparator(":")
.minimumParsedDigits(2)
.appendMinute() // 2 digits minimum
.appendSeparator(":")
.minimumParsedDigits(2)
.appendSecond()
.appendSeparator(".")
.appendMillis3Digit()
.toFormatter();
Period result = Period.parse(string, periodFormat);
return result.toStandardDuration().getMillis();
Save the execution file on your desktop Make sure you note the name of your file Go to start and type cmd right click on it
select run as administrator press enter
then you something below
C:\Users\your computer name\Desktop>
If you are seeing
C:\Windows\system32>
make sure you change it using CD
type the name of your file
C:\Users\your computer name\Desktop>the name of the file your copy.exe/ACTION=install /SKIPRULES=PerfMonCounterNotCorruptedCheck
If you are not limited to just a camera which wasn't in one of your constraints perhaps you can move to using a range sensor like the Xbox Kinect. With this you can perform depth and colour based matched segmentation of the image. This allows for faster separation of objects in the image. You can then use ICP matching or similar techniques to even match the shape of the can rather then just its outline or colour and given that it is cylindrical this may be a valid option for any orientation if you have a previous 3D scan of the target. These techniques are often quite quick especially when used for such a specific purpose which should solve your speed problem.
Also I could suggest, not necessarily for accuracy or speed but for fun you could use a trained neural network on your hue segmented image to identify the shape of the can. These are very fast and can often be up to 80/90% accurate. Training would be a little bit of a long process though as you would have to manually identify the can in each image.
Looping through the array and inserting a key, value pair is about your best solution. You could use the 'map' function but it is just a matter of preference.
var arrOfObj = [{name: 'eve'},{name:'john'},{name:'jane'}];
arrOfObj.map(function (obj) {
obj.isActive = true;
});
You can use StringBuffer
or StringBuilder
for this. Both are for dynamic string manipulation. StringBuffer
is thread-safe where as StringBuilder
is not.
Use StringBuffer
in a multi-thread environment. But if it is single threaded StringBuilder
is recommended and it is much faster than StringBuffer
.
The CSV format sounds easy enough for StringTokenizer but it can become more complicated. Here in Germany a semicolon is used as a delimiter and cells containing delimiters need to be escaped. You're not going to handle that easily with StringTokenizer.
I would go for http://sourceforge.net/projects/javacsv
<div ng-if="modeldate==''"><span ng-message="required" class="change">Date is required</span> </div>
you can use the ng-if directive as above.
In the bean you can use session.getAttribute("attributeName");
<textarea onClick="javascript: this.value='';">Please describe why</textarea>
Use f-string
:
print(f'Total score for {name} is {score}')
Or
Use .format
:
print("Total score for {} is {}".format(name, score))
If you want to get advantage of your local machine timezone you can use myDateTime.ToUniversalTime()
to get the UTC time from your local time or myDateTime.ToLocalTime()
to convert the UTC time to the local machine's time.
// convert UTC time from the database to the machine's time
DateTime databaseUtcTime = new DateTime(2011,6,5,10,15,00);
var localTime = databaseUtcTime.ToLocalTime();
// convert local time to UTC for database save
var databaseUtcTime = localTime.ToUniversalTime();
If you need to convert time from/to other timezones, you may use TimeZoneInfo.ConvertTime()
or TimeZoneInfo.ConvertTimeFromUtc()
.
// convert UTC time from the database to japanese time
DateTime databaseUtcTime = new DateTime(2011,6,5,10,15,00);
var japaneseTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");
var japaneseTime = TimeZoneInfo.ConvertTimeFromUtc(databaseUtcTime, japaneseTimeZone);
// convert japanese time to UTC for database save
var databaseUtcTime = TimeZoneInfo.ConvertTimeToUtc(japaneseTime, japaneseTimeZone);
<script>
function validate() {
var phone=document.getElementById("phone").value;
if(isNaN(phone))
{
alert("please enter digits only");
}
else if(phone.length!=10)
{
alert("invalid mobile number");
}
else
{
confirm("hello your mobile number is" +" "+phone);
}
</script>
What's dumpsys and what are its benefit
dumpsys is an android tool that runs on the device and dumps interesting information about the status of system services.
Obvious benefits:
What information can we retrieve from dumpsys shell command and how we can use it
If you run dumpsys you would see a ton of system information. But you can use only separate parts of this big dump.
to see all of the "subcommands" of dumpsys do:
dumpsys | grep "DUMP OF SERVICE"
Output:
DUMP OF SERVICE SurfaceFlinger:
DUMP OF SERVICE accessibility:
DUMP OF SERVICE account:
DUMP OF SERVICE activity:
DUMP OF SERVICE alarm:
DUMP OF SERVICE appwidget:
DUMP OF SERVICE audio:
DUMP OF SERVICE backup:
DUMP OF SERVICE battery:
DUMP OF SERVICE batteryinfo:
DUMP OF SERVICE clipboard:
DUMP OF SERVICE connectivity:
DUMP OF SERVICE content:
DUMP OF SERVICE cpuinfo:
DUMP OF SERVICE device_policy:
DUMP OF SERVICE devicestoragemonitor:
DUMP OF SERVICE diskstats:
DUMP OF SERVICE dropbox:
DUMP OF SERVICE entropy:
DUMP OF SERVICE hardware:
DUMP OF SERVICE input_method:
DUMP OF SERVICE iphonesubinfo:
DUMP OF SERVICE isms:
DUMP OF SERVICE location:
DUMP OF SERVICE media.audio_flinger:
DUMP OF SERVICE media.audio_policy:
DUMP OF SERVICE media.player:
DUMP OF SERVICE meminfo:
DUMP OF SERVICE mount:
DUMP OF SERVICE netstat:
DUMP OF SERVICE network_management:
DUMP OF SERVICE notification:
DUMP OF SERVICE package:
DUMP OF SERVICE permission:
DUMP OF SERVICE phone:
DUMP OF SERVICE power:
DUMP OF SERVICE reboot:
DUMP OF SERVICE screenshot:
DUMP OF SERVICE search:
DUMP OF SERVICE sensor:
DUMP OF SERVICE simphonebook:
DUMP OF SERVICE statusbar:
DUMP OF SERVICE telephony.registry:
DUMP OF SERVICE throttle:
DUMP OF SERVICE usagestats:
DUMP OF SERVICE vibrator:
DUMP OF SERVICE wallpaper:
DUMP OF SERVICE wifi:
DUMP OF SERVICE window:
Some Dumping examples and output
1) Getting all possible battery statistic:
$~ adb shell dumpsys battery
You will get output:
Current Battery Service state:
AC powered: false
AC capacity: 500000
USB powered: true
status: 5
health: 2
present: true
level: 100
scale: 100
voltage:4201
temperature: 271 <---------- Battery temperature! %)
technology: Li-poly <---------- Battery technology! %)
2)Getting wifi informations
~$ adb shell dumpsys wifi
Output:
Wi-Fi is enabled
Stay-awake conditions: 3
Internal state:
interface tiwlan0 runState=Running
SSID: XXXXXXX BSSID: xx:xx:xx:xx:xx:xx, MAC: xx:xx:xx:xx:xx:xx, Supplicant state: COMPLETED, RSSI: -60, Link speed: 54, Net ID: 2, security: 0, idStr: null
ipaddr 192.168.1.xxx gateway 192.168.x.x netmask 255.255.255.0 dns1 192.168.x.x dns2 8.8.8.8 DHCP server 192.168.x.x lease 604800 seconds
haveIpAddress=true, obtainingIpAddress=false, scanModeActive=false
lastSignalLevel=2, explicitlyDisabled=false
Latest scan results:
Locks acquired: 28 full, 0 scan
Locks released: 28 full, 0 scan
Locks held:
3) Getting CPU info
~$ adb shell dumpsys cpuinfo
Output:
Load: 0.08 / 0.4 / 0.64
CPU usage from 42816ms to 34683ms ago:
system_server: 1% = 1% user + 0% kernel / faults: 16 minor
kdebuglog.sh: 0% = 0% user + 0% kernel / faults: 160 minor
tiwlan_wq: 0% = 0% user + 0% kernel
usb_mass_storag: 0% = 0% user + 0% kernel
pvr_workqueue: 0% = 0% user + 0% kernel
+sleep: 0% = 0% user + 0% kernel
+sleep: 0% = 0% user + 0% kernel
TOTAL: 6% = 1% user + 3% kernel + 0% irq
4)Getting memory usage informations
~$ adb shell dumpsys meminfo 'your apps package name'
Output:
** MEMINFO in pid 5527 [com.sec.android.widgetapp.weatherclock] **
native dalvik other total
size: 2868 5767 N/A 8635
allocated: 2861 2891 N/A 5752
free: 6 2876 N/A 2882
(Pss): 532 80 2479 3091
(shared dirty): 932 2004 6060 8996
(priv dirty): 512 36 1872 2420
Objects
Views: 0 ViewRoots: 0
AppContexts: 0 Activities: 0
Assets: 3 AssetManagers: 3
Local Binders: 2 Proxy Binders: 8
Death Recipients: 0
OpenSSL Sockets: 0
SQL
heap: 0 MEMORY_USED: 0
PAGECACHE_OVERFLOW: 0 MALLOC_SIZE: 0
If you want see the info for all processes, use ~$ adb shell dumpsys meminfo
dumpsys is ultimately flexible and useful tool!
If you want to use this tool do not forget to add permission into your android manifest automatically android.permission.DUMP
Try to test all commands to learn more about dumpsys. Happy dumping!
sdleihssirhc's answer is of course the correct one for the case in the question, but just as a reference if you need to select elements that don't have a certain class, you can use the not selector:
// select all divs that don't have class test
$( 'div' ).not( ".test" );
$( 'div:not(.test)' ); // <-- alternative
I had the same problem my OS is windows 8 and I am using Tomcat 8, I just edited the setclasspath.bat file in bin folder and set JAVA_HOME and JRE_HOME like this...
@echo off
...
...
set "JRE_HOME=%ProgramFiles%\Java\jre8"
set "JAVA_HOME=%ProgramFiles%\Java\jdk1.7.0_03"
...
...
and it works fine for me now......
If the object was recently created, you can check the Schema Changes History report, within the SQL Server Management Studio, which "provides a history of all committed DDL statement executions within the Database recorded by the default trace":
You then can search for the create statements of the objects. Among all the information displayed, there is the login name of whom executed the DDL statement.
I would like to share a detailed way of how to post with PHP + Ajax along with errors thrown back on failure.
First of all, create two files, for example form.php
and process.php
.
We will first create a form
which will be then submitted using the jQuery
.ajax()
method. The rest will be explained in the comments.
form.php
<form method="post" name="postForm">
<ul>
<li>
<label>Name</label>
<input type="text" name="name" id="name" placeholder="Bruce Wayne">
<span class="throw_error"></span>
<span id="success"></span>
</li>
</ul>
<input type="submit" value="Send" />
</form>
Validate the form using jQuery client-side validation and pass the data to process.php
.
$(document).ready(function() {
$('form').submit(function(event) { //Trigger on form submit
$('#name + .throw_error').empty(); //Clear the messages first
$('#success').empty();
//Validate fields if required using jQuery
var postForm = { //Fetch form data
'name' : $('input[name=name]').val() //Store name fields value
};
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'process.php', //Your form processing file URL
data : postForm, //Forms name
dataType : 'json',
success : function(data) {
if (!data.success) { //If fails
if (data.errors.name) { //Returned if any error from process.php
$('.throw_error').fadeIn(1000).html(data.errors.name); //Throw relevant error
}
}
else {
$('#success').fadeIn(1000).append('<p>' + data.posted + '</p>'); //If successful, than throw a success message
}
}
});
event.preventDefault(); //Prevent the default submit
});
});
Now we will take a look at process.php
$errors = array(); //To store errors
$form_data = array(); //Pass back the data to `form.php`
/* Validate the form on the server side */
if (empty($_POST['name'])) { //Name cannot be empty
$errors['name'] = 'Name cannot be blank';
}
if (!empty($errors)) { //If errors in validation
$form_data['success'] = false;
$form_data['errors'] = $errors;
}
else { //If not, process the form, and return true on success
$form_data['success'] = true;
$form_data['posted'] = 'Data Was Posted Successfully';
}
//Return the data back to form.php
echo json_encode($form_data);
The project files can be downloaded from http://projects.decodingweb.com/simple_ajax_form.zip.
Handling the input
event is a consistent solution: it is supported for textarea
and input
elements in all contemporary browsers and it fires exactly when you need it:
function edValueKeyPress() {
var edValue = document.getElementById("edValue");
var s = edValue.value;
var lblValue = document.getElementById("lblValue");
lblValue.innerText = "The text box contains: " + s;
}
_x000D_
<input id="edValue" type="text" onInput="edValueKeyPress()"><br>
<span id="lblValue">The text box contains: </span>
_x000D_
I'd rewrite this a bit, though:
function showCurrentValue(event)
{
const value = event.target.value;
document.getElementById("label").innerText = value;
}
_x000D_
<input type="text" onInput="showCurrentValue(event)"><br>
The text box contains: <span id="label"></span>
_x000D_
The differences are covered at the PostgreSQL documentation for date/time types. Yes, the treatment of TIME
or TIMESTAMP
differs between one WITH TIME ZONE
or WITHOUT TIME ZONE
. It doesn't affect how the values are stored; it affects how they are interpreted.
The effects of time zones on these data types is covered specifically in the docs. The difference arises from what the system can reasonably know about the value:
With a time zone as part of the value, the value can be rendered as a local time in the client.
Without a time zone as part of the value, the obvious default time zone is UTC, so it is rendered for that time zone.
The behaviour differs depending on at least three factors:
WITH TIME ZONE
or WITHOUT TIME ZONE
) of the value.Here are examples covering the combinations of those factors:
foo=> SET TIMEZONE TO 'Japan';
SET
foo=> SELECT '2011-01-01 00:00:00'::TIMESTAMP;
timestamp
---------------------
2011-01-01 00:00:00
(1 row)
foo=> SELECT '2011-01-01 00:00:00'::TIMESTAMP WITH TIME ZONE;
timestamptz
------------------------
2011-01-01 00:00:00+09
(1 row)
foo=> SELECT '2011-01-01 00:00:00+03'::TIMESTAMP;
timestamp
---------------------
2011-01-01 00:00:00
(1 row)
foo=> SELECT '2011-01-01 00:00:00+03'::TIMESTAMP WITH TIME ZONE;
timestamptz
------------------------
2011-01-01 06:00:00+09
(1 row)
foo=> SET TIMEZONE TO 'Australia/Melbourne';
SET
foo=> SELECT '2011-01-01 00:00:00'::TIMESTAMP;
timestamp
---------------------
2011-01-01 00:00:00
(1 row)
foo=> SELECT '2011-01-01 00:00:00'::TIMESTAMP WITH TIME ZONE;
timestamptz
------------------------
2011-01-01 00:00:00+11
(1 row)
foo=> SELECT '2011-01-01 00:00:00+03'::TIMESTAMP;
timestamp
---------------------
2011-01-01 00:00:00
(1 row)
foo=> SELECT '2011-01-01 00:00:00+03'::TIMESTAMP WITH TIME ZONE;
timestamptz
------------------------
2011-01-01 08:00:00+11
(1 row)
This table might be helpful for you:
Going down the first column, you will see how the log works in each level. i.e for WARN, (FATAL, ERROR and WARN) will be visible. For OFF, nothing will be visible.
The accepted answer using button.tag
as information carrier which button has actually been pressed is solid and widely accepted but rather limited since a tag can only hold Int
s.
You can make use of Swift's awesome closure-capabilities to have greater flexibility and cleaner code.
I recommend this article: How to properly do buttons in table view cells using Swift closures by Jure Zove.
Applied to your problem:
Declare a variable that can hold a closure in your tableview cell like
var buttonTappedAction : ((UITableViewCell) -> Void)?
Add an action when the button is pressed that only executes the closure. You did it programmatically with cell.yes.targetForAction("connected", withSender: self)
but I would prefer an @IBAction
outlet :-)
@IBAction func buttonTap(sender: AnyObject) {
tapAction?(self)
}
func connected(sender: UIButton!) { ... }
as a closure to cell.tapAction = {<closure content here...>}
. Please refer to the article for a more precise explanation and please don't forget to break reference cycles when capturing variables from the environment.Use either:
balancePanel.Left = optionsPanel.Location.X;
or
balancePanel.Location = new Point(optionsPanel.Location.X, balancePanel.Location.Y);
See the documentation of Location:
Because the Point class is a value type (Structure in Visual Basic, struct in Visual C#), it is returned by value, meaning accessing the property returns a copy of the upper-left point of the control. So, adjusting the X or Y properties of the Point returned from this property will not affect the Left, Right, Top, or Bottom property values of the control. To adjust these properties set each property value individually, or set the Location property with a new Point.
I also had problem understanding next() , but this helped
var app = require("express")();
app.get("/", function(httpRequest, httpResponse, next){
httpResponse.write("Hello");
next(); //remove this and see what happens
});
app.get("/", function(httpRequest, httpResponse, next){
httpResponse.write(" World !!!");
httpResponse.end();
});
app.listen(8080);
$(".overdue").each( function() {
alert("Your book is overdue.");
});
Note that ".addClass()" works because addClass is a function defined on the jQuery object. You can't just plop any old function on the end of a selector and expect it to work.
Also, probably a bad idea to bombard the user with n popups (where n = the number of books overdue).
Perhaps use the size function:
alert( "You have " + $(".overdue").size() + " books overdue." );
I Also Faced This Problem. To Solve This I have first converted my long to String then to int.
int i = Integer.parseInt(String.valueOf(long));
The explorer suite can do what you want.
2.51 * 100 = 250.999999999997
The int()
function simply truncates the number at the decimal point, giving 250. Use
int(round(2.51*100))
to get 251 as an integer. In general, floating point numbers cannot be represented exactly. One should therefore be careful of round-off errors. As mentioned, this is not a Python-specific problem. It's a recurring problem in all computer languages.
I just managed to wedge myself pretty thoroughly trying to follow user619330's advice above. The situation was: (1): I had added some files while working on my initial branch, branch1; (2) I created a new branch, branch2 for further development, branching it off from the trunk and then merging in my changes from branch1 (3) A co-worker had copied my mods from branch1 to his own branch, added further mods, and then merged back to the trunk; (4) I now wanted to merge the latest changes from trunk into my current working branch, branch2. This is with svn 1.6.17.
The merge had tree conflicts with the new files, and I wanted the new version from the trunk where they differed, so from a clean copy of branch2, I did an svn delete of the conflicting files, committed these branch2 changes (thus creating a temporary version of branch2 without the files in question), and then did my merge from the trunk. I did this because I wanted the history to match the trunk version so that I wouldn't have more problems later when trying to merge back to trunk. Merge went fine, I got the trunk version of the files, svn st shows all ok, and then I hit more tree conflicts while trying to commit the changes, between the delete I had done earlier and the add from the merge. Did an svn resolve of the conflicts in favor of my working copy (which now had the trunk version of the files), and got it to commit. All should be good, right?
Well, no. An update of another copy of branch2 resulted in the old version of the files (pre-trunk merge). So now I have two different working copies of branch2, supposedly updated to the same version, with two different versions of the files, and both insisting that they are fully up to date! Checking out a clean copy of branch2 resulted in the old (pre-trunk) version of the files. I manually update these to the trunk version and commit the changes, go back to my first working copy (from which I had submitted the trunk changes originally), try to update it, and now get a checksum error on the files in question. Blow the directory in question away, get a new version via update, and finally I have what should be a good version of branch2 with the trunk changes. I hope. Caveat developer.
You can see the error information from:
Magento/var/report
Most of the time it is cause by broken database connection especially at local server, when one forget to start XAMPP or WAMPP server.
I had this issue happening often. I found SQL Server Agent
service was not running. Once I started the service manually, it got fixed. Double check if the service is running or not:
services.msc
and hit enterSQL Server Agent
(Instance Name)If SQL Server Agent
is not running, double-click the service to open properties window. Then click on Start
button. Hope it will help someone.
? singleton method is a method that is defined only for a single object.
Example:
class SomeClass
class << self
def test
end
end
end
test_obj = SomeClass.new
def test_obj.test_2
end
class << test_obj
def test_3
end
end
puts "Singleton's methods of SomeClass"
puts SomeClass.singleton_methods
puts '------------------------------------------'
puts "Singleton's methods of test_obj"
puts test_obj.singleton_methods
Singleton's methods of SomeClass
test
Singleton's methods of test_obj
test_2
test_3
just offering this up as a possible solution if you don't think the user will have a negative experience on the obvious change. I simply changed the body's class of overflow to hidden when the mouse was over the target div; then I changed the body's div to hidden overflow when the mouse leaves.
Personally I don't think it looks bad, my code could use toggle to make it cleaner, and there are obvious benefits for making this effect possible without the user being aware. So this is probably the hackish-last-resort answer.
//listen mouse on and mouse off for the button
pxMenu.addEventListener("mouseover", toggleA1);
pxOptContainer.addEventListener("mouseout", toggleA2);
//show / hide the pixel option menu
function toggleA1(){
pxOptContainer.style.display = "flex";
body.style.overflow = "hidden";
}
function toggleA2(){
pxOptContainer.style.display = "none";
body.style.overflow = "hidden scroll";
}
According to caniuse.com:
You can use a client-only polyfill to extend support of SSE to many other browsers. This is less likely with WebSockets. Some EventSource polyfills:
If you need to support all the browsers, consider using a library like web-socket-js, SignalR or socket.io which support multiple transports such as WebSockets, SSE, Forever Frame and AJAX long polling. These often require modifications to the server side as well.
Learn more about SSE from:
Learn more about WebSockets from:
Other differences:
I think it's best to break the answer in depth and in simple words:
__name__
: Every module in Python has a special attribute called __name__
.
It is a built-in variable that returns the name of the module.
__main__
: Like other programming languages, Python too has an execution entry point, i.e., main. '__main__'
is the name of the scope in which top-level code executes. Basically you have two ways of using a Python module: Run it directly as a script, or import it. When a module is run as a script, its __name__
is set to __main__
.
Thus, the value of the __name__
attribute is set to __main__
when the module is run as the main program. Otherwise the value of __name__
is set to contain the name of the module.
You can use this tool to create appropriate c# classes:
http://jsonclassgenerator.codeplex.com/
and when you will have classes created you can simply convert string to object:
public static T ParseJsonObject<T>(string json) where T : class, new()
{
JObject jobject = JObject.Parse(json);
return JsonConvert.DeserializeObject<T>(jobject.ToString());
}
Here that classes: http://ge.tt/2KGtbPT/v/0?c
Just fix namespaces.
JAX-RS implementations automatically support marshalling/unmarshalling of classes based on discoverable JAXB annotations, but because your payload is declared as Object
, I think the created JAXBContext
misses the Department
class and when it's time to marshall it it doesn't know how.
A quick and dirty fix would be to add a XmlSeeAlso
annotation to your response class:
@XmlRootElement
@XmlSeeAlso({Department.class})
public class Response implements Serializable {
....
or something a little more complicated would be "to enrich" the JAXB context for the Response
class by using a ContextResolver
:
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
@Provider
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public class ResponseResolver implements ContextResolver<JAXBContext> {
private JAXBContext ctx;
public ResponseResolver() {
try {
this.ctx = JAXBContext.newInstance(
Response.class,
Department.class
);
} catch (JAXBException ex) {
throw new RuntimeException(ex);
}
}
public JAXBContext getContext(Class<?> type) {
return (type.equals(Response.class) ? ctx : null);
}
}
In Unix systems the end of a line is represented with a line feed (LF). In windows a line is represented with a carriage return (CR) and a line feed (LF) thus (CRLF). when you get code from git that was uploaded from a unix system they will only have an LF.
If you are a single developer working on a windows machine, and you don't care that git automatically replaces LFs to CRLFs, you can turn this warning off by typing the following in the git command line
git config core.autocrlf true
If you want to make an intelligent decision how git should handle this, read the documentation
Here is a snippet
Formatting and Whitespace
Formatting and whitespace issues are some of the more frustrating and subtle problems that many developers encounter when collaborating, especially cross-platform. It’s very easy for patches or other collaborated work to introduce subtle whitespace changes because editors silently introduce them, and if your files ever touch a Windows system, their line endings might be replaced. Git has a few configuration options to help with these issues.
core.autocrlf
If you’re programming on Windows and working with people who are not (or vice-versa), you’ll probably run into line-ending issues at some point. This is because Windows uses both a carriage-return character and a linefeed character for newlines in its files, whereas Mac and Linux systems use only the linefeed character. This is a subtle but incredibly annoying fact of cross-platform work; many editors on Windows silently replace existing LF-style line endings with CRLF, or insert both line-ending characters when the user hits the enter key.
Git can handle this by auto-converting CRLF line endings into LF when you add a file to the index, and vice versa when it checks out code onto your filesystem. You can turn on this functionality with the core.autocrlf setting. If you’re on a Windows machine, set it to true – this converts LF endings into CRLF when you check out code:
$ git config --global core.autocrlf true
If you’re on a Linux or Mac system that uses LF line endings, then you don’t want Git to automatically convert them when you check out files; however, if a file with CRLF endings accidentally gets introduced, then you may want Git to fix it. You can tell Git to convert CRLF to LF on commit but not the other way around by setting core.autocrlf to input:
$ git config --global core.autocrlf input
This setup should leave you with CRLF endings in Windows checkouts, but LF endings on Mac and Linux systems and in the repository.
If you’re a Windows programmer doing a Windows-only project, then you can turn off this functionality, recording the carriage returns in the repository by setting the config value to false:
$ git config --global core.autocrlf false
It's part of C99 and defined in POSIX definition stdbool.h.
I had this problem and the suggestions above didn't help. What I found is that the add-migration reads the current state and creates a signature of the current model. You must modify your model before modifying. So the sequence is.
I did the opposite and added the migration before modifying my model (which was empty, so I added the new columns) and then ran my code.
Hope this helps.
In your Startup.Auth.cs file add this line:
LoginPath = new PathString("/Account/Login"),
Example:
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
If the two databases are on the same server, you should be able to create a SQL statement something like this:
UPDATE Test1.dbo.Employee
SET DeptID = emp2.DeptID
FROM Test2.dbo.Employee as 'emp2'
WHERE
Test1.dbo.Employee.EmployeeID = emp2.EmployeeID
From your post, I'm not quite clear whether you want to update Test1.dbo.Employee
with the values from Test2.dbo.Employee
(that's what my query does), or the other way around (since you mention the db on Test1
was the new table......)
my 5c: In integration and networking the idempotency is very important. Several examples from real-life: Imagine, we deliver data to the target system. Data delivered by a sequence of messages. 1. What would happen if the sequence is mixed in channel? (As network packages always do :) ). If the target system is idempotent, the result will not be different. If the target system depends of the right order in the sequence, we have to implement resequencer on the target site, which would restore the right order. 2. What would happen if there are the message duplicates? If the channel of target system does not acknowledge timely, the source system (or channel itself) usually sends another copy of the message. As a result we can have duplicate message on the target system side. If the target system is idempotent, it takes care of it and result will not be different. If the target system is not idempotent, we have to implement deduplicator on the target system side of the channel.
This approach seems more straightforward, avoiding the need to individually select each file:
# keep remote files
git merge --strategy-option theirs
# keep local files
git merge --strategy-option ours
or
# keep remote files
git pull -Xtheirs
# keep local files
git pull -Xours
Copied directly from: Resolve Git merge conflicts in favor of their changes during a pull
In case of Include Program will not terminate and display warning on browser,On the other hand Require program will terminate and display fatal error in case of file not found.
The issue here is that JSON, as a format, is generally parsed in full and then handled in-memory, which for such a large amount of data is clearly problematic.
The solution to this is to work with the data as a stream - reading part of the file, working with it, and then repeating.
The best option appears to be using something like ijson - a module that will work with JSON as a stream, rather than as a block file.
Edit: Also worth a look - kashif's comment about json-streamer
and Henrik Heino's comment about bigjson
.
Two options, that have different uses:
HTML:
<a class="example" href="http://www.example.com">example</a>
CSS:
.example { text-align: center; }
Or:
.example { display:block; width:100px; margin:0 auto;}
I ran into a similar issue and found I was hitting the wrong port. After fixing the port things worked great.
According to this link: signature help
APK Signature Scheme v2 offers:
Android 7.0 introduces APK Signature Scheme v2, a new app-signing scheme that offers faster app install times and more protection against unauthorized alterations to APK files. By default, Android Studio 2.2 and the Android Plugin for Gradle 2.2 sign your app using both APK Signature Scheme v2 and the traditional signing scheme, which uses JAR signing.
It is recommended to use APK Signature Scheme v2 but is not mandatory.
Although we recommend applying APK Signature Scheme v2 to your app, this new scheme is not mandatory. If your app doesn't build properly when using APK Signature Scheme v2, you can disable the new scheme.
It's very easy if you use Kotlin:
val textFile = File(cacheDir, "/text_file.txt")
val allText = textFile.readText()
println(allText)
From readText()
docs:
Gets the entire content of this file as a String using UTF-8 or specified charset. This method is not recommended on huge files. It has an internal limitation of 2 GB file size.
I had the same issue but fixed just after running these commands:
flutter channel dev
flutter doctor
flutter channel master
flutter doctor
when iserting into t-sql
this fails:
select CONVERT(datetime,'2019-09-13 09:04:35.823312',21)
this works:
select CONVERT(datetime,'2019-09-13 09:04:35.823',21)
easy way:
regexp = re.compile(r'\.(\d{6})')
def to_splunk_iso(dt):
"""Converts the datetime object to Splunk isoformat string."""
# 6-digits string.
microseconds = regexp.search(dt).group(1)
return regexp.sub('.%d' % round(float(microseconds) / 1000), dt)
If You try to insert other than the number in the Table column you get Constraint[numbering] error.
Try to insert the only number (or) make your Table column to char Type
Regular Expressions
Context Free Grammars
Neither of the first two answers worked for me with multiple elements that can open dialogs that point to different pages.
This feels like the cleanest solution, only creates the dialog object once on load and then uses the events to open/close/display appropriately:
$(function () {
var ajaxDialog = $('<div id="ajax-dialog" style="display:hidden"></div>').appendTo('body');
ajaxDialog.dialog({autoOpen: false});
$('a.ajax-dialog-opener').live('click', function() {
// load remote content
ajaxDialog.load(this.href);
ajaxDialog.dialog("open");
//prevent the browser from following the link
return false;
});
});
In my case the "bind-address" setting was the problem. Commenting this setting in my.cnf
did not help, because in my case mysql set the default to 127.0.0.1 for some reason.
To verify what setting MySql is currently using, open the command line on your local box:
mysql -h localhost -u myname -pmypass mydb
Read out the current setting:
Show variables where variable_name like "bind%"
You should see 0.0.0.0 here if you want to allow access from all hosts. If this is not the case, edit your /etc/mysql/my.cnf
and set bind-address under the [mysqld] section:
bind-address=0.0.0.0
Finally restart your MySql server to pick up the new setting:
sudo service mysql restart
Try again and check if the new setting has been picked up.
Not Swift but I'm sure you get the idea.
pow10np = pow(10,num_places);
val = round(val*pow10np) / pow10np;
NOTE: Though this is possible, it is not at all recommended as it kind of destroys the reason for inheritance. The best way would be to restructure your application design so that there are NO parent to child dependencies. A parent should not ever need to know its children or their capabilities.
However.. you should be able to do it like:
void calculate(Person p) {
((Student)p).method();
}
a safe way would be:
void calculate(Person p) {
if(p instanceof Student) ((Student)p).method();
}
There can be any number of different screen sizes due to Android having no set standard size so as a guide you can use the minimum screen sizes, which are provided by Google.
According to Google's statistics the majority of ldpi displays are small screens and the majority of mdpi, hdpi, xhdpi and xxhdpi displays are normal sized screens.
You can view the statistics on the relative sizes of devices on Google's dashboard which is available here.
More information on multiple screens can be found here.
The best solution is to create a nine-patch image so that the image's border can stretch to fit the size of the screen without affecting the static area of the image.
http://developer.android.com/guide/topics/graphics/2d-graphics.html#nine-patch
This works for me:
Create a new shell file job. So let's say:
touch job.sh
and add command to run python script (you can even add command line arguments to that python, I usually predefine my command line arguments).
chmod +x job.sh
Inside job.sh
add the following py files, let's say:
python_file.py argument1 argument2 argument3 >> testpy-output.txt && echo "Done with python_file.py"
python_file1.py argument1 argument2 argument3 >> testpy-output.txt && echo "Done with python_file1.py"
Done with python_file.py
Done with python_file1.py
I use this usually when I have to run multiple python files with different arguments, pre defined.
Note: Just a quick heads up on what's going on here:
python_file.py argument1 argument2 argument3 >> testpy-output.txt && echo "completed with python_file.py" .
python python_file.py
, plain and simple.
Next up, the >> will print and store the output of this .py file in the testpy-output.txt file. I have same issue when I was trying out Laravel 5.2 at first, then I learnt about {{!! csrf_field() !!}}
to be added in the form and that solved it. But later I learnt about Form Helpers, this takes care of CSRF protection and does not give any errors. Though Form Helpers are not legitimately available after Laravel 5.2, you can still use them from LaravelCollective.
Recommended Approach
This answer enumerates different mechanisms for passing parameters to FXML controllers.
For small applications I highly recommend passing parameters directly from the caller to the controller - it's simple, straightforward and requires no extra frameworks.
For larger, more complicated applications, it would be worthwhile investigating if you want to use Dependency Injection or Event Bus mechanisms within your application.
Passing Parameters Directly From the Caller to the Controller
Pass custom data to an FXML controller by retrieving the controller from the FXML loader instance and calling a method on the controller to initialize it with the required data values.
Something like the following code:
public Stage showCustomerDialog(Customer customer) {
FXMLLoader loader = new FXMLLoader(
getClass().getResource(
"customerDialog.fxml"
)
);
Stage stage = new Stage(StageStyle.DECORATED);
stage.setScene(
new Scene(loader.load())
);
CustomerDialogController controller = loader.getController();
controller.initData(customer);
stage.show();
return stage;
}
...
class CustomerDialogController {
@FXML private Label customerName;
void initialize() {}
void initData(Customer customer) {
customerName.setText(customer.getName());
}
}
A new FXMLLoader is constructed as shown in the sample code i.e. new FXMLLoader(location)
. The location is a URL and you can generate such a URL from an FXML resource by:
new FXMLLoader(getClass().getResource("sample.fxml"));
Be careful NOT to use a static load function on the FXMLLoader, or you will not be able to get your controller from your loader instance.
FXMLLoader instances themselves never know anything about domain objects. You do not directly pass application specific domain objects into the FXMLLoader constructor, instead you:
This blog (by another writer) provides an alternate, but similar, example.
Setting a Controller on the FXMLLoader
CustomerDialogController dialogController =
new CustomerDialogController(param1, param2);
FXMLLoader loader = new FXMLLoader(
getClass().getResource(
"customerDialog.fxml"
)
);
loader.setController(dialogController);
Pane mainPane = loader.load();
You can construct a new controller in code, passing any parameters you want from your caller into the controller constructor. Once you have constructed a controller, you can set it on an FXMLLoader instance before you invoke the load()
instance method.
To set a controller on a loader (in JavaFX 2.x) you CANNOT also define a fx:controller
attribute in your fxml file.
Due to the limitation on the fx:controller
definition in FXML, I personally prefer getting the controller from the FXMLLoader rather than setting the controller into the FXMLLoader.
Having the Controller Retrieve Parameters from an External Static Method
This method is exemplified by Sergey's answer to Javafx 2.0 How-to Application.getParameters() in a Controller.java file.
Use Dependency Injection
FXMLLoader supports dependency injection systems like Guice, Spring or Java EE CDI by allowing you to set a custom controller factory on the FXMLLoader. This provides a callback that you can use to create the controller instance with dependent values injected by the respective dependency injection system.
An example of JavaFX application and controller dependency injection with Spring is provided in the answer to:
A really nice, clean dependency injection approach is exemplified by the afterburner.fx framework with a sample air-hacks application that uses it. afterburner.fx relies on JEE6 javax.inject to perform the dependency injection.
Use an Event Bus
Greg Brown, the original FXML specification creator and implementor, often suggests considering use of an event bus, such as the Guava EventBus, for communication between FXML instantiated controllers and other application logic.
The EventBus is a simple but powerful publish/subscribe API with annotations that allows POJOs to communicate with each other anywhere in a JVM without having to refer to each other.
Follow-up Q&A
on first method, why do you return Stage? The method can be void as well because you already giving the command show(); just before return stage;. How do you plan usage by returning the Stage
It is a functional solution to a problem. A stage is returned from the showCustomerDialog
function so that a reference to it can be stored by an external class which may wish to do something, such as hide the stage based on a button click in the main window, at a later time. An alternate, object-oriented solution could encapsulate the functionality and stage reference inside a CustomerDialog object or have a CustomerDialog extend Stage. A full example for an object-oriented interface to a custom dialog encapsulating FXML, controller and model data is beyond the scope of this answer, but may make a worthwhile blog post for anybody inclined to create one.
Additional information supplied by StackOverflow user named @dzim
Example for Spring Boot Dependency Injection
The question of how to do it "The Spring Boot Way", there was a discussion about JavaFX 2, which I anserwered in the attached permalink. The approach is still valid and tested in March 2016, on Spring Boot v1.3.3.RELEASE: https://stackoverflow.com/a/36310391/1281217
Sometimes, you might want to pass results back to the caller, in which case you can check out the answer to the related question:
The accepted answer works for most cases, but it doesn't work well when your div
can vary greatly in height — the animation speed is not dependent on the actual height of the content, and it can look choppy.
You can still perform the actual animation with CSS, but you need to use JavaScript to compute the height of the items, instead of trying to use auto
. No jQuery is required, although you may have to modify this a bit if you want compatibility (works in the latest version of Chrome :)).
window.toggleExpand = function(element) {_x000D_
if (!element.style.height || element.style.height == '0px') { _x000D_
element.style.height = Array.prototype.reduce.call(element.childNodes, function(p, c) {return p + (c.offsetHeight || 0);}, 0) + 'px';_x000D_
} else {_x000D_
element.style.height = '0px';_x000D_
}_x000D_
}
_x000D_
#menu #list {_x000D_
height: 0px;_x000D_
transition: height 0.3s ease;_x000D_
background: #d5d5d5;_x000D_
overflow: hidden;_x000D_
}
_x000D_
<div id="menu">_x000D_
<input value="Toggle list" type="button" onclick="toggleExpand(document.getElementById('list'));">_x000D_
<ul id="list">_x000D_
<!-- Works well with dynamically-sized content. -->_x000D_
<li>item</li>_x000D_
<li><div style="height: 100px; width: 100px; background: red;"></div></li>_x000D_
<li>item</li>_x000D_
<li>item</li>_x000D_
<li>item</li>_x000D_
</ul>_x000D_
</div>
_x000D_
If my compiler is set to 32 bit, size_t
is nothing other than a typedef for unsigned int
. If my compiler is set to 64 bit, size_t
is nothing other than a typedef for unsigned long long
.
function setjdk() {
if [ $# -ne 0 ]; then
removeFromPath '/System/Library/Frameworks/JavaVM.framework/Home/bin'
if [ -n "${JAVA_HOME+x}" ]; then
removeFromPath $JAVA_HOME
fi
export JAVA_HOME=`/usr/libexec/java_home -v $@`
export PATH=$JAVA_HOME/bin:$PATH
fi
}
put this in your ~/.profile and use it in your terminal like so setjdk 1.8
, setjdk 1.7
, setjdk 9
etc etc...
If you don't have removeFromPath
then it is:
function removeFromPath() {
export PATH=$(echo $PATH | sed -E -e "s;:$1;;" -e "s;$1:?;;")
}
Your should really use the INFORMATION_SCHEMA
views in your database:
USE <your_database_name>
GO
SELECT * FROM INFORMATION_SCHEMA.TABLES
You can then filter that by table schema and/or table type, e.g.
SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'
I thought you might forget to add attribute data-toggle="modal"
to the link or button that triggers the modal popup event. Firstly, I also got the same problem but, after adding the attribute above it works well for me.
You need to say math.sqrt
when you use it. Or, do from math import sqrt
.
Hmm, I just read your question more thoroughly.... How are you importing math
? I just tried import math
and then math.sqrt
which worked perfectly. Are you doing something like import math as m
? If so, then you have to prefix the function with m
(or whatever name you used after as
).
pow
is working because there are two versions: an always available version in __builtin__
, and another version in math
.
Best and Free ( maybe only) solution for this is google sheets. i don't know whether it plots as u expected or not but certainly you can draw multiple axes.
Regards
keerthan
No additional packages, to just check outdated and update those which are, this command will do:
npm install $(npm outdated | cut -d' ' -f 1 | sed '1d' | xargs -I '$' echo '$@latest' | xargs echo)
Bulk folder creation and grant permission works me by using the below powershell script.
Import-Csv "D:\Scripts\foldernames.csv" | foreach-object {
$username = $_.foldername
# foldername is the header of csv file
$domain = “example.com”
$folder= "D:\Users"
$domainusername = $domain+“\”+$username
New-Item $folder\$username –Type Directory
Get-Acl $folder\$username
$acl = Get-Acl $folder\$username
$acl.SetAccessRuleProtection($True, $False)
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("Administrators","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")
$acl.AddAccessRule($rule)
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("SYSTEM","FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")
$acl.AddAccessRule($rule)
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("$domain\Domain Admins","Read", "ContainerInherit, ObjectInherit", "None", "Allow")
$acl.AddAccessRule($rule)
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule($domainusername,"Modify", "ContainerInherit, ObjectInherit", "None", "Allow")
$acl.AddAccessRule($rule)
Set-Acl $folder\$username $acl
}
Note: You have to create same domain username in csv file otherwise you will get permission issues
If you use a static key, encrypt and decrypt always give the same result;
public static final String CRYPTOR_KEY = "your static key here";
byte[] keyByte = Base64.getDecoder().decode(CRYPTOR_KEY);
key = new SecretKeySpec(keyByte, "AES");
This is the way how to check whether a given character is alphabet or not
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char c = sc.next().charAt(0);
if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
System.out.println(c + " is an alphabet.");
else
System.out.println(c + " is not an alphabet.");
}
For anyone who has SQL 2012 or later, I was able to accomplish this with stored procedures that aren't dynamic and have the same columns output each time.
The general idea is I build the dynamic query to create, insert into, select from, and drop the temp table, and execute this after it's all generated. I dynamically generate the temp table by first retrieving column names and types from the stored procedure.
Note: there are much better, more universal solutions that will work with fewer lines of code if you're willing/able to update the SP or change configuration and use OPENROWSET
. Use the below if you have no other way.
DECLARE @spName VARCHAR(MAX) = 'MyStoredProc'
DECLARE @tempTableName VARCHAR(MAX) = '#tempTable'
-- might need to update this if your param value is a string and you need to escape quotes
DECLARE @insertCommand VARCHAR(MAX) = 'INSERT INTO ' + @tempTableName + ' EXEC MyStoredProc @param=value'
DECLARE @createTableCommand VARCHAR(MAX)
-- update this to select the columns you want
DECLARE @selectCommand VARCHAR(MAX) = 'SELECT col1, col2 FROM ' + @tempTableName
DECLARE @dropCommand VARCHAR(MAX) = 'DROP TABLE ' + @tempTableName
-- Generate command to create temp table
SELECT @createTableCommand = 'CREATE TABLE ' + @tempTableName + ' (' +
STUFF
(
(
SELECT ', ' + CONCAT('[', name, ']', ' ', system_type_name)
FROM sys.dm_exec_describe_first_result_set_for_object
(
OBJECT_ID(@spName),
NULL
)
FOR XML PATH('')
)
,1
,1
,''
) + ')'
EXEC( @createTableCommand + ' '+ @insertCommand + ' ' + @selectCommand + ' ' + @dropCommand)
A much simpler way is to simply use the round() function. Here is an example.
total_price = float()
price_1 = 2.99
price_2 = 0.99
total_price = price_1 + price_2
If you were to print out total_price right now you would get
3.9800000000000004
But if you enclose it in a round() function like so
print(round(total_price,2))
The output equals
3.98
The round() function works by accepting two parameters. The first is the number you want to round. The second is the number of decimal places to round to.
lines
is a list. re.findall()
doesn't take lists.
>>> import re
>>> f = open('README.md', 'r')
>>> lines = f.readlines()
>>> match = re.findall('[A-Z]+', lines)
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/usr/lib/python2.7/re.py", line 177, in findall
return _compile(pattern, flags).findall(string)
TypeError: expected string or buffer
>>> type(lines)
<type 'list'>
From help(file.readlines)
. I.e. readlines()
is for loops/iterating:
readlines(...)
readlines([size]) -> list of strings, each a line from the file.
To find all uppercase characters in your file:
>>> import re
>>> re.findall('[A-Z]+', open('README.md', 'r').read())
['S', 'E', 'A', 'P', 'S', 'I', 'R', 'C', 'I', 'A', 'P', 'O', 'G', 'P', 'P', 'T', 'V', 'W', 'V', 'D', 'A', 'L', 'U', 'O', 'I', 'L', 'P', 'A', 'D', 'V', 'S', 'M', 'S', 'L', 'I', 'D', 'V', 'S', 'M', 'A', 'P', 'T', 'P', 'Y', 'C', 'M', 'V', 'Y', 'C', 'M', 'R', 'R', 'B', 'P', 'M', 'L', 'F', 'D', 'W', 'V', 'C', 'X', 'S']
Try-except-else is great for combining the EAFP pattern with duck-typing:
try:
cs = x.cleanupSet
except AttributeError:
pass
else:
for v in cs:
v.cleanup()
You might thing this naïve code is fine:
try:
for v in x.cleanupSet:
v.clenaup()
except AttributeError:
pass
This is a great way of accidentally hiding severe bugs in your code. I typo-ed cleanup there, but the AttributeError that would let me know is being swallowed. Worse, what if I'd written it correctly, but the cleanup method was occasionally being passed a user type that had a misnamed attribute, causing it to silently fail half-way through and leave a file unclosed? Good luck debugging that one.
You may go with Plotly library. It can render interactive 3D plots directly in Jupyter Notebooks.
To do so you first need to install Plotly by running:
pip install plotly
You might also want to upgrade the library by running:
pip install plotly --upgrade
After that in you Jupyter Notebook you may write something like:
# Import dependencies
import plotly
import plotly.graph_objs as go
# Configure Plotly to be rendered inline in the notebook.
plotly.offline.init_notebook_mode()
# Configure the trace.
trace = go.Scatter3d(
x=[1, 2, 3], # <-- Put your data instead
y=[4, 5, 6], # <-- Put your data instead
z=[7, 8, 9], # <-- Put your data instead
mode='markers',
marker={
'size': 10,
'opacity': 0.8,
}
)
# Configure the layout.
layout = go.Layout(
margin={'l': 0, 'r': 0, 'b': 0, 't': 0}
)
data = [trace]
plot_figure = go.Figure(data=data, layout=layout)
# Render the plot.
plotly.offline.iplot(plot_figure)
As a result the following chart will be plotted for you in Jupyter Notebook and you'll be able to interact with it. Of course you will need to provide your specific data instead of suggeseted one.
I followed the above (never a bad idea to keep up to date with brew anyhow) and still had the same exact issue:
LAPTOP:folder Username$ php -v
dyld: Library not loaded: /usr/local/lib/libpng15.15.dylib
Referenced from: /usr/local/bin/php
Reason: image not found
Trace/BPT trap: 5
Then figured out a simpler way:
Search for your libpng version(s) on your box:
# Requires locate & updatedb for mac os x
# See Link [1]
LAPTOP:folder Username$ locate libpng15.15.dylib
/Applications/GIMP.app/Contents/Resources/lib/libpng15.15.dylib
/usr/X11/lib/libpng15.15.dylib
/usr/local/Cellar/libpng/1.5.14/lib/libpng15.15.dylib
Make a symlink:
LAPTOP:folder Username$ ln -s /usr/local/Cellar/libpng/1.5.14/lib/libpng15.15.dylib /usr/local/lib/libpng15.15.dylib
Try again:
LAPTOP:folder Username$ php -v
PHP 5.3.26 (cli) (built: Aug 25 2013 16:07:23)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2013 Zend Technologies
with Xdebug v2.2.3, Copyright (c) 2002-2013, by Derick Rethans
adb uninstall <package_name>
can be used to uninstall an app via your PC. If you want this to happen automatically every time you launch your app via Android Studio, you can do this:
adb
in Program: and uninstall <your-package-name>
in Parameters:.
Make sure that the new item is selected when you click Ok in the popup window.Note: If you do not have adb in your PATH environment variable, give the full path to adb in Program: field (eg /home/user/android/sdk/platform-tools/adb).
You can achieve this with a few simple extension methods. The following Date extension method returns just the timezone component in ISO format, then you can define another for the date/time part and combine them for a complete date-time-offset string.
Date.prototype.getISOTimezoneOffset = function () {
const offset = this.getTimezoneOffset();
return (offset < 0 ? "+" : "-") + Math.floor(Math.abs(offset / 60)).leftPad(2) + ":" + (Math.abs(offset % 60)).leftPad(2);
}
Date.prototype.toISOLocaleString = function () {
return this.getFullYear() + "-" + (this.getMonth() + 1).leftPad(2) + "-" +
this.getDate().leftPad(2) + "T" + this.getHours().leftPad(2) + ":" +
this.getMinutes().leftPad(2) + ":" + this.getSeconds().leftPad(2) + "." +
this.getMilliseconds().leftPad(3);
}
Number.prototype.leftPad = function (size) {
var s = String(this);
while (s.length < (size || 2)) {
s = "0" + s;
}
return s;
}
Example usage:
var date = new Date();
console.log(date.toISOLocaleString() + date.getISOTimezoneOffset());
// Prints "2020-08-05T16:15:46.525+10:00"
I know it's 2020 and most people are probably using Moment.js by now, but a simple copy & pastable solution is still sometimes handy to have.
(The reason I split the date/time and offset methods is because I'm using an old Datejs library which already provides a flexible toString
method with custom format specifiers, but just doesn't include the timezone offset. Hence, I added toISOLocaleString
for anyone without said library.)
a) If you want 0 when value is null
SELECT isnull(PartNum,0) AS PartNumber, PartID
FROM Part
b) If you want 0 when value is null and otherwise 1
SELECT
(CASE
WHEN PartNum IS NULL THEN 0
ELSE 1
END) AS PartNumber,
PartID
FROM Part
I also met this problem just now and solved it in this way. So I recorded it here, and I wish it be useful for others.
Scenario:
The error occurred.
Solution:
In case you do not need indentation that much but a few line breaks, it could be sufficient to simply regex...
String leastPrettifiedXml = uglyXml.replaceAll("><", ">\n<");
The code is nice, not the result because of missing indentation.
(For solutions with indentation, see other answers.)
in regards to:
Take a look at the open source WordPress application. They have a very re-usable window they have created for displaying an "activity in progress" type display over top of whatever view your application is currently displaying.
note that if you do utilise this code you MUST provide ALL the sourcecode to your own application to any user that requests it. You need to be aware that they may decide to repackage your code and sell it on the store themselves. This is all provided for under the terms of the GNU General Public License (GPL).
If you don't want to be forced into opening your sourcecode then you cannot use anything from the wordpress iphone application including the, referenced activity progress window, without forcing the GPL to apply to your own.
The official RFC which defines this specification could be found here:
http://tools.ietf.org/html/rfc4021#section-2.1.2 (look at paragraph 2.1.2. and the following)
2.1.2. Header Field: From
Description: Mailbox of message author [...] Related information: Specifies the author(s) of the message; that is, the mailbox(es) of the person(s) or system(s) responsible for the writing of the message. Defined as standard by RFC 822.
2.1.3. Header Field: Sender
Description: Mailbox of message sender [...] Related information: Specifies the mailbox of the agent responsible for the actual transmission of the message. Defined as standard by RFC 822.
2.1.22. Header Field: Return-Path
Description: Message return path [...] Related information: Return path for message response diagnostics. See also RFC 2821 [17]. Defined as standard by RFC 822.
Try Access DataTable easiest way which can help you for getting perfect idea for accessing DataTable, DataSet using Linq...
Consider following example, suppose we have DataTable like below.
DataTable ObjDt = new DataTable("List");
ObjDt.Columns.Add("WorkName", typeof(string));
ObjDt.Columns.Add("Price", typeof(decimal));
ObjDt.Columns.Add("Area", typeof(string));
ObjDt.Columns.Add("Quantity",typeof(int));
ObjDt.Columns.Add("Breath",typeof(decimal));
ObjDt.Columns.Add("Length",typeof(decimal));
Here above is the code for DatTable, here we assume that there are some data are available in this DataTable, and we have to bind Grid view of particular by processing some data as shown below.
Area | Quantity | Breath | Length | Price = Quantity * breath *Length
Than we have to fire following query which will give us exact result as we want.
var data = ObjDt.AsEnumerable().Select
(r => new
{
Area = r.Field<string>("Area"),
Que = r.Field<int>("Quantity"),
Breath = r.Field<decimal>("Breath"),
Length = r.Field<decimal>("Length"),
totLen = r.Field<int>("Quantity") * (r.Field<decimal>("Breath") * r.Field<decimal>("Length"))
}).ToList();
We just have to assign this data variable as Data Source.
By using this simple Linq query we can get all our accepts, and also we can perform all other LINQ queries with this…
Copied from the formal specification: ECMAScript 5.1 section 11.9.5
11.9.4 The Strict Equals Operator ( === )
The production EqualityExpression : EqualityExpression === RelationalExpression is evaluated as follows:
- Let lref be the result of evaluating EqualityExpression.
- Let lval be GetValue(lref).
- Let rref be the result of evaluating RelationalExpression.
- Let rval be GetValue(rref).
- Return the result of performing the strict equality comparison rval === lval. (See 11.9.6)
11.9.5 The Strict Does-not-equal Operator ( !== )
The production EqualityExpression : EqualityExpression !== RelationalExpression is evaluated as follows:
- Let lref be the result of evaluating EqualityExpression.
- Let lval be GetValue(lref).
- Let rref be the result of evaluating RelationalExpression.
- Let rval be GetValue(rref). Let r be the result of performing strict equality comparison rval === lval. (See 11.9.6)
- If r is true, return false. Otherwise, return true.
11.9.6 The Strict Equality Comparison Algorithm
The comparison x === y, where x and y are values, produces true or false. Such a comparison is performed as follows:
- If Type(x) is different from Type(y), return false.
- Type(x) is Undefined, return true.
- Type(x) is Null, return true.
- Type(x) is Number, then
- If x is NaN, return false.
- If y is NaN, return false.
- If x is the same Number value as y, return true.
- If x is +0 and y is -0, return true.
- If x is -0 and y is +0, return true.
- Return false.
- If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions); otherwise, return false.
- If Type(x) is Boolean, return true if x and y are both true or both false; otherwise, return false.
- Return true if x and y refer to the same object. Otherwise, return false.
Run command rndc querylog on
or add querylog yes;
to options{};
section in named.conf
to activate that channel.
Also make sure you’re checking correct directory if your bind is chrooted.
adding HttpClientModule
in app.module.ts
file in import
section fixed my issue.
Using Thread.currentThread()
:
private class MyTask implements Runnable {
public void run() {
long threadId = Thread.currentThread().getId();
logger.debug("Thread # " + threadId + " is doing this task");
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices.AccountManagement;
class WindowsCred
{
private const string SPLIT_1 = "\\";
public static bool ValidateW(string UserName, string Password)
{
bool valid = false;
string Domain = "";
if (UserName.IndexOf("\\") != -1)
{
string[] arrT = UserName.Split(SPLIT_1[0]);
Domain = arrT[0];
UserName = arrT[1];
}
if (Domain.Length == 0)
{
Domain = System.Environment.MachineName;
}
using (PrincipalContext context = new PrincipalContext(ContextType.Domain, Domain))
{
valid = context.ValidateCredentials(UserName, Password);
}
return valid;
}
}
Kashif Mushtaq Ottawa, Canada
Here is what I would do.
In your base class (can be rootVC BaseVc etc),
A. Write a Protocol to send the "DidFinishReloading" callback.
@protocol ReloadComplition <NSObject>
@required
- (void)didEndReloading:(UITableView *)tableView;
@end
B. Write a generic method to reload the table view.
-(void)reloadTableView:(UITableView *)tableView withOwner:(UIViewController *)aViewController;
In the base class method implementation, call reloadData followed by delegateMethod with delay.
-(void)reloadTableView:(UITableView *)tableView withOwner:(UIViewController *)aViewController{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[tableView reloadData];
if(aViewController && [aViewController respondsToSelector:@selector(didEndReloading:)]){
[aViewController performSelector:@selector(didEndReloading:) withObject:tableView afterDelay:0];
}
}];
}
Confirm to the reload completion protocol in all the view controllers where you need the callback.
-(void)didEndReloading:(UITableView *)tableView{
//do your stuff.
}
Reference: https://discussions.apple.com/thread/2598339?start=0&tstart=0
This is due a conflict of versions, to solve it, just force an update of your support-annotations version, adding this line on your module: app gradle
implementation ('com.android.support:support-annotations:27.1.1')
Hope this solves your issue ;)
Edit
Almost forgot, you can declare a single extra property (https://docs.gradle.org/current/userguide/writing_build_scripts.html#sec:extra_properties) for the version, go to your project (or your top) gradle file, and declare your support, or just for this example, annotation version var
ext.annotation_version = "27.1.1"
Then in your module gradle replace it with:
implementation ("com.android.support:support-annotations:$annotation_version")
This is very similar to the @emadabel solution, which is a good alternative for doing it, but without the block, or the rootproject
prefix.
I have gone through many links but this answer helped me alot:
$scope.redirectPage = function (data) {
$window.open(data, "popup", "width=1000,height=700,left=300,top=200");
};
** data will be absolute url which you are hitting.
show
is probably not the best choice for this. What I would do is use pyplot.draw()
instead. You also might want to include a small time delay (e.g., time.sleep(0.05)
) in the loop so that you can see the plots happening. If I make these changes to your example it works for me and I see each point appearing one at a time.
I had a doubt that whether the encrypted text will be same for single text when encryption done by multiple times on a same text??
This depends strongly on the crypto algorithm you use:
This worked for me (I added an "if sheet visible" because in my case I wanted to skip hidden sheets)
Sub Create_new_file()
Application.DisplayAlerts = False
Dim wb As Workbook
Dim wbNew As Workbook
Dim sh As Worksheet
Dim shNew As Worksheet
Dim pname, parea As String
Set wb = ThisWorkbook
Workbooks.Add
Set wbNew = ActiveWorkbook
For Each sh In wb.Worksheets
pname = sh.Name
If sh.Visible = True Then
sh.Copy After:=wbNew.Sheets(Sheets.Count)
wbNew.Sheets(Sheets.Count).Cells.ClearContents
wbNew.Sheets(Sheets.Count).Cells.ClearFormats
wb.Sheets(sh.Name).Activate
Range(sh.PageSetup.PrintArea).Select
Selection.Copy
wbNew.Sheets(pname).Activate
Range("A1").Select
With Selection
.PasteSpecial (xlValues)
.PasteSpecial (xlFormats)
.PasteSpecial (xlPasteColumnWidths)
End With
ActiveSheet.Name = pname
End If
Next
wbNew.Sheets("Hoja1").Delete
Application.DisplayAlerts = True
End Sub
Since the time the question was asked, the draft for the const
keyword is already a living standard as part of ECMAScript 2015. Also the current version of Node.js supports const declarations without the --harmony
flag.
With the above said you can now run node app.js
, with app.js
:
'use strict';
const MB = 1024 * 1024;
...
getting both the syntax sugar and the benefits of strict mode.
Try Unlocker.
The Unlocker site has a nifty chart (scroll down after following the link) that shows a comparison to other tools. Obviously such comparisons are usually biased since they are typically written by the tool author, but the chart at least lists the alternatives so that you can try them for yourself.
Try to use:
location.reload(true);
When this method receives a true
value as argument, it will cause the page to always be reloaded from the server. If it is false or not specified, the browser may reload the page from its cache.
More info:
Run it through a debugger. All will become clear.
You are facing issue in
s1.name="Paolo";
because, in the LHS, you're using an array type, which is not assignable.
To elaborate, from C11
, chapter §6.5.16
assignment operator shall have a modifiable lvalue as its left operand.
and, regarding the modifiable lvalue, from chapter §6.3.2.1
A modifiable lvalue is an lvalue that does not have array type, [...]
You need to use strcpy()
to copy into the array.
That said, data s1 = {"Paolo", "Rossi", 19};
works fine, because this is not a direct assignment involving assignment operator. There we're using a brace-enclosed initializer list to provide the initial values of the object. That follows the law of initialization, as mentioned in chapter §6.7.9
Each brace-enclosed initializer list has an associated current object. When no designations are present, subobjects of the current object are initialized in order according to the type of the current object: array elements in increasing subscript order, structure members in declaration order, and the first named member of a union.[....]
I am using windows 8. I had the same problem. I added the path "C:\MinGW\bin" to system environment variable named 'path' then it worked. May be, you can try the same. Hope it'll help!
Just complementing what Devart said, the below code is not ordering according to the question:
SELECT t1.* FROM messages t1
JOIN (SELECT from_id, MAX(timestamp) timestamp FROM messages GROUP BY from_id) t2
ON t1.from_id = t2.from_id AND t1.timestamp = t2.timestamp;
The "GROUP BY" clause must be in the main query since that we need first reorder the "SOURCE" to get the needed "grouping" so:
SELECT t1.* FROM messages t1
JOIN (SELECT from_id, MAX(timestamp) timestamp FROM messages ORDER BY timestamp DESC) t2
ON t1.from_id = t2.from_id AND t1.timestamp = t2.timestamp GROUP BY t2.timestamp;
Regards,
The zeroth parameter of a shell command is the command itself (or sometimes the shell itself). You should be using $1
.
(("$#" < 1)) && ( (("$1" != 1)) || (("$1" -ne 0q)) )
Your boolean logic is also a bit confused:
(( "$#" < 1 && # If the number of arguments is less than one…
"$1" != 1 || "$1" -ne 0)) # …how can the first argument possibly be 1 or 0?
This is probably what you want:
(( "$#" )) && (( $1 == 1 || $1 == 0 )) # If true, there is at least one argument and its value is 0 or 1
Solution by @MaxU worked very well. I have just one suggestion:
If truncate_sheet=True is specified than "startrow" should NOT be retained from existing sheet. I suggest:
if startrow is None and sheet_name in writer.book.sheetnames:
if not truncate_sheet: # truncate_sheet would use startrow if provided (or zero below)
startrow = writer.book[sheet_name].max_row
You can try this
var lastPostDate = reader[3] == DBNull.Value ?
default(DateTime?):
Convert.ToDateTime(reader[3]);
I was having the same problem, I had a ComboBox followed by a ListBox in a StackPanel and the scroll bar for the ListBox was not showing up. I solved this by putting the two in a DockPanel instead. I set the ComboBox DockPanel.Dock="Top" and let the ListBox fill the remaining space.
What you can do is use WMI to get the paths. This will allow you to get the path regardless it's a 32-bit or 64-bit application. Here's an example demonstrating how you can get it:
// include the namespace
using System.Management;
var wmiQueryString = "SELECT ProcessId, ExecutablePath, CommandLine FROM Win32_Process";
using (var searcher = new ManagementObjectSearcher(wmiQueryString))
using (var results = searcher.Get())
{
var query = from p in Process.GetProcesses()
join mo in results.Cast<ManagementObject>()
on p.Id equals (int)(uint)mo["ProcessId"]
select new
{
Process = p,
Path = (string)mo["ExecutablePath"],
CommandLine = (string)mo["CommandLine"],
};
foreach (var item in query)
{
// Do what you want with the Process, Path, and CommandLine
}
}
Note that you'll have to reference the System.Management.dll
assembly and use the System.Management
namespace.
For more info on what other information you can grab out of these processes such as the command line used to start the program (CommandLine
), see the Win32_Process class and WMI .NET for for more information.
From what I've read, this error means that you're not referencing the table name correctly. One common reason is that the table is defined with a mixed-case spelling, and you're trying to query it with all lower-case.
In other words, the following fails:
CREATE TABLE "SF_Bands" ( ... );
SELECT * FROM sf_bands; -- ERROR!
Use double-quotes to delimit identifiers so you can use the specific mixed-case spelling as the table is defined.
SELECT * FROM "SF_Bands";
Re your comment, you can add a schema to the "search_path" so that when you reference a table name without qualifying its schema, the query will match that table name by checked each schema in order. Just like PATH
in the shell or include_path
in PHP, etc. You can check your current schema search path:
SHOW search_path
"$user",public
You can change your schema search path:
SET search_path TO showfinder,public;
See also http://www.postgresql.org/docs/8.3/static/ddl-schemas.html
Well, like (almost) every console program for unix-like systems, git does not tell you anything if a command succeeds. It prints out something only if there's something wrong.
However if you want to be sure of what just happened, just type
git status
and see which changes are going to be committed and which not. I suggest you to use this before every commit, just to be sure that you are not forgetting anything.
Since you seem new to git, here is a link to a free online book that introduces you to git. It's very useful, it writes about basics as well as well known different workflows: http://git-scm.com/book
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:padding="20dp" > <TextView android:id="@+id/textview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:shadowColor="#000" android:shadowDx="0" android:shadowDy="0" android:shadowRadius="50" android:text="Text Shadow Example1" android:textColor="#FBFBFB" android:textSize="28dp" android:textStyle="bold" /> <TextView android:id="@+id/textview2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="Text Shadow Example2" android:textColor="#FBFBFB" android:textSize="28dp" android:textStyle="bold" /> </LinearLayout>
In the above XML layout code, the textview1 is given with Shadow effect in the layout. below are the configuration items are
android:shadowDx – specifies the X-axis offset of shadow. You can give -/+ values, where -Dx draws a shadow on the left of text and +Dx on the right
android:shadowDy – it specifies the Y-axis offset of shadow. -Dy specifies a shadow above the text and +Dy specifies below the text.
android:shadowRadius – specifies how much the shadow should be blurred at the edges. Provide a small value if shadow needs to be prominent. android:shadowColor – specifies the shadow color
Shadow Effect on Android TextView pragmatically
Use below code snippet to get the shadow effect on the second TextView pragmatically.
TextView textv = (TextView) findViewById(R.id.textview2); textv.setShadowLayer(30, 0, 0, Color.RED);
Output :
In my case, I had to create local.properties file with sdk.dir=PATH_TO_ANDROID_SDK in my machine. It seems that, it's regarding the android sdk path setup. Hence, it could also be set in ANDROID_HOME env. variable too.
If you are not validating explicitly for numbers in the text field, in any case its better to use
int result=0;
if(int.TryParse(textBox1.Text,out result))
Now if the result is success then you can proceed with your calculations.
I had a similar error with the following code:-
foreach($myvar as $key => $value){
$query = "SELECT stuff
FROM table
WHERE col1 = '$criteria1'
AND col2 = '$criteria2'";
$result = mysql_query($query) or die('Could not execute query - '.mysql_error(). __FILE__. __LINE__. $query);
$point_values = mysql_fetch_assoc($result);
$top_five_actions[$key] += $point_values; //<--- Problem Line
}
It turned out that my $point_values variable was occasionally returning false which caused the problem so I fixed it by wrapping it in mysql_num_rows check:-
if(mysql_num_rows($result) > 0) {
$point_values = mysql_fetch_assoc($result);
$top_five_actions[$key] += $point_values;
}
Not sure if this helps though?
Cheers
MySQL use HAVING statement for this tasks.
Your query would look like this:
SELECT g.group_id, COUNT(m.member_id) AS members
FROM groups AS g
LEFT JOIN group_members AS m USING(group_id)
GROUP BY g.group_id
HAVING members > 4
example when references have different names
SELECT g.id, COUNT(m.member_id) AS members
FROM groups AS g
LEFT JOIN group_members AS m ON g.id = m.group_id
GROUP BY g.id
HAVING members > 4
Also, make sure that you set indexes inside your database schema for keys you are using in JOINS as it can affect your site performance.
Time to contribute now. I am sysadmin role and worked on getting two public access users to execute xp_cmdshell. I am able to execute xp_cmdshell but not the two users.
I did the following steps:
create new role:
use master
CREATE ROLE [CmdShell_Executor] AUTHORIZATION [dbo]
GRANT EXEC ON xp_cmdshell TO [CmdShell_Executor]
add users in master database: Security --> Users. Membership checks only [CmdShell_Executor] that is just created
set up proxy account:
EXEC sp_xp_cmdshell_proxy_account 'domain\user1','users1 Windows password'
EXEC sp_xp_cmdshell_proxy_account 'domain\user2','users2 Windows password'
Then both users can execute the stored procedure that contains xp_cmdshell invoking a R script run. I let the users come to my PC to type in the password, execute the one line code, then delete the password.
Below is a slightly awkward solution for the special case in which you are creating the original file yourself and happen to know the insertion location (e.g. you know ahead of time that you will need to insert a line with an additional name before the third line, but won't know the name until after you've fetched and written the rest of the names). Reading, storing and then re-writing the entire contents of the file as described in other answers is, I think, more elegant than this option, but may be undesirable for large files.
You can leave a buffer of invisible null characters ('\0') at the insertion location to be overwritten later:
num_names = 1_000_000 # Enough data to make storing in a list unideal
max_len = 20 # The maximum allowed length of the inserted line
line_to_insert = 2 # The third line is at index 2 (0-based indexing)
with open(filename, 'w+') as file:
for i in range(line_to_insert):
name = get_name(i) # Returns 'Alfred' for i = 0, etc.
file.write(F'{i + 1}. {name}\n')
insert_position = file.tell() # Position to jump back to for insertion
file.write('\0' * max_len + '\n') # Buffer will show up as a blank line
for i in range(line_to_insert, num_names):
name = get_name(i)
file.write(F'{i + 2}. {name}\n') # Line numbering now bumped up by 1.
# Later, once you have the name to insert...
with open(filename, 'r+') as file: # Must use 'r+' to write to middle of file
file.seek(insert_position) # Move stream to the insertion line
name = get_bonus_name() # This lucky winner jumps up to 3rd place
new_line = F'{line_to_insert + 1}. {name}'
file.write(new_line[:max_len]) # Slice so you don't overwrite next line
Unfortunately there is no way to delete-without-replacement any excess null characters that did not get overwritten (or in general any characters anywhere in the middle of a file), unless you then re-write everything that follows. But the null characters will not affect how your file looks to a human (they have zero width).
There are at least two ways for attach a method to an instance without types.MethodType
:
>>> class A:
... def m(self):
... print 'im m, invoked with: ', self
>>> a = A()
>>> a.m()
im m, invoked with: <__main__.A instance at 0x973ec6c>
>>> a.m
<bound method A.m of <__main__.A instance at 0x973ec6c>>
>>>
>>> def foo(firstargument):
... print 'im foo, invoked with: ', firstargument
>>> foo
<function foo at 0x978548c>
1:
>>> a.foo = foo.__get__(a, A) # or foo.__get__(a, type(a))
>>> a.foo()
im foo, invoked with: <__main__.A instance at 0x973ec6c>
>>> a.foo
<bound method A.foo of <__main__.A instance at 0x973ec6c>>
2:
>>> instancemethod = type(A.m)
>>> instancemethod
<type 'instancemethod'>
>>> a.foo2 = instancemethod(foo, a, type(a))
>>> a.foo2()
im foo, invoked with: <__main__.A instance at 0x973ec6c>
>>> a.foo2
<bound method instance.foo of <__main__.A instance at 0x973ec6c>>
Useful links:
Data model - invoking descriptors
Descriptor HowTo Guide - invoking descriptors
I found the GNU Introduction to PDF to be helpful in understanding the structure. It includes an easily readable example PDF file that they describe in complete detail.
Other helpful links:
Java also does not use line numbers, which is a necessity for a GOTO function. Unlike C/C++, Java does not have goto statement, but java supports label. The only place where a label is useful in Java is right before nested loop statements. We can specify label name with break to break out a specific outer loop.
I noticed something else about your coding.... look
INSERT INTO reports_services (id,title,description,cost) VALUES (0, 'test title', 'test decription ', '3.80')
in your "CREATE TABLE" code you have the id set to "AUTO_INCREMENT" which means it's automatically generating a result for that field.... but in your above code you include it as one of the insertions and in the "VALUES" you have a 0 there... idk if that's your way of telling us you left it blank because it's set to AUTO_INC. or if that's the actual code you have... if it's the code you have not only should you not be trying to send data to a field set to generate it automatically, but the RIGHT WAY to do it WRONG would be
'0',
you put
0,
lol....so that might be causing some of the problem... I also just noticed in the code after "test description" you have a space before the '.... that might be throwing something off too.... idk.. I hope this helps n maybe resolves some other problem you might be pulling your hair out about now.... speaking of which.... I need to figure out my problem before I tear all my hair out..... good luck.. :)
UPDATE.....
I almost forgot... if you have the 0 there to show that it's blank... you could be entering "test title" as the id and "test description" as the title then "3.whatever cents" for the description leaving "cost" empty...... which could be why it maxed out because if I'm not mistaking you have it set to NOT NULL.... and you left it null... so it forced something... maybe.... lol
Apart from the fact that cloning is from server to your machine and forking is making a copy on the server itself, an important difference is that when we clone, we actually get all the branches, labels, etc.
But when we fork, we actually only get the current files in the master branch, nothing other than that. This means we don't get the other branches, etc.
Hence if you have to merge something back to the original repository, it is a inter-repository merge and will definitely need higher privileges.
Fork is not a command in Git; it is just a concept which GitHub implements. Remember Git was designed to work in peer-to-peer environment without the need to synchronize stuff with any master copy. The server is just another peer, but we look at it as a master copy.
You can try with python3 manage.py runserver
.
It works for me.
Here's a a couple of useful link that I found when I started with JNI
http://en.wikipedia.org/wiki/Java_Native_Interface
http://download.oracle.com/javase/1.5.0/docs/guide/jni/spec/functions.html
concerning your problem you can use this
JNIEXPORT void JNICALL Java_ClassName_MethodName(JNIEnv *env, jobject obj, jstring javaString)
{
const char *nativeString = env->GetStringUTFChars(javaString, 0);
// use your string
env->ReleaseStringUTFChars(javaString, nativeString);
}
Install new version of Dev c++. It works fine in Windows 8. It also supports 64 bit version.
Download link is http://sourceforge.net/projects/orwelldevcpp/ .
You could do the following:
.interrupt
the working threads if they wait for data in some blocking call)writeBatch
in your case) to finish, by calling the Thread.join()
method on the working threads.Some sketchy code:
static volatile boolean keepRunning = true;
In run() you change to
for (int i = 0; i < N && keepRunning; ++i)
writeBatch(pw, i);
In main() you add:
final Thread mainThread = Thread.currentThread();
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
keepRunning = false;
mainThread.join();
}
});
That's roughly how I do a graceful "reject all clients upon hitting Control-C" in terminal.
From the docs:
When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt.
That is, a shutdown hook keeps the JVM running until the hook has terminated (returned from the run()-method.
Run the below commands and it will work.
Go to terminal and type
sudo chown -RL root:mysql /usr/local/mysql
sudo chown -RL mysql:mysql /usr/local/mysql/data
sudo /usr/local/mysql/support-files/mysql.server start
I am using WAMP server.
Actually its files showed that openssl is opened.
But manually I went to the folder and edited php.ini
.
Then I found it has not opened openssl.I uncommented it and it worked after after WAMP restart.
First ,you should install github in your PC; Second,you can download the tool 'Everything'; Third,open the tool everything ,type git.exe,then you will find the location and copy the location to PyCharm ,and Test,you will see successfully!
After I updated my MySql, I was getting the same error message. It turned out that after installing a different version on MySql, inside the my.ini, the port was different. Previous MySql version had port 3306 but the new one have port 3308. Check your MySql my.ini, if it is different use the port from .ini in your connection.
I don't think there is a way to ignore adding DEFINER
s to the dump. But there are ways to remove them after the dump file is created.
Open the dump file in a text editor and replace all occurrences of DEFINER=root@localhost
with an empty string ""
Edit the dump (or pipe the output) using perl
:
perl -p -i.bak -e "s/DEFINER=\`\w.*\`@\`\d[0-3].*[0-3]\`//g" mydatabase.sql
mysqldump ... | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' > triggers_backup.sql
Basically all you need to do is add $ as prefix at column letter and row number. Please see image below
You can use microtime
and calculate the difference:
$time_pre = microtime(true);
exec(...);
$time_post = microtime(true);
$exec_time = $time_post - $time_pre;
Here's the PHP docs for microtime
: http://php.net/manual/en/function.microtime.php
I was trying to also sort by a DateTime field descending and this seems to do the trick:
var ud = (from d in env
orderby -d.ReportDate.Ticks
select d.ReportDate.ToString("yyyy-MMM") ).Distinct();
try this
$ cmd='mysql AMORE -u root --password="password" -h localhost -e "select host from amoreconfig"'
$ eval $cmd
Try using the QueryDefs. Create the query with parameters. Then use something like this:
Dim dbs As DAO.Database
Dim qdf As DAO.QueryDef
Set dbs = CurrentDb
Set qdf = dbs.QueryDefs("Your Query Name")
qdf.Parameters("Parameter 1").Value = "Parameter Value"
qdf.Parameters("Parameter 2").Value = "Parameter Value"
qdf.Execute
qdf.Close
Set qdf = Nothing
Set dbs = Nothing
You use
#main_text .title {
/* Properties */
}
If you just put a space between the selectors, styles will apply to all children (and children of children) of the first. So in this case, any child element of #main_text
with the class name title
. If you use >
instead of a space, it will only select the direct child of the element, and not children of children, e.g.:
#main_text > .title {
/* Properties */
}
Either will work in this case, but the first is more typically used.
Python has a built in any() function for exactly this purpose.
you have to call it like this
SELECT dbo.CheckIfSFExists(23, default)
From Technet:
When a parameter of the function has a default value, the keyword DEFAULT must be specified when the function is called in order to retrieve the default value. This behaviour is different from using parameters with default values in stored procedures in which omitting the parameter also implies the default value. An exception to this behaviour is when invoking a scalar function by using the EXECUTE statement. When using EXECUTE, the DEFAULT keyword is not required.
If it happens that you need the Current Active Form from your MDI application: (MDI- Multi Document Interface).
Form activForm;
activForm = Form.ActiveForm.ActiveMdiChild;
Get the Method Names:
var getMethodNames = function (obj) {
return (Object.getOwnPropertyNames(obj).filter(function (key) {
return obj[key] && (typeof obj[key] === "function");
}));
};
Or, Get the Methods:
var getMethods = function (obj) {
return (Object.getOwnPropertyNames(obj).filter(function (key) {
return obj[key] && (typeof obj[key] === "function");
})).map(function (key) {
return obj[key];
});
};
In my notepad++, it seems TextFX needs a perl environment to format HTML files. Tidy2 demands nothing so I think it's more handy.
As the previous answer did show an example of how the full hook might look like here is the code of my working post-receive hook:
#!/usr/bin/python
import sys
from subprocess import call
if __name__ == '__main__':
for line in sys.stdin.xreadlines():
old, new, ref = line.strip().split(' ')
if ref == 'refs/heads/master':
print "=============================================="
print "Pushing to master. Triggering jenkins. "
print "=============================================="
sys.stdout.flush()
call(["curl", "-sS", "http://jenkinsserver/git/notifyCommit?url=ssh://user@gitserver/var/git/repo.git"])
In this case I trigger jenkins jobs only when pushing to master and not other branches.
From the documentation:
list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, soa.insert(0, x)
inserts at the front of the list, anda.insert(len(a),x)
is equivalent toa.append(x)
http://docs.python.org/2/tutorial/datastructures.html#more-on-lists
Create a section called <connectionStrings></connectionStrings>
in your web.config
inside <configuration></configuration>
then add different connection strings to it, for example
<configuration>
<connectionStrings>
<add name="ConnectionStringName" providerName="System.Data.SqlClient" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=DatabaseName;Integrated Security=True;MultipleActiveResultSets=True"/>
</connectionStrings>
</configuration>
Here's a list of all the different connection string formats https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx
REST is somewhat of a revival of old-school HTTP, where the actual HTTP verbs (commands) have semantic meaning. Til recently, apps that wanted to update stuff on the server would supply a form containing an 'action' variable and a bunch of data. The HTTP command would almost always be GET
or POST
, and would be almost irrelevant. (Though there's almost always been a proscription against using GET for operations that have side effects, in reality a lot of apps don't care about the command used.)
With REST, you might instead PUT /profiles/cHao
and send an XML or JSON representation of the profile info. (Or rather, I would -- you would have to update your own profile. :) That'd involve logging in, usually through HTTP's built-in authentication mechanisms.) In the latter case, what you want to do is specified by the URL, and the request body is just the guts of the resource involved.
http://en.wikipedia.org/wiki/Representational_State_Transfer has some details.
Using Dominic's answer I found the answer to my problem specifically was an invalid DateTiime in the source data before it was applied to the range. Somewhere between the database, .NET and Excel the conversion of the date defaulted down to "1/1/1899 12:00:00 AM". I had to check it and convert it to an empty string and it fixed it for me.
if (objectArray[row, col].ToString() == "1/1/1899 12:00:00 AM")
{
objectArray[row, col] = string.Empty;
}
This is probably a pretty specific example but hopefully it will save somebody else some time if they are trying to track down a piece of invalid data.
This worked great for me
$this->db->where('sell_date BETWEEN "'. date('Y-m-d', strtotime($start_date)). '" and "'. date('Y-m-d', strtotime($end_date)).'"');
Another thing to check:
When you install the GoogleAPIs into a .Net app with NuGet, it will inject a new set of dummy values in your *.config file.
Check that any original values are still in place, and remove dummy entries.
Here is the JSFiddle -> https://jsfiddle.net/PRkonsult/mn31qf0p/1/
The JavaScript bit at the bottom is what does the actual magic.
<!--http://getbootstrap.com/components/#navbar-->
<div class="body-wrap">
<div class="container">
<nav class="navbar navbar-inverse" role="navigation">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Brand</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li><a href="#">Separated link</a></li>
<li class="divider"></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="#">Link</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li><a href="#">Separated link</a></li>
</ul>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container-fluid -->
</nav>
</div>
</div>
/* Bootstrap dropdown hover menu */
body {
font-family: 'PT Sans', sans-serif;
font-size: 13px;
font-weight: 400;
color: #4f5d6e;
position: relative;
background: rgb(26, 49, 95);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, rgba(26, 49, 95, 1)), color-stop(10%, rgba(26, 49, 95, 1)), color-stop(24%, rgba(29, 108, 141, 1)), color-stop(37%, rgba(41, 136, 151, 1)), color-stop(77%, rgba(39, 45, 100, 1)), color-stop(90%, rgba(26, 49, 95, 1)), color-stop(100%, rgba(26, 49, 95, 1)));
filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#1a315f', endColorstr='#1a315f', GradientType=0);
}
.body-wrap {
min-height: 700px;
}
.body-wrap {
position: relative;
z-index: 0;
}
.body-wrap: before,
.body-wrap: after {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
z-index: -1;
height: 260px;
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, rgba(26, 49, 95, 1)), color-stop(100%, rgba(26, 49, 95, 0)));
background: linear-gradient(to bottom, rgba(26, 49, 95, 1) 0%, rgba(26, 49, 95, 0) 100%);
filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#1a315f', endColorstr='#001a315f', GradientType=0);
}
.body-wrap:after {
top: auto;
bottom: 0;
background: linear-gradient(to bottom, rgba(26, 49, 95, 0) 0%, rgba(26, 49, 95, 1) 100%);
filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#001a315f', endColorstr='#1a315f', GradientType=0);
}
nav {
margin-top: 60px;
box-shadow: 5px 4px 5px #000;
}
Then the important bit of JavaScript code:
$('ul.nav li.dropdown').hover(function() {
$(this).find('.dropdown-menu').stop(true, true).delay(200).fadeIn(500);
}, function() {
$(this).find('.dropdown-menu').stop(true, true).delay(200).fadeOut(500);
});
Python3:
import importlib.machinery
loader = importlib.machinery.SourceFileLoader('report', '/full/path/report/other_py_file.py')
handle = loader.load_module('report')
handle.mainFunction(parameter)
This method can be used to import whichever way you want in a folder structure (backwards, forwards doesn't really matter, i use absolute paths just to be sure).
There's also the more normal way of importing a python module in Python3,
import importlib
module = importlib.load_module('folder.filename')
module.function()
Kudos to Sebastian for spplying a similar answer for Python2:
import imp
foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()
I'm not sure if we have the same problem since webpack only support one output per configuration as of Jun 2016. I guess you already seen the issue on Github.
But I separate the output path by using the multi-compiler. (i.e. separating the configuration object of webpack.config.js
).
var config = {
// TODO: Add common Configuration
module: {},
};
var fooConfig = Object.assign({}, config, {
name: "a",
entry: "./a/app",
output: {
path: "./a",
filename: "bundle.js"
},
});
var barConfig = Object.assign({}, config,{
name: "b",
entry: "./b/app",
output: {
path: "./b",
filename: "bundle.js"
},
});
// Return Array of Configurations
module.exports = [
fooConfig, barConfig,
];
If you have common configuration among them, you could use the extend library or Object.assign
in ES6 or {...}
spread operator in ES7.
Have you checked if:
class
file under src
folder in your JAVA project?(not file
)I am a newbie who try to run a helloworld example and just got the same error as yours, and these work for me.
grep
can be used even if we're not looking for a string.
Simply running,
grep -RIl "" .
will print out the path to all text files, i.e. those containing only printable characters.
Permitting a nested object :
params.permit( {:school => [:id , :name]},
{:student => [:id,
:name,
:address,
:city]},
{:records => [:marks, :subject]})
Use a wrapper selector and create a container that has a 100% width inside of that wrapper to encapsulate the entire page.
<style>#wrapper {width: 1000px;}
#wrapper .container {max-width: 100%; display: block;}</style>
<body>
<div id="wrapper">
<div class="container">
<div class="row">....
Now the maximum width is set to 1000px and you need no less or sass.