There is _tkinter and Tkinter - both work on Py 3.x But to be safe- Download Loopy and change your python root directory(if you're using an IDE like PyCharms) to Loopy's installation directory. You'll get this library and many more.
As this answer says, you can also just wrap your code in an anonymous function like this:
expect(function(){
model.get('z');
}).to.throw('Property does not exist in model schema.');
Your question will trigger discussion I suppose. The general idea is that it's good to separate behavior and structure. Furthermore, afaik, an inline click handler has to be eval
led to 'become' a real javascript function. And it's pretty old fashioned, allbeit that that's a pretty shaky argument. Ah, well, read some about it @quirksmode.org
Neither of the above answers worked for me, however this did
UPDATE:
As @doppleganger pointed out below, load is gone as of jQuery 3.0, so here's an updated version that uses on
. Please note this will actually work on jQuery 1.7+, so you can implement it this way even if you're not on jQuery 3.0 yet.
$('iframe').on('load', function() {
// do stuff
});
unsigned
means unsigned int
. signed
means signed int
. Using just unsigned
is a lazy way of declaring an unsigned int
in C. Yes this is ANSI.
Using plain java:
String s = "1234567890";
List<String> list = new Scanner(s).findAll("...").map(MatchResult::group).collect(Collectors.toList());
System.out.printf("%s%n", list);
Produces the output:
[123, 456, 789]
Note that this discards leftover characters (0 in this case).
SELECT * FROM tableName WHERE columnName LIKE "%#%" OR columnName LIKE "%$%" OR (etc.)
This probably isn't the most elegant way to do it, but it gets the job done.
In[1]: import numpy as np
In[2]: import pandas as pd
In[3]: df = pd.DataFrame(np.genfromtxt('/Users/spencerlyon2/Desktop/test.csv', dtype=str)[1:], columns=['ID'])
In[4]: df
Out[4]:
ID
0 00013007854817840016671868
1 00013007854817840016749251
2 00013007854817840016754630
3 00013007854817840016781876
4 00013007854817840017028824
5 00013007854817840017963235
6 00013007854817840018860166
Just replace '/Users/spencerlyon2/Desktop/test.csv'
with the path to your file
PROBLEM :-
Sometimes, Localhost may not get resolved. So it tends to return an output as seen below :
# curl -XGET localhost:9200/_cluster/health?pretty
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head>
<meta http-equiv="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<title>ERROR: The requested URL could not be retrieved</title>
<style type="text/css"><!--BODY{background-color:#ffffff;font-family:verdana,sans-serif}PRE{font-family:sans-serif}--></style>
</head><body>
<h1>ERROR</h1>
<h2>The requested URL could not be retrieved</h2>
<hr>
<p>The following error was encountered while trying to retrieve the URL: <a href="http://localhost:9200/_cluster/health?">http://localhost:9200/_cluster/health?</a></p>
<blockquote>
<p><b>Connection to 127.0.0.1 failed.</b></p>
</blockquote>
<p>The system returned: <i>(111) Connection refused</i></p>
<p>The remote host or network may be down. Please try the request again.</p>
<p>Your cache administrator is <a href="mailto:root?subject=CacheErrorInfo%20-%20ERR_CONNECT_FAIL&body=CacheHost%3A%20squid2%0D%0AErrPage%3A%20ERR_CONNECT_FAIL%0D%0AErr%3A%20(111)%20Connection%20refused%0D%0ATimeStamp%3A%20Mon,%2017%20Dec%202018%2008%3A07%3A36%20GMT%0D%0A%0D%0AClientIP%3A%20192.168.13.14%0D%0AServerIP%3A%20127.0.0.1%0D%0A%0D%0AHTTP%20Request%3A%0D%0AGET%20%2F_cluster%2Fhealth%3Fpretty%20HTTP%2F1.1%0AUser-Agent%3A%20curl%2F7.29.0%0D%0AHost%3A%20localhost%3A9200%0D%0AAccept%3A%20*%2F*%0D%0AProxy-Connection%3A%20Keep-Alive%0D%0A%0D%0A%0D%0A">root</a>.</p>
<br>
<hr>
<div id="footer">Generated Mon, 17 Dec 2018 08:07:36 GMT by squid2 (squid/3.0.STABLE25)</div>
</body></html>
# curl -XGET localhost:9200/_cat/indices
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head>
<meta http-equiv="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<title>ERROR: The requested URL could not be retrieved</title>
<style type="text/css"><!--BODY{background-color:#ffffff;font-family:verdana,sans-serif}PRE{font-family:sans-serif}--></style>
</head><body>
<h1>ERROR</h1>
<h2>The requested URL could not be retrieved</h2>
<hr>
<p>The following error was encountered while trying to retrieve the URL: <a href="http://localhost:9200/_cat/indices">http://localhost:9200/_cat/indices</a></p>
<blockquote>
<p><b>Connection to 127.0.0.1 failed.</b></p>
</blockquote>
<p>The system returned: <i>(111) Connection refused</i></p>
<p>The remote host or network may be down. Please try the request again.</p>
<p>Your cache administrator is <a href="mailto:root?subject=CacheErrorInfo%20-%20ERR_CONNECT_FAIL&body=CacheHost%3A%20squid2%0D%0AErrPage%3A%20ERR_CONNECT_FAIL%0D%0AErr%3A%20(111)%20Connection%20refused%0D%0ATimeStamp%3A%20Mon,%2017%20Dec%202018%2008%3A10%3A09%20GMT%0D%0A%0D%0AClientIP%3A%20192.168.13.14%0D%0AServerIP%3A%20127.0.0.1%0D%0A%0D%0AHTTP%20Request%3A%0D%0AGET%20%2F_cat%2Findices%20HTTP%2F1.1%0AUser-Agent%3A%20curl%2F7.29.0%0D%0AHost%3A%20localhost%3A9200%0D%0AAccept%3A%20*%2F*%0D%0AProxy-Connection%3A%20Keep-Alive%0D%0A%0D%0A%0D%0A">root</a>.</p>
<br>
<hr>
<div id="footer">Generated Mon, 17 Dec 2018 08:10:09 GMT by squid2 (squid/3.0.STABLE25)</div>
</body></html>
SOLUTION :-
Guess, this error is most probably returned by Local Squid deployed in the server.
So, it worked fine and good after replacing localhost by the local_ip in which the ElasticSearch has been deployed.
In reference of this answer
https://stackoverflow.com/a/17144634/4146239
For me is the best solution but there's a way to avoid use jQuery.
.directive('loading', function () {_x000D_
return {_x000D_
restrict: 'E',_x000D_
replace:true,_x000D_
template: '<div class="loading"><img src="http://www.nasa.gov/multimedia/videogallery/ajax-loader.gif" width="20" height="20" />LOADING...</div>',_x000D_
link: function (scope, element, attr) {_x000D_
scope.$watch('loading', function (val) {_x000D_
if (val)_x000D_
scope.loadingStatus = 'true';_x000D_
else_x000D_
scope.loadingStatus = 'false';_x000D_
});_x000D_
}_x000D_
}_x000D_
})_x000D_
_x000D_
.controller('myController', function($scope, $http) {_x000D_
$scope.cars = [];_x000D_
_x000D_
$scope.clickMe = function() {_x000D_
scope.loadingStatus = 'true'_x000D_
$http.get('test.json')_x000D_
.success(function(data) {_x000D_
$scope.cars = data[0].cars;_x000D_
$scope.loadingStatus = 'false';_x000D_
});_x000D_
}_x000D_
_x000D_
});
_x000D_
<body ng-app="myApp" ng-controller="myController" ng-init="loadingStatus='true'">_x000D_
<loading ng-show="loadingStatus" ></loading>_x000D_
_x000D_
<div ng-repeat="car in cars">_x000D_
<li>{{car.name}}</li>_x000D_
</div>_x000D_
<button ng-click="clickMe()" class="btn btn-primary">CLICK ME</button>_x000D_
_x000D_
</body>
_x000D_
You need to replace $(element).show(); and (element).show(); with $scope.loadingStatus = 'true'; and $scope.loadingStatus = 'false';
Than, you need to use this variable to set the ng-show attribute of the element.
Even better use implicit remoting to use a module from another Machine!
$s = New-PSSession Server-Name
Invoke-Command -Session $s -ScriptBlock {Import-Module ActiveDirectory}
Import-PSSession -Session $s -Module ActiveDirectory -Prefix REM
This will allow you to use the module off a remote PC for as long as the PSSession is connected.
More Information: https://technet.microsoft.com/en-us/library/ff720181.aspx
If your your list is dynamically generated with unknown number and your target is to always have last div in a new line set last div class to "col-xl-12" and remove other classes so it will always take a full row.
This is a copy of your code corrected so that last div always occupy a full row (I although removed unnecessary classes).
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">_x000D_
<div class="grid">_x000D_
<div class="row">_x000D_
<div class="col-sm-3">Under me should be a DIV</div>_x000D_
<div class="col-md-6 col-sm-5">Under me should be a DIV</div>_x000D_
<div class="col-xl-12">I am the last DIV and I always take a full row for my self!!</div>_x000D_
</div>_x000D_
</div>
_x000D_
The problem is that your ui
property uses a forward declaration of class Ui::MainWindowClass
, hence the "incomplete type" error.
Including the header file in which this class is declared will fix the problem.
EDIT
Based on your comment, the following code:
namespace Ui
{
class MainWindowClass;
}
does NOT declare a class. It's a forward declaration, meaning that the class will exist at some point, at link time.
Basically, it just tells the compiler that the type will exist, and that it shouldn't warn about it.
But the class has to be defined somewhere.
Note this can only work if you have a pointer to such a type.
You can't have a statically allocated instance of an incomplete type.
So either you actually want an incomplete type, and then you should declare your ui
member as a pointer:
namespace Ui
{
// Forward declaration - Class will have to exist at link time
class MainWindowClass;
}
class MainWindow : public QMainWindow
{
private:
// Member needs to be a pointer, as it's an incomplete type
Ui::MainWindowClass * ui;
};
Or you want a statically allocated instance of Ui::MainWindowClass
, and then it needs to be declared.
You can do it in another header file (usually, there's one header file per class).
But simply changing the code to:
namespace Ui
{
// Real class declaration - May/Should be in a specific header file
class MainWindowClass
{};
}
class MainWindow : public QMainWindow
{
private:
// Member can be statically allocated, as the type is complete
Ui::MainWindowClass ui;
};
will also work.
Note the difference between the two declarations. First uses a forward declaration, while the second one actually declares the class (here with no properties nor methods).
You can also use awk
for these purposes, since it allows you to perform more complex checks in a clearer way:
Lines not containing foo
:
awk '!/foo/'
Lines containing neither foo
nor bar
:
awk '!/foo/ && !/bar/'
Lines containing neither foo
nor bar
which contain either foo2
or bar2
:
awk '!/foo/ && !/bar/ && (/foo2/ || /bar2/)'
And so on.
Use '_blank'. It will not only open the link in a new tab but the state of the original webpage will also remain unaffected.
I prefer to use
RadioButton b = (RadioButton) findViewById(R.id.option1);
b.performClick();
instead of using the accepted answer.
RadioButton b = (RadioButton) findViewById(R.id.option1);
b.setChecked(true);
The reason is setChecked(true)
only changes the checked state of radio button. It does not trigger the onClick()
method added to your radio button. Sometimes this might waste your time to debug why the action related to onClick()
not working.
Finding of week number for each date of a month (considering Monday as beginning of the week)
Keep the first date of month contant $B$13
=WEEKNUM(B18,2)-WEEKNUM($B$13,2)+1
WEEKNUM(B18,2)
- returns the week number of the date mentioned in cell B18
WEEKNUM($B$13,2)
- returns the week number of the 1st date of month in cell B13
i had the same problem. it was due to false name in the path. there was a special Character in the path like this: C:\User\My App\Projekte-Tablet&Handy i deleted the "&" character and it worked well.
iloc
works based on integer positioning. So no matter what your row labels are, you can always, e.g., get the first row by doing
df.iloc[0]
or the last five rows by doing
df.iloc[-5:]
You can also use it on the columns. This retrieves the 3rd column:
df.iloc[:, 2] # the : in the first position indicates all rows
You can combine them to get intersections of rows and columns:
df.iloc[:3, :3] # The upper-left 3 X 3 entries (assuming df has 3+ rows and columns)
On the other hand, .loc
use named indices. Let's set up a data frame with strings as row and column labels:
df = pd.DataFrame(index=['a', 'b', 'c'], columns=['time', 'date', 'name'])
Then we can get the first row by
df.loc['a'] # equivalent to df.iloc[0]
and the second two rows of the 'date'
column by
df.loc['b':, 'date'] # equivalent to df.iloc[1:, 1]
and so on. Now, it's probably worth pointing out that the default row and column indices for a DataFrame
are integers from 0 and in this case iloc
and loc
would work in the same way. This is why your three examples are equivalent. If you had a non-numeric index such as strings or datetimes, df.loc[:5]
would raise an error.
Also, you can do column retrieval just by using the data frame's __getitem__
:
df['time'] # equivalent to df.loc[:, 'time']
Now suppose you want to mix position and named indexing, that is, indexing using names on rows and positions on columns (to clarify, I mean select from our data frame, rather than creating a data frame with strings in the row index and integers in the column index). This is where .ix
comes in:
df.ix[:2, 'time'] # the first two rows of the 'time' column
I think it's also worth mentioning that you can pass boolean vectors to the loc
method as well. For example:
b = [True, False, True]
df.loc[b]
Will return the 1st and 3rd rows of df
. This is equivalent to df[b]
for selection, but it can also be used for assigning via boolean vectors:
df.loc[b, 'name'] = 'Mary', 'John'
In your Html page please add
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Test the multiselect with ajax</title>
<!-- Bootstrap -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<!-- Bootstrap multiselect -->
<link rel="stylesheet" href="http://davidstutz.github.io/bootstrap-multiselect/dist/css/bootstrap-multiselect.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.2/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<br>
<form method="post" id="myForm">
<!-- Build your select: -->
<select name="categories[]" id="example-getting-started" multiple="multiple" class="col-md-12">
<option value="A">Cheese</option>
<option value="B">Tomatoes</option>
<option value="C">Mozzarella</option>
<option value="D">Mushrooms</option>
<option value="E">Pepperoni</option>
<option value="F">Onions</option>
<option value="G">10</option>
<option value="H">11</option>
<option value="I">12</option>
</select>
<br><br>
<button type="button" class="btnSubmit"> Send </button>
</form>
<br><br>
<div id="result">result</div>
</div><!--container-->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<!-- Bootstrap multiselect -->
<script src="http://davidstutz.github.io/bootstrap-multiselect/dist/js/bootstrap-multiselect.js"></script>
<!-- Bootstrap multiselect -->
<script src="ajax.js"></script>
<!-- Initialize the plugin: -->
<script type="text/javascript">
$(document).ready(function() {
$('#example-getting-started').multiselect();
});
</script>
</body>
</html>
In your ajax.js page please add
$(document).ready(function () {
$(".btnSubmit").on('click',(function(event) {
var formData = new FormData($('#myForm')[0]);
$.ajax({
url: "action.php",
type: "POST",
data: formData,
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#result").html(data);
// To clear the selected options
var select = $("#example-getting-started");
select.children().remove();
if (data.d) {
$(data.d).each(function(key,value) {
$("#example-getting-started").append($("<option></option>").val(value.State_id).html(value.State_name));
});
}
$('#example-getting-started').multiselect({includeSelectAllOption: true});
$("#example-getting-started").multiselect('refresh');
},
error: function()
{
console.log("failed to send the data");
}
});
}));
});
In your action.php page add
echo "<b>You selected :</b>";
for($i=0;$i<=count($_POST['categories']);$i++){
echo $_POST['categories'][$i]."<br>";
}
The CSS :active
state means the active state of the clicked link - the moment when you clicked on it, but not released the mouse button yet, for example. It doesn't know which page you're on and can't apply any styles to the menu items.
To fix your problem you have to create a class and add it manually to the current page's menu:
a.active { color: #f00 }
<ul>
<li><a href="index.php" class="active">HOME</a></li>
<li><a href="two.php">PORTFOLIO</a></li>
<li><a href="three.php">ABOUT</a></li>
<li><a href="four.php">CONTACT</a></li>
<li><a href="five.php">SHOP</a></li>
</ul>
Option Explicit
Public myarray (1 To 10)
Public Count As Integer
myarray(1) = "A"
myarray(2) = "B"
myarray(3) = "C"
myarray(4) = "D"
myarray(5) = "E"
myarray(6) = "F"
myarray(7) = "G"
myarray(8) = "H"
myarray(9) = "I"
myarray(10) = "J"
Private Function unwrapArray()
For Count = 1 to UBound(myarray)
MsgBox "Letters of the Alphabet : " & myarray(Count)
Next
End Function
Try this:
DataTable dt = (DataTable)Session["dtAllOrders"];
DataTable dtSpecificOrders = dt.Clone();
DataRow[] orderRows = dt.Select("CustomerID = 2");
foreach (DataRow dr in orderRows)
{
dtSpecificOrders.ImportRow(dr);
}
$memberId =$_SESSION['TWILLO']['Id'];
$QueryServer=mysql_query("select * from smtp_server where memberId='".$memberId."'");
$data = array();
while($ser=mysql_fetch_assoc($QueryServer))
{
$data[$ser['Id']] =array('ServerName','ServerPort','Server_limit','email','password','status');
}
Windows Presentation Foundation 4.5 Cookbook by Pavel Yosifovich on page 155 in the section on "Using the common dialog boxes" says:
"What about folder selection (instead of files)? The WPF OpenFileDialog does not support that. One solution is to use Windows Forms' FolderBrowseDialog class. Another good solution is to use the Windows API Code Pack described shortly."
I downloaded the API Code Pack from Windows® API Code Pack for Microsoft® .NET Framework Windows API Code Pack: Where is it?, then added references to Microsoft.WindowsAPICodePack.dll and Microsoft.WindowsAPICodePack.Shell.dll to my WPF 4.5 project.
Example:
using Microsoft.WindowsAPICodePack.Dialogs;
var dlg = new CommonOpenFileDialog();
dlg.Title = "My Title";
dlg.IsFolderPicker = true;
dlg.InitialDirectory = currentDirectory;
dlg.AddToMostRecentlyUsedList = false;
dlg.AllowNonFileSystemItems = false;
dlg.DefaultDirectory = currentDirectory;
dlg.EnsureFileExists = true;
dlg.EnsurePathExists = true;
dlg.EnsureReadOnly = false;
dlg.EnsureValidNames = true;
dlg.Multiselect = false;
dlg.ShowPlacesList = true;
if (dlg.ShowDialog() == CommonFileDialogResult.Ok)
{
var folder = dlg.FileName;
// Do something with selected folder string
}
You can use clone() method to create a copy..
$('#foo1').html( $('#foo2 > div').clone())?;
Answer by @Calvin Froedge is the shortest answer but have an issue also mentioned by @kizu. Due to inconsistent width of the div the div will flick on hover. To solve this issue add minus margin to the right on hover
#div {
overflow:hidden;
height:whatever px;
}
#div:hover {
overflow-y:scroll;
margin-right: -15px; // adjust according to scrollbar width
}
I don't think that notation is available because—unlike say PHP or C—everything in Ruby is an object.
Sure you could use $var=0; $var++
in PHP, but that's because it's a variable and not an object. Therefore, $var = new stdClass(); $var++
would probably throw an error.
I'm not a Ruby or RoR programmer, so I'm sure someone can verify the above or rectify it if it's inaccurate.
For anyone trying to do this in asp.net core. You can use claims.
public class CustomEmailProvider : IUserIdProvider
{
public virtual string GetUserId(HubConnectionContext connection)
{
return connection.User?.FindFirst(ClaimTypes.Email)?.Value;
}
}
Any identifier can be used, but it must be unique. If you use a name identifier for example, it means if there are multiple users with the same name as the recipient, the message would be delivered to them as well. I have chosen email because it is unique to every user.
Then register the service in the startup class.
services.AddSingleton<IUserIdProvider, CustomEmailProvider>();
Next. Add the claims during user registration.
var result = await _userManager.CreateAsync(user, Model.Password);
if (result.Succeeded)
{
await _userManager.AddClaimAsync(user, new Claim(ClaimTypes.Email, Model.Email));
}
To send message to the specific user.
public class ChatHub : Hub
{
public async Task SendMessage(string receiver, string message)
{
await Clients.User(receiver).SendAsync("ReceiveMessage", message);
}
}
Note: The message sender won't be notified the message is sent. If you want a notification on the sender's end. Change the SendMessage
method to this.
public async Task SendMessage(string sender, string receiver, string message)
{
await Clients.Users(sender, receiver).SendAsync("ReceiveMessage", message);
}
These steps are only necessary if you need to change the default identifier. Otherwise, skip to the last step where you can simply send messages by passing userIds or connectionIds to SendMessage
. For more
window.onresize = function(){
var img = document.getElementById('fullsize');
img.style.width = "100%";
};
In IE onresize
event gets fired on every pixel change (width or height) so there could be performance issue. Delay image resizing for few milliseconds by using javascript's window.setTimeout().
http://mbccs.blogspot.com/2007/11/fixing-window-resize-event-in-ie.html
A delegate is a class that wraps a pointer or reference to an object instance, a member method of that object's class to be called on that object instance, and provides a method to trigger that call.
Here's an example:
template <class T>
class CCallback
{
public:
typedef void (T::*fn)( int anArg );
CCallback(T& trg, fn op)
: m_rTarget(trg)
, m_Operation(op)
{
}
void Execute( int in )
{
(m_rTarget.*m_Operation)( in );
}
private:
CCallback();
CCallback( const CCallback& );
T& m_rTarget;
fn m_Operation;
};
class A
{
public:
virtual void Fn( int i )
{
}
};
int main( int /*argc*/, char * /*argv*/ )
{
A a;
CCallback<A> cbk( a, &A::Fn );
cbk.Execute( 3 );
}
Assuming this example HTML:
<input type="text" name="email" id="email" />
<input type="text" name="first_name" id="first_name" />
<input type="text" name="last_name" id="last_name" />
You could have this javascript:
$("#email").bind("change", function(e){
$.getJSON("http://yourwebsite.com/lokup.php?email=" + $("#email").val(),
function(data){
$.each(data, function(i,item){
if (item.field == "first_name") {
$("#first_name").val(item.value);
} else if (item.field == "last_name") {
$("#last_name").val(item.value);
}
});
});
});
Then just you have a PHP script (in this case lookup.php) that takes an email in the query string and returns a JSON formatted array back with the values you want to access. This is the part that actually hits the database to look up the values:
<?php
//look up the record based on email and get the firstname and lastname
...
//build the JSON array for return
$json = array(array('field' => 'first_name',
'value' => $firstName),
array('field' => 'last_name',
'value' => $last_name));
echo json_encode($json );
?>
You'll want to do other things like sanitize the email input, etc, but should get you going in the right direction.
Seems like you might want a treemap.
http://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html
You can pass in a custom comparator to it if that applies.
When you use a decorator, you're replacing one function with another. In other words, if you have a decorator
def logged(func):
def with_logging(*args, **kwargs):
print(func.__name__ + " was called")
return func(*args, **kwargs)
return with_logging
then when you say
@logged
def f(x):
"""does some math"""
return x + x * x
it's exactly the same as saying
def f(x):
"""does some math"""
return x + x * x
f = logged(f)
and your function f
is replaced with the function with_logging
. Unfortunately, this means that if you then say
print(f.__name__)
it will print with_logging
because that's the name of your new function. In fact, if you look at the docstring for f
, it will be blank because with_logging
has no docstring, and so the docstring you wrote won't be there anymore. Also, if you look at the pydoc result for that function, it won't be listed as taking one argument x
; instead it'll be listed as taking *args
and **kwargs
because that's what with_logging takes.
If using a decorator always meant losing this information about a function, it would be a serious problem. That's why we have functools.wraps
. This takes a function used in a decorator and adds the functionality of copying over the function name, docstring, arguments list, etc. And since wraps
is itself a decorator, the following code does the correct thing:
from functools import wraps
def logged(func):
@wraps(func)
def with_logging(*args, **kwargs):
print(func.__name__ + " was called")
return func(*args, **kwargs)
return with_logging
@logged
def f(x):
"""does some math"""
return x + x * x
print(f.__name__) # prints 'f'
print(f.__doc__) # prints 'does some math'
Your code will count the number of tabs and not the number of spaces. Also, the number of tabs will be one less than arr.length
.
DESCRIBE all_tab_columns
will show a TABLE_NAME VARCHAR2(30)
Note VARCHAR2(30) means a 30 byte limitation, not a 30 character limitation, and therefore may be different if your database is configured/setup to use a multibyte character set.
Mike
Why not just
$q->where("a = 1");
$q->andWhere("b = 1 OR b = 2");
$q->andWhere("c = 1 OR d = 2");
EDIT: You can also use the Expr class (Doctrine2).
It is a number, not a string. Numbers don't have a toLowerCase()
function because numbers do not have case in the first place.
To make the function run without error, run it on a string.
var ans = "334";
Of course, the output will be the same as the input since, as mentioned, numbers don't have case in the first place.
MAKE THIS YOUR config.js file code
CKEDITOR.editorConfig = function( config ) {
// config.enterMode = 2; //disabled <p> completely
config.enterMode = CKEDITOR.ENTER_BR; // pressing the ENTER KEY input <br/>
config.shiftEnterMode = CKEDITOR.ENTER_P; //pressing the SHIFT + ENTER KEYS input <p>
config.autoParagraph = false; // stops automatic insertion of <p> on focus
};
in case you'd need to drop everything at once: (drop all databases at once)
mongo --quiet --eval 'db.getMongo().getDBNames().forEach(function(i){db.getSiblingDB(i).dropDatabase()})'
The difference is that ActionEvent
is fired when the action is performed on the JCheckBox
that is its state is changed either by clicking on it with the mouse or with a space bar or a mnemonic. It does not really listen to change events whether the JCheckBox
is selected or deselected.
For instance, if JCheckBox c1
(say) is added to a ButtonGroup
. Changing the state of other JCheckBoxes
in the ButtonGroup
will not fire an ActionEvent
on other JCheckBox
, instead an ItemEvent
is fired.
Final words: An ItemEvent
is fired even when the user deselects a check box by selecting another JCheckBox
(when in a ButtonGroup
), however ActionEvent
is not generated like that instead ActionEvent
only listens whether an action is performed on the JCheckBox
(to which the ActionListener
is registered only) or not. It does not know about ButtonGroup
and all other selection/deselection stuff.
Turn off the JavaScript Validator in the "Builders" config for your project:
Then either restart your Eclipse or/and rename the .js to something like .js_ then back again.
This is possible with a bit of format conversion.
To extract the private key in a format openssh can use:
openssl pkcs12 -in pkcs12.pfx -nocerts -nodes | openssl rsa > id_rsa
To convert the private key to a public key:
openssl rsa -in id_rsa -pubout | ssh-keygen -f /dev/stdin -i -m PKCS8
To extract the public key in a format openssh can use:
openssl pkcs12 -in pkcs12.pfx -clcerts -nokeys | openssl x509 -pubkey -noout | ssh-keygen -f /dev/stdin -i -m PKCS8
Here's the config for ISAPI_Rewrite 3:
RewriteBase /
RewriteCond %{HTTP_HOST} ^mysite.org.uk$ [NC]
RewriteRule ^stuff/(.+)$ http://stuff.mysite.org.uk/$1 [NC,R=301,L]
You can use XML literals to sort of do this:
Dim s = <sql>
Create table article
(articleID int -- sql comment
,articleName varchar(50) <comment text="here's an xml comment" />
)
</sql>.Value
warning: XML text rules apply, like & for ampersand, < for <, etc.
Dim alertText = "Hello World"
Dim js = <script>
$(document).ready(function() {
alert('<%= alertText %>');
});
</script>.ToString 'instead of .Value includes <script> tag
note: the above is problematic when it includes characters that need to be escaped. Better to use "<script>"+js.Value+"</script>"
A one-liner is unlikely, but the strptime function can be used to parse your date format and the struct tm
argument can be queried for its tm_wday
member on systems that modify those fields automatically (e.g. some glibc implementations).
int get_weekday(char * str) {
struct tm tm;
memset((void *) &tm, 0, sizeof(tm));
if (strptime(str, "%d-%m-%Y", &tm) != NULL) {
time_t t = mktime(&tm);
if (t >= 0) {
return localtime(&t)->tm_wday; // Sunday=0, Monday=1, etc.
}
}
return -1;
}
Or you could encode these rules to do some arithmetic in a really long single line:
EDIT: note that this solution only works for dates after the UNIX epoch (1970-01-01T00:00:00Z).
to pass the event
object:
<p id="p" onclick="doSomething(event)">
to get the clicked child element
(should be used with event
parameter:
function doSomething(e) {
e = e || window.event;
var target = e.target || e.srcElement;
console.log(target);
}
to pass the element
itself (DOMElement):
<p id="p" onclick="doThing(this)">
see live example on jsFiddle.
You can specify the name of the event
as above, but alternatively your handler can access the event
parameter as described here: "When the event handler is specified as an HTML attribute, the specified code is wrapped into a function with the following parameters". There's much more additional documentation at the link.
For anyone who comes here, as I did, looking for the syntax to change origin to a different location you can find that documentation here: https://help.github.com/articles/changing-a-remote-s-url/. Using git remote add
to do this will result in "fatal: remote origin already exists."
Nutshell:
git remote set-url origin https://github.com/username/repo
(The marked answer is correct, I'm just hoping to help anyone as lost as I was... haha)
The following ways to fetch local JSON file-
ES6 version:
import customData from './customData.json';
or import customData from './customData';
If it's inside .js
file instead of .json
then import like -
import { customData } from './customData';
for more clarification/understanding refer example - Live working demo
This works. Just remove the button from the "dummy" div
if you want to keep the button.
function removeDummy() {_x000D_
var elem = document.getElementById('dummy');_x000D_
elem.parentNode.removeChild(elem);_x000D_
return false;_x000D_
}
_x000D_
#dummy {_x000D_
min-width: 200px;_x000D_
min-height: 200px;_x000D_
max-width: 200px;_x000D_
max-height: 200px;_x000D_
background-color: #fff000;_x000D_
}
_x000D_
<div id="dummy">_x000D_
<button onclick="removeDummy()">Remove</button>_x000D_
</div>
_x000D_
Try just setting the link color:
$("ul#mainFilter a").css('color','#000');
Edit: or better yet, use the CSS, as Christopher suggested
You must check if the same JAR is being imported again. In my case there was a class inside a jar which was getting imported in another jar. So just check if the any lib / class file is being included twice in the whole project!
You cannot change the default but there is a codeless workaround.
Select the whole sheet and change the font size on your data to something small, like 10 or 12. When you zoom in to view the data you will find that the drop down box entries are now visible.
To emphasize, the issue is not so much with the size of the font in the drop down, it is the relative size between drop down and data display font sizes.
I have a one-liner answer (this example gives you 999 lines of data and one header row per file)
cat bigFile.csv | parallel --header : --pipe -N999 'cat >file_{#}.csv'
Another similar method to those described above is to use plt.ylim
for example:
plt.ylim(max(y_array), min(y_array))
This method works for me when I'm attempting to compound multiple datasets on Y1 and/or Y2
On VS2017 I installed the NuGet package: Microsoft.AspNet.WebPages
That did the trick.
I had the same problem on a rackspeed server after changing the php version in the cpanel. Turned out it also changed the permissions of the folder... I set the permission of the folder to 755 with
chmod 755 folder_name
Also make sure your Workspace Settings aren't overriding your User Settings. The UI doesn't make it very obvious which settings you're editing and "File > Preferences > Settings" defaults to User Settings even though Workspace Settings trump User Settings.
You can also edit Workspace settings directly: /.vscode/settings.json
Entity Framework Core does not support multiple parallel operations being run on the same DbContext
instance. This includes both parallel execution of async
queries and any explicit concurrent use from multiple threads. Therefore, always await async
calls immediately, or use separate DbContext
instances for operations that execute in parallel.
I got this type question on Django, and My issue is forget to add static
to the <script>
tag.
Such as in my template:
<script type="text/javascript" src="css/layer.js"></script>
I should add the static
to it like this:
<script type="text/javascript" src="{% static 'css/layer.js' %}" ></script>
I know this is really late, but with C# 7.3 you can do this for unmanaged structs or anything else that's unmanged (int, bool etc...):
public static unsafe byte[] ConvertToBytes<T>(T value) where T : unmanaged {
byte* pointer = (byte*)&value;
byte[] bytes = new byte[sizeof(T)];
for (int i = 0; i < sizeof(T); i++) {
bytes[i] = pointer[i];
}
return bytes;
}
Then use like this:
struct MyStruct {
public int Value1;
public int Value2;
//.. blah blah blah
}
byte[] bytes = ConvertToBytes(new MyStruct());
First, run npm install expo-linear-gradient --save
You don't need to use an animated tag, but this is what I was using in my code.
inside colors={[ put your gradient colors ]}
then you can use something like this:
import { LinearGradient } from "expo-linear-gradient";
import { Animated } from "react-native";
<AnimatedLinearGradient
colors={["rgba(255,255,255, 0)", "rgba(255,255,255, 1)"]}
style={{ your styles go here }}/>
const AnimatedLinearGradient = Animated.createAnimatedComponent(LinearGradient);
You can use this snippet :-D
using System;
using System.Reflection;
public static class EnumUtils
{
public static T GetDefaultValue<T>()
where T : struct, Enum
{
return (T)GetDefaultValue(typeof(T));
}
public static object GetDefaultValue(Type enumType)
{
var attribute = enumType.GetCustomAttribute<DefaultValueAttribute>(inherit: false);
if (attribute != null)
return attribute.Value;
var innerType = enumType.GetEnumUnderlyingType();
var zero = Activator.CreateInstance(innerType);
if (enumType.IsEnumDefined(zero))
return zero;
var values = enumType.GetEnumValues();
return values.GetValue(0);
}
}
Example:
using System;
public enum Enum1
{
Foo,
Bar,
Baz,
Quux
}
public enum Enum2
{
Foo = 1,
Bar = 2,
Baz = 3,
Quux = 0
}
public enum Enum3
{
Foo = 1,
Bar = 2,
Baz = 3,
Quux = 4
}
[DefaultValue(Enum4.Bar)]
public enum Enum4
{
Foo = 1,
Bar = 2,
Baz = 3,
Quux = 4
}
public static class Program
{
public static void Main()
{
var defaultValue1 = EnumUtils.GetDefaultValue<Enum1>();
Console.WriteLine(defaultValue1); // Foo
var defaultValue2 = EnumUtils.GetDefaultValue<Enum2>();
Console.WriteLine(defaultValue2); // Quux
var defaultValue3 = EnumUtils.GetDefaultValue<Enum3>();
Console.WriteLine(defaultValue3); // Foo
var defaultValue4 = EnumUtils.GetDefaultValue<Enum4>();
Console.WriteLine(defaultValue4); // Bar
}
}
I finally got a proof-of-concept project to work, so I will share it here.
The layout is set up like this, where the light grey area is the VideoView
.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.videotest.MainActivity">
<VideoView
android:id="@+id/videoview"
android:layout_width="300dp"
android:layout_height="200dp"/>
<Button
android:text="Play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/videoview"
android:onClick="onButtonClick"
android:id="@+id/button"/>
</RelativeLayout>
According to the documentation, Android should support mp4 H.264 playback (decoding) for all API levels. However, there seem to be a lot of factors that affect whether an actual video will play or not. The most in depth answer I could find that told how to encode the videos is here. It uses the powerful ffmpeg
command line tool to do the conversion to something that should be playable on all (hopefully?) Android devices. Read the answer I linked to for more explanation. I used a slightly modified version because I was getting errors with the original version.
ffmpeg -y -i input_file.avi -s 432x320 -b:v 384k -vcodec libx264 -flags +loop+mv4 -cmp 256 -partitions +parti4x4+parti8x8+partp4x4+partp8x8 -subq 6 -trellis 0 -refs 5 -bf 0 -coder 0 -me_range 16 -g 250 -keyint_min 25 -sc_threshold 40 -i_qfactor 0.71 -qmin 10 -qmax 51 -qdiff 4 -c:a aac -ac 1 -ar 16000 -r 13 -ab 32000 -aspect 3:2 -strict -2 output_file.mp4
I would definitely read up a lot more on each of those parameters to see which need adjusting as far as video and audio quality go.
Next, rename output_file.mp4
to test.mp4
and put it in your Android project's /res/raw
folder. Create the folder if it doesn't exist already.
There is not much to the code. The video plays when the "Play" button is clicked. Thanks to this answer for help.
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onButtonClick(View v) {
VideoView videoview = (VideoView) findViewById(R.id.videoview);
Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.test);
videoview.setVideoURI(uri);
videoview.start();
}
}
That's all. You should be able play your video clip on the simulator or a real device now.
>>> lst = [1, 2, 3]
>>> print('\n'.join('{}: {}'.format(*k) for k in enumerate(lst)))
0: 1
1: 2
2: 3
Note: you just need to understand that list comprehension or iterating over a generator expression is explicit looping.
You can't update more that one table in a single statement, however the error message you get is because of the aliases, you could try this :
BEGIN TRANSACTION
update A
set A.ORG_NAME = @ORG_NAME
from table1 A inner join table2 B
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID
update B
set B.REF_NAME = @REF_NAME
from table2 B inner join table1 A
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID
COMMIT
You can use XMLGrid's Online viewer which provides a great XSD support and many other features:
Screenshot:
you can use the following common function.
<div>
<select class="form-control"
name="Extension for area validity sought for"
onchange="CommonShowHide('txtc1opt2', this, 'States')"
>
<option value="All India">All India</option>
<option value="States">States</option>
</select>
<input type="text"
id="txtc1opt2"
style="display:none;"
name="Extension for area validity sought for details"
class="form-control"
value=""
placeholder="">
</div>
<script>
function CommonShowHide(ElementId, element, value) {
document
.getElementById(ElementId)
.style
.display = element.value == value ? 'block' : 'none';
}
</script>
Have you tried setting the spacing to zero?
/*alternating row*/
table, tr, td, th {margin:0;border:0;padding:0;spacing:0;}
tr.rowhighlight {background-color:#f0f8ff;margin:0;border:0;padding:0;spacing:0;}
As Kris mentions, you can use the $resource
service to interact with the server, but I get the impression you are beginning your journey with Angular - I was there last week - so I recommend to start experimenting directly with the $http
service. In this case you can call its get
method.
If you have the following JSON
[{ "text":"learn angular", "done":true },
{ "text":"build an angular app", "done":false},
{ "text":"something", "done":false },
{ "text":"another todo", "done":true }]
You can load it like this
var App = angular.module('App', []);
App.controller('TodoCtrl', function($scope, $http) {
$http.get('todos.json')
.then(function(res){
$scope.todos = res.data;
});
});
The get
method returns a promise object which
first argument is a success callback and the second an error
callback.
When you add $http
as a parameter of a function Angular does it magic
and injects the $http
resource into your controller.
I've put some examples here
return None
or return
can be used to exit out of a function or program, both does the same thingquit()
function can be used, although use of this function is discouraged for making real world applications and should be used only in interpreter. import site
def func():
print("Hi")
quit()
print("Bye")
exit()
function can be used, similar to quit()
but the use is discouraged for making real world applications.import site
def func():
print("Hi")
exit()
print("Bye")
sys.exit([arg])
function can be used and need to import sys
module for that, this function can be used for real world applications unlike the other two functions.import sys
height = 150
if height < 165: # in cm
# exits the program
sys.exit("Height less than 165")
else:
print("You ride the rollercoaster.")
os._exit(n)
function can be used to exit from a process, and need to import os
module for that.I'm using SourceTree along with TortoiseMerge/Diff, which is very easy and convinient diff/merge tool.
If you'd like to use it as well, then:
Get standalone version of TortoiseMerge/Diff (quite old, since it doesn't ship standalone since version 1.6.7 of TortosieSVN, that is since July 2011). Links and details in this answer.
Unzip TortoiseIDiff.exe
and TortoiseMerge.exe
to any folder (c:\Program Files (x86)\Atlassian\SourceTree\extras\
in my case).
In SourceTree open Tools > Options > Diff > External Diff / Merge
. Select TortoiseMerge
in both dropdown lists.
Hit OK
and point SourceTree to your location of TortoiseIDiff.exe
and TortoiseMerge.exe
.
After that, you can select Resolve Conflicts > Launch External Merge Tool
from context menu on each conflicted file in your local repository. This will open up TortoiseMerge, where you can easily deal with all the conflicts, you have. Once finished, simply close TortoiseMerge (you don't even need to save changes, this will probably be done automatically) and after few seconds SourceTree should handle that gracefully.
The only problem is, that it automatically creates backup copy, even though proper option is unchecked.
Use following property same as table and its fully dynamic:
ul {_x000D_
width: 100%;_x000D_
display: table;_x000D_
table-layout: fixed; /* optional, for equal spacing */_x000D_
border-collapse: collapse;_x000D_
}_x000D_
li {_x000D_
display: table-cell;_x000D_
text-align: center;_x000D_
border: 1px solid pink;_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<ul>_x000D_
<li>foo<br>foo</li>_x000D_
<li>barbarbarbarbar</li>_x000D_
<li>baz klxjgkldjklg </li>_x000D_
<li>baz</li>_x000D_
<li>baz lds.jklklds</li>_x000D_
</ul>
_x000D_
May be its solve your issue.
For php there is also an option:
The code using NetworkInterface to wait for the network worked for me until I switched from fixed network address to DHCP. A slight enhancement makes it work also with DHCP:
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface interf = interfaces.nextElement();
if (interf.isUp() && !interf.isLoopback()) {
List<InterfaceAddress> adrs = interf.getInterfaceAddresses();
for (Iterator<InterfaceAddress> iter = adrs.iterator(); iter.hasNext();) {
InterfaceAddress adr = iter.next();
InetAddress inadr = adr.getAddress();
if (inadr instanceof Inet4Address) return true;
}
}
}
This works for Java 7 in openSuse 13.1 for IPv4 network. The problem with the original code is that although the interface was up after resuming from suspend, an IPv4 network address was not yet assigned. After waiting for this assignment, the program can connect to servers. But I have no idea what to do in case of IPv6.
Here's the cleaner and working version of the accepted answer using guzzle:
You can use curl instead of guzzle it's just a simple get request.
function ip_info($ip = NULL, $purpose = "location", $deep_detect = TRUE) {
$output = NULL;
if (filter_var($ip, FILTER_VALIDATE_IP) === FALSE) {
$ip = $_SERVER["REMOTE_ADDR"];
if ($deep_detect) {
if (filter_var(@$_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP))
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
if (filter_var(@$_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP))
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
}
$purpose = str_replace(array("name", "\n", "\t", " ", "-", "_"), NULL, strtolower(trim($purpose)));
$support = array("country", "countrycode", "state", "region", "city", "location", "address");
$continents = array(
"AF" => "Africa",
"AN" => "Antarctica",
"AS" => "Asia",
"EU" => "Europe",
"OC" => "Australia (Oceania)",
"NA" => "North America",
"SA" => "South America"
);
if (filter_var($ip, FILTER_VALIDATE_IP) && in_array($purpose, $support, true)) {
$client = New \GuzzleHttp\Client();
$ipdat = json_decode($client->request('GET','http://www.geoplugin.net/json.gp',$params = [
'query' => [
'ip' => $ip,
]
])->getBody()->getContents(),true);
if (strlen(trim($ipdat['geoplugin_countryCode'])) === 2) {
switch ($purpose) {
case "location":
$output = array(
"city" => $ipdat['geoplugin_city'],
"state" => $ipdat['geoplugin_regionName'],
"country" => $ipdat['geoplugin_countryName'],
"country_code" => $ipdat['geoplugin_countryCode'],
"continent" => $continents[strtoupper($ipdat['geoplugin_continentCode'])],
"continent_code" => $ipdat['geoplugin_continentCode']
);
break;
case "address":
$address = array($ipdat['geoplugin_countryName']);
if (@strlen($ipdat['geoplugin_regionName']) >= 1)
$address[] = $ipdat['geoplugin_regionName'];
if (@strlen($ipdat['geoplugin_city']) >= 1)
$address[] = $ipdat['geoplugin_city'];
$output = implode(", ", array_reverse($address));
break;
case "city":
$output = $ipdat['geoplugin_city'];
break;
case "region":
case "state":
$output = $ipdat['geoplugin_regionName'];
break;
case "country":
$output = $ipdat['geoplugin_countryName'];
break;
case "countrycode":
$output = $ipdat['geoplugin_countryCode'];
break;
}
}
}
return $output;
}
It appears that the correct answer varies in different JS engines. Here are the results I got from the test suite linked in ninjagecko's answer:
[].concat.apply
is fastest in Chrome 83 on Windows and Android, followed by reduce
(~56% slower);concat
is fastest in Safari 13 on Mac, followed by reduce
(~13% slower);reduce
is fastest in Safari 12 on iOS, followed by looped concat
(~40% slower);push
is fastest in Firefox 70 on Windows, followed by [].concat.apply
(~30% slower).I had both pywin32
and pipywin32
installed like suggested in previous answer, but I still did not have a folder ${PYTHON_HOME}\Lib\site-packages\win32
.
This always lead to errors when trying import win32api
.
The simple solution was to uninstall both packages and reinstall pywin32
:
pip uninstall pipywin32
pip uninstall pywin32
pip install pywin32
Then restart Python (and Jupyter).
Now, the win32
folder is there and the import works fine. Problem solved.
Use of the String.toString
:
Whenever you require to explore the constructor called value in the String
form, you can simply use String.toString
...
for an example...
package pack1;
import java.util.*;
class Bank {
String n;
String add;
int an;
int bal;
int dep;
public Bank(String n, String add, int an, int bal) {
this.add = add;
this.bal = bal;
this.an = an;
this.n = n;
}
public String toString() {
return "Name of the customer.:" + this.n + ",, "
+ "Address of the customer.:" + this.add + ",, " + "A/c no..:"
+ this.an + ",, " + "Balance in A/c..:" + this.bal;
}
}
public class Demo2 {
public static void main(String[] args) {
List<Bank> l = new LinkedList<Bank>();
Bank b1 = new Bank("naseem1", "Darbhanga,bihar", 123, 1000);
Bank b2 = new Bank("naseem2", "patna,bihar", 124, 1500);
Bank b3 = new Bank("naseem3", "madhubani,bihar", 125, 1600);
Bank b4 = new Bank("naseem4", "samastipur,bihar", 126, 1700);
Bank b5 = new Bank("naseem5", "muzafferpur,bihar", 127, 1800);
l.add(b1);
l.add(b2);
l.add(b3);
l.add(b4);
l.add(b5);
Iterator<Bank> i = l.iterator();
while (i.hasNext()) {
System.out.println(i.next());
}
}
}
... copy this program into your Eclipse, and run it... you will get the ideas about String.toString
...
select time, coalesce(count(case when activities = 3 then 1 end), 0) as count
from MyTable
group by time
Output:
| TIME | COUNT |
-----------------
| 13:00 | 2 |
| 13:15 | 2 |
| 13:30 | 0 |
| 13:45 | 1 |
If you want to count all the activities in one query, you can do:
select time,
coalesce(count(case when activities = 1 then 1 end), 0) as count1,
coalesce(count(case when activities = 2 then 1 end), 0) as count2,
coalesce(count(case when activities = 3 then 1 end), 0) as count3,
coalesce(count(case when activities = 4 then 1 end), 0) as count4,
coalesce(count(case when activities = 5 then 1 end), 0) as count5
from MyTable
group by time
The advantage of this over grouping by activities, is that it will return a count of 0 even if there are no activites of that type for that time segment.
Of course, this will not return rows for time segments with no activities of any type. If you need that, you'll need to use a left join with table that lists all the possible time segments.
In my case this was caused by not committing my conflict resolution.
The problem was caused by running the git pull
command. Changes in the origin led to conflicts with my local repo, which I resolved. However, I did not commit them. The solution at this point is to commit the changes (git commit
the resolved file)
If you have also modified some files since resolving the conflict, the git status
command will show the local modifications as unstaged local modifications and merge resolution as staged local modifications. This can be properly resolved by committing changes from the merge first by git commit
, then adding and committing the unstaged changes as usual (e.g. by git commit -a
).
111 means connection refused, which in turn means that your mysqld only listens to the localhost
interface.
To alter it you may want to look at the bind-address
value in the mysqld
section of your my.cnf
file.
Well the problem with the GET is that the user is able to change the value by himself if he has some knowledges. I wrote this so that PHP is able to retrive the timezone from Javascript:
// -- index.php
<?php
if (!isset($_COOKIE['timezone'])) {
?>
<html>
<script language="javascript">
var d = new Date();
var timezoneOffset = d.getTimezoneOffset() / 60;
// the cookie expired in 3 hours
d.setTime(d.getTime()+(3*60*60*1000));
var expires = "; expires="+d.toGMTString();
document.cookie = "timezone=" + timezoneOffset + expires + "; path=/";
document.location.href="index.php"
</script>
</html>
<?php
} else {
?>
<html>
<head>
<body>
<?php
if(isset($_COOKIE['timezone'])){
dump_var($_COOKIE['timezone']);
}
}
?>
Did you try assigning it back to the column?
df['column'] = df['column'].astype('str')
Referring to this question, the pandas dataframe stores the pointers to the strings and hence it is of type 'object'. As per the docs ,You could try:
df['column_new'] = df['column'].str.split(',')
If the above solutions don't work on ubuntu/linux then you can try this
sudo fuser -k -n tcp port
Run it several times to kill processes on your port of choosing. port could be 3000 for example. You would have killed all the processes if you see no output after running the command
Steve Ebersole & other members,
Would you kindly explain the reason for an id with a larger gap(by default 50)?
I am using Hibernate 4.2.15 and found the following code in org.hibernate.id.enhanced.OptimizerFactory cass.
if ( lo > maxLo ) {
lastSourceValue = callback.getNextValue();
lo = lastSourceValue.eq( 0 ) ? 1 : 0;
hi = lastSourceValue.copy().multiplyBy( maxLo+1 );
}
value = hi.copy().add( lo++ );
Whenever it hits the inside of the if statement, hi value is getting much larger. So, my id during the testing with the frequent server restart generates the following sequence ids:
1, 2, 3, 4, 19, 250, 251, 252, 400, 550, 750, 751, 752, 850, 1100, 1150.
I know you already said it didn't conflict with the spec, but I believe this will be very unexpected situation for most developers.
Anyone's input will be much helpful.
Jihwan
UPDATE:
ne1410s: Thanks for the edit.
cfrick: OK. I will do that. It was my first post here and wasn't sure how to use it.
Now, I understood better why maxLo was used for two purposes: Since the hibernate calls the DB sequence once, keep increase the id in Java level, and saves it to the DB, the Java level id value should consider how much was changed without calling the DB sequence when it calls the sequence next time.
For example, sequence id was 1 at a point and hibernate entered 5, 6, 7, 8, 9 (with allocationSize = 5). Next time, when we get the next sequence number, DB returns 2, but hibernate needs to use 10, 11, 12... So, that is why "hi = lastSourceValue.copy().multiplyBy( maxLo+1 )" is used to get a next id 10 from the 2 returned from the DB sequence. It seems only bothering thing was during the frequent server restart and this was my issue with the larger gap.
So, when we use the SEQUENCE ID, the inserted id in the table will not match with the SEQUENCE number in DB.
This doesn't sound intuitive but select the column you're having the issue with and use "text to column" and just press finish. This is the suggested answer from Excel help as well. For some reason in converts text to numbers.
I would use a listener. Fragment1 calling the listener (main activity)
Very good, clean and simple directive with shift + enter support:
app.directive('enterSubmit', function () {
return {
restrict: 'A',
link: function (scope, elem, attrs) {
elem.bind('keydown', function(event) {
var code = event.keyCode || event.which;
if (code === 13) {
if (!event.shiftKey) {
event.preventDefault();
scope.$apply(attrs.enterSubmit);
}
}
});
}
}
});
The problem is in your playerMovement
method. You are creating the string name of your room variables (ID1
, ID2
, ID3
):
letsago = "ID" + str(self.dirDesc.values())
However, what you create is just a str
. It is not the variable. Plus, I do not think it is doing what you think its doing:
>>>str({'a':1}.values())
'dict_values([1])'
If you REALLY needed to find the variable this way, you could use the eval
function:
>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'
or the globals
function:
class Foo(object):
def __init__(self):
super(Foo, self).__init__()
def test(self, name):
print(globals()[name])
foo = Foo()
bar = 'Hello World!'
foo.text('bar')
However, instead I would strongly recommend you rethink you class(es). Your userInterface
class is essentially a Room
. It shouldn't handle player movement. This should be within another class, maybe GameManager
or something like that.
Might be, more safe alternative to "_ORACLE_SCRIPT"=true
is to change "_common_user_prefix"
from C##
to an empty string. When it's null - any name can be used for common user. Found there.
During changing that value you may face another issue - ORA-02095 - parameter cannot be modified, that can be fixed in a several ways, based on your configuration (source).
So for me worked that:
alter system set _common_user_prefix = ''; scope=spfile;
Everyone has different defaults, and interestingly it will change after time. As an example, first I was on global, and then after 15 minutes it shows Ohio (which is us-east-2
).
The best approach is to check it during your work -- in console of your AWS working area, just set it on the right above side near your name on top bar check your region name and click on the down arrow to see your region.
In AWS CLI type aws configure
or aws2 configure
, give your access and secret id, then during default region, write your region and press Enter.
You will definitely get access to specific region set and it will work.
I was getting similar problem for other reason (url pattern test-response
not added in csrf token)
I resolved it by allowing my URL pattern in following property in config/local.properties
:
csrf.allowed.url.patterns = /[^/]+(/[^?])+(sop-response)$,/[^/]+(/[^?])+(merchant_callback)$,/[^/]+(/[^?])+(hop-response)$
modified to
csrf.allowed.url.patterns = /[^/]+(/[^?])+(sop-response)$,/[^/]+(/[^?])+(merchant_callback)$,/[^/]+(/[^?])+(hop-response)$,/[^/]+(/[^?])+(test-response)$
Just looking at the message it sounds like one or more of the components that you reference, or one or more of their dependencies is not registered properly.
If you know which component it is you can use regsvr32.exe to register it, just open a command prompt, go to the directory where the component is and type regsvr32 filename.dll
(assuming it's a dll), if it works, try to run the code again otherwise come back here with the error.
If you don't know which component it is, try re-installing/repairing the GIS software (I assume you've installed some GIS software that includes the component you're trying to use).
In general, ! is a perfectly good and readable boolean logic operator. No reason not to use it unless you're simplifying by removing double negatives or applying Morgan's law.
!(!A) = A
or
!(!A | !B) = A & B
As a rule of thumb, keep the signature of your boolean return methods mnemonic and in line with convention. The problem with the scenario that @hvgotcodes proposes is that of course a.b and c.d.e are not very friendly examples to begin with. Suppose you have a Flight and a Seat class for a flight booking application. Then the condition for booking a flight could perfectly be something like
if(flight.isActive() && !seat.isTaken())
{
//book the seat
}
This perfectly readable and understandable code. You could re-define your boolean logic for the Seat class and rephrase the condition to this, though.
if(flight.isActive() && seat.isVacant())
{
//book the seat
}
Thus removing the ! operator if it really bothers you, but you'll see that it all depends on what your boolean methods mean.
You can use the following:
float asd = (float) Convert.ToDouble("41.00027357629127");
Compilating answers here and there, here's a complete set of arr tools to get the work done:
Function getArraySize(arr As Variant)
' returns array size for a n dimention array
' usage result(k) = size of the k-th dimension
Dim ndims As Long
Dim arrsize() As Variant
ndims = getDimensions(arr)
ReDim arrsize(ndims - 1)
For i = 1 To ndims
arrsize(i - 1) = getDimSize(arr, i)
Next i
getArraySize = arrsize
End Function
Function getDimSize(arr As Variant, dimension As Integer)
' returns size for the given dimension number
getDimSize = UBound(arr, dimension) - LBound(arr, dimension) + 1
End Function
Function getDimensions(arr As Variant) As Long
' returns number of dimension in an array (ex. sheet range = 2 dimensions)
On Error GoTo Err
Dim i As Long
Dim tmp As Long
i = 0
Do While True
i = i + 1
tmp = UBound(arr, i)
Loop
Err:
getDimensions = i - 1
End Function
If you're doing shell commands and you (like I) have a fetish for pipelining, this one is good:
seq 1 $END | xargs -I {} echo {}
Use the synaptic packet manager in order to install yacc / lex. If you are feeling more comfortable doing this on the console just do:
sudo apt-get install bison flex
There are some very nice articles on the net on how to get started with those tools. I found the article from CodeProject to be quite good and helpful (see here). But you should just try and search for "introduction to lex", there are plenty of good articles showing up.
its pretty simple
Date someDate = new DateTime();
string timeOfDay = someDate.ToString("hh:mm tt");
// hh - shows hour and mm - shows minute - tt - shows AM or PM
what's wrong with:
int myInt = myFloat;
bear in mind this'll use the default rounding rule, which is towards zero (i.e. -3.9f becomes -3)
Regarding Bruce Adams answer:
Your answer creates dangerous confusion. DESTDIR is intended for installs out of the root tree. It allows one to see what would be installed in the root tree if one did not specify DESTDIR. PREFIX is the base directory upon which the real installation is based.
For example, PREFIX=/usr/local indicates that the final destination of a package is /usr/local. Using DESTDIR=$HOME will install the files as if $HOME was the root (/). If, say DESTDIR, was /tmp/destdir, one could see what 'make install' would affect. In that spirit, DESTDIR should never affect the built objects.
A makefile segment to explain it:
install:
cp program $DESTDIR$PREFIX/bin/program
Programs must assume that PREFIX is the base directory of the final (i.e. production) directory. The possibility of symlinking a program installed in DESTDIR=/something only means that the program does not access files based upon PREFIX as it would simply not work. cat(1) is a program that (in its simplest form) can run from anywhere. Here is an example that won't:
prog.pseudo.in:
open("@prefix@/share/prog.db")
...
prog:
sed -e "s/@prefix@/$PREFIX/" prog.pseudo.in > prog.pseudo
compile prog.pseudo
install:
cp prog $DESTDIR$PREFIX/bin/prog
cp prog.db $DESTDIR$PREFIX/share/prog.db
If you tried to run prog from elsewhere than $PREFIX/bin/prog, prog.db would never be found as it is not in its expected location.
Finally, /etc/alternatives really does not work this way. There are symlinks to programs installed in the root tree (e.g. vi -> /usr/bin/nvi, vi -> /usr/bin/vim, etc.).
Python dictionary has get(key) function
>>> d.get(key)
For Example,
>>> d = {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four'}
>>> d.get('3')
'three'
>>> d.get('10')
None
If your key does'nt exist, will return None
value.
foo = d[key] # raise error if key doesn't exist
foo = d.get(key) # return None if key doesn't exist
Content relevant to versions less than 3.0 and greater than 5.0.
.You can write a function that manually delegates between the other functions:
module.exports = function(arg) {
if(arg instanceof String) {
return doStringThing.apply(this, arguments);
}else{
return doObjectThing.apply(this, arguments);
}
};
if min=10
and max=100
:
(int)(Math.random() * max) + min
gives a result between 10 and 110, while
(int)(Math.random() * (max - min) + min)
gives a result between 10 and 100, so they are very different formulas. What's important here is clarity, so whatever you do, make sure the code makes it clear what is being generated.
(PS. the first makes more sense if you change the variable 'max' to be called 'range')
I think the better way to go is to put switch to named functions (Check this overflow for more on that subject). That way you can call them from a single event.
Like so:
function firstFunction() {
console.log("first");
}
function secondFunction() {
console.log("second");
}
function thirdFunction() {
console.log("third");
}
That way you can load them in a single ready function.
jQuery(document).on('ready', function(){
firstFunction();
secondFunction();
thirdFunction();
});
This will output the following to your console.log:
first
second
third
This way you can reuse the functions for other events.
jQuery(window).on('resize',function(){
secondFunction();
});
Adding position: relative
to the parent, and a max-height:100%
; on div2 works.
<body>_x000D_
<div id="div1" style="height: 500px;position:relative;">_x000D_
<div id="div2" style="max-height:100%;overflow:auto;border:1px solid red;">_x000D_
<div id="div3" style="height:1500px;border:5px solid yellow;">hello</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</body>?
_x000D_
Update: The following shows the "updated" example and answer. http://jsfiddle.net/Wcgvt/181/
The secret there is to use box-sizing: border-box
, and some padding to make the second div height 100%, but move it's content down 50px. Then wrap the content in a div with overflow: auto
to contain the scrollbar. Pay attention to z-indexes to keep all the text selectable - hope this helps, several years later.
Building on @general03's answer, you can use Android's built-in style to customize the dialog quickly. You can find the dialog themes under android.R.style.Theme_DeviceDefault_Dialogxxx
.
For example:
builder = new AlertDialog.Builder(this, android.R.style.Theme_DeviceDefault_Dialog_MinWidth);
builder = new AlertDialog.Builder(this, android.R.style.Theme_DeviceDefault_Dialog_NoActionBar);
builder = new AlertDialog.Builder(this, android.R.style.Theme_DeviceDefault_DialogWhenLarge);
tl;dr
"Foo" and "bar" as metasyntactic variables were popularised by MIT and DEC, the first references are in work on LISP and PDP-1 and Project MAC from 1964 onwards.
Many of these people were in MIT's Tech Model Railroad Club, where we find the first documented use of "foo" in tech circles in 1959 (and a variant in 1958).
Both "foo" and "bar" (and even "baz") were well known in popular culture, especially from Smokey Stover and Pogo comics, which will have been read by many TMRC members.
Also, it seems likely the military FUBAR contributed to their popularity.
The use of lone "foo" as a nonsense word is pretty well documented in popular culture in the early 20th century, as is the military FUBAR. (Some background reading: FOLDOC FOLDOC Jargon File Jargon File Wikipedia RFC3092)
OK, so let's find some references.
STOP PRESS! After posting this answer, I discovered this perfect article about "foo" in the Friday 14th January 1938 edition of The Tech ("MIT's oldest and largest newspaper & the first newspaper published on the web"), Volume LVII. No. 57, Price Three Cents:
On Foo-ism
The Lounger thinks that this business of Foo-ism has been carried too far by its misguided proponents, and does hereby and forthwith take his stand against its abuse. It may be that there's no foo like an old foo, and we're it, but anyway, a foo and his money are some party. (Voice from the bleachers- "Don't be foo-lish!")
As an expletive, of course, "foo!" has a definite and probably irreplaceable position in our language, although we fear that the excessive use to which it is currently subjected may well result in its falling into an early (and, alas, a dark) oblivion. We say alas because proper use of the word may result in such happy incidents as the following.
It was an 8.50 Thermodynamics lecture by Professor Slater in Room 6-120. The professor, having covered the front side of the blackboard, set the handle that operates the lift mechanism, turning meanwhile to the class to continue his discussion. The front board slowly, majestically, lifted itself, revealing the board behind it, and on that board, writ large, the symbols that spelled "FOO"!
The Tech newspaper, a year earlier, the Letter to the Editor, September 1937:
By the time the train has reached the station the neophytes are so filled with the stories of the glory of Phi Omicron Omicron, usually referred to as Foo, that they are easy prey.
...
It is not that I mind having lost my first four sons to the Grand and Universal Brotherhood of Phi Omicron Omicron, but I do wish that my fifth son, my baby, should at least be warned in advance.
Hopefully yours,
Indignant Mother of Five.
And The Tech in December 1938:
General trend of thought might be best interpreted from the remarks made at the end of the ballots. One vote said, '"I don't think what I do is any of Pulver's business," while another merely added a curt "Foo."
The first documented "foo" in tech circles is probably 1959's Dictionary of the TMRC Language:
FOO: the sacred syllable (FOO MANI PADME HUM); to be spoken only when under inspiration to commune with the Deity. Our first obligation is to keep the Foo Counters turning.
These are explained at FOLDOC. The dictionary's compiler Pete Samson said in 2005:
Use of this word at TMRC antedates my coming there. A foo counter could simply have randomly flashing lights, or could be a real counter with an obscure input.
And from 1996's Jargon File 4.0.0:
Earlier versions of this lexicon derived 'baz' as a Stanford corruption of bar. However, Pete Samson (compiler of the TMRC lexicon) reports it was already current when he joined TMRC in 1958. He says "It came from "Pogo". Albert the Alligator, when vexed or outraged, would shout 'Bazz Fazz!' or 'Rowrbazzle!' The club layout was said to model the (mythical) New England counties of Rowrfolk and Bassex (Rowrbazzle mingled with (Norfolk/Suffolk/Middlesex/Essex)."
A year before the TMRC dictionary, 1958's MIT Voo Doo Gazette ("Humor suplement of the MIT Deans' office") (PDF) mentions Foocom, in "The Laws of Murphy and Finagle" by John Banzhaf (an electrical engineering student):
Further research under a joint Foocom and Anarcom grant expanded the law to be all embracing and universally applicable: If anything can go wrong, it will!
Also 1964's MIT Voo Doo (PDF) references the TMRC usage:
Yes! I want to be an instant success and snow customers. Send me a degree in: ...
Foo Counters
Foo Jung
Let's find "foo", "bar" and "foobar" published in code examples.
So, Jargon File 4.4.7 says of "foobar":
Probably originally propagated through DECsystem manuals by Digital Equipment Corporation (DEC) in 1960s and early 1970s; confirmed sightings there go back to 1972.
The first published reference I can find is from February 1964, but written in June 1963, The Programming Language LISP: its Operation and Applications by Information International, Inc., with many authors, but including Timothy P. Hart and Michael Levin:
Thus, since "FOO" is a name for itself, "COMITRIN" will treat both "FOO" and "(FOO)" in exactly the same way.
Also includes other metasyntactic variables such as: FOO CROCK GLITCH / POOT TOOR / ON YOU / SNAP CRACKLE POP / X Y Z
I expect this is much the same as this next reference of "foo" from MIT's Project MAC in January 1964's AIM-064, or LISP Exercises by Timothy P. Hart and Michael Levin:
car[((FOO . CROCK) . GLITCH)]
It shares many other metasyntactic variables like: CHI / BOSTON NEW YORK / SPINACH BUTTER STEAK / FOO CROCK GLITCH / POOT TOOP / TOOT TOOT / ISTHISATRIVIALEXCERCISE / PLOOP FLOT TOP / SNAP CRACKLE POP / ONE TWO THREE / PLANE SUB THRESHER
For both "foo" and "bar" together, the earliest reference I could find is from MIT's Project MAC in June 1966's AIM-098, or PDP-6 LISP by none other than Peter Samson:
EXPLODE, like PRIN1, inserts slashes, so (EXPLODE (QUOTE FOO/ BAR)) PRIN1's as (F O O // / B A R) or PRINC's as (F O O / B A R).
Some more recallations.
@Walter Mitty recalled on this site in 2008:
I second the jargon file regarding Foo Bar. I can trace it back at least to 1963, and PDP-1 serial number 2, which was on the second floor of Building 26 at MIT. Foo and Foo Bar were used there, and after 1964 at the PDP-6 room at project MAC.
John V. Everett recalls in 1996:
When I joined DEC in 1966, foobar was already being commonly used as a throw-away file name. I believe fubar became foobar because the PDP-6 supported six character names, although I always assumed the term migrated to DEC from MIT. There were many MIT types at DEC in those days, some of whom had worked with the 7090/7094 CTSS. Since the 709x was also a 36 bit machine, foobar may have been used as a common file name there.
Foo and bar were also commonly used as file extensions. Since the text editors of the day operated on an input file and produced an output file, it was common to edit from a .foo file to a .bar file, and back again.
It was also common to use foo to fill a buffer when editing with TECO. The text string to exactly fill one disk block was IFOO$HXA127GA$$. Almost all of the PDP-6/10 programmers I worked with used this same command string.
Daniel P. B. Smith in 1998:
Dick Gruen had a device in his dorm room, the usual assemblage of B-battery, resistors, capacitors, and NE-2 neon tubes, which he called a "foo counter." This would have been circa 1964 or so.
Robert Schuldenfrei in 1996:
The use of FOO and BAR as example variable names goes back at least to 1964 and the IBM 7070. This too may be older, but that is where I first saw it. This was in Assembler. What would be the FORTRAN integer equivalent? IFOO and IBAR?
Paul M. Wexelblat in 1992:
The earliest PDP-1 Assembler used two characters for symbols (18 bit machine) programmers always left a few words as patch space to fix problems. (Jump to patch space, do new code, jump back) That space conventionally was named FU: which stood for Fxxx Up, the place where you fixed Fxxx Ups. When spoken, it was known as FU space. Later Assemblers ( e.g. MIDAS allowed three char tags so FU became FOO, and as ALL PDP-1 programmers will tell you that was FOO space.
Bruce B. Reynolds in 1996:
On the IBM side of FOO(FU)BAR is the use of the BAR side as Base Address Register; in the middle 1970's CICS programmers had to worry out the various xxxBARs...I think one of those was FRACTBAR...
Here's a straight IBM "BAR" from 1955.
Other early references:
1973 foo bar International Joint Council on Artificial Intelligence
1975 foo bar International Joint Council on Artificial Intelligence
I haven't been able to find any references to foo bar as "inverted foo signal" as suggested in RFC3092 and elsewhere.
Here are a some of even earlier F00s but I think they're coincidences/false positives:
Everything in S3 is an object. To you, it may be files and folders. But to S3, they're just objects.
Objects that end with the delimiter (/
in most cases) are usually perceived as a folder, but it's not always the case. It depends on the application. Again, in your case, you're interpretting it as a folder. S3 is not. It's just another object.
In your case above, the object users/<user-id>/contacts/<contact-id>/
exists in S3 as a distinct object, but the object users/<user-id>/
does not. That's the difference in your responses. Why they're like that, we cannot tell you, but someone made the object in one case, and didn't in the other. You don't see it in the AWS Management Console because the console is interpreting it as a folder and hiding it from you.
Since S3 just sees these things as objects, it won't "exclude" certain things for you. It's up to the client to deal with the objects as they should be dealt with.
Your Solution
Since you're the one that doesn't want the folder objects, you can exclude it yourself by checking the last character for a /
. If it is, then ignore the object from the response.
Adding where to find UPDATE CURRENT_TIMESTAMP
because for new people this is a confusion.
Most people will use phpmyadmin or something like it.
Default value you select CURRENT_TIMESTAMP
Attributes (a different drop down) you select UPDATE CURRENT_TIMESTAMP
Answered my own question:
IPv6 addresses are normally written as eight groups of four hexadecimal digits, where each group is separated by a colon (:).
So that's 39 characters max.
Not in C# unfortunately, as you'd need an exception filter to do it and C# doesn't expose that feature of MSIL. VB.NET does have this capability though, e.g.
Catch ex As Exception When TypeOf ex Is FormatException OrElse TypeOf ex Is OverflowException
What you could do is use an anonymous function to encapsulate your on-error code, and then call it in those specific catch blocks:
Action onError = () => WebId = Guid.Empty;
try
{
// something
}
catch (FormatException)
{
onError();
}
catch (OverflowException)
{
onError();
}
My solutions in one of my own sites, with a table:
$.getJSON("sections/view_numbers_update.php", function(data) {
$.each(data, function(index, objNumber) {
$('#tr_' + objNumber.intID).find("td").eq(3).html(objNumber.datLastCalled);
$('#tr_' + objNumber.intID).find("td").eq(4).html(objNumber.strStatus);
$('#tr_' + objNumber.intID).find("td").eq(5).html(objNumber.intDuration);
$('#tr_' + objNumber.intID).find("td").eq(6).html(objNumber.blnWasHuman);
});
});
sections/view_numbers_update.php Returns something like:
[{"intID":"19","datLastCalled":"Thu, 10 Jan 13 08:52:20 +0000","strStatus":"Completed","intDuration":"0:04 secs","blnWasHuman":"Yes","datModified":1357807940},
{"intID":"22","datLastCalled":"Thu, 10 Jan 13 08:54:43 +0000","strStatus":"Completed","intDuration":"0:00 secs","blnWasHuman":"Yes","datModified":1357808079}]
HTML table:
<table id="table_numbers">
<tr>
<th>[...]</th>
<th>[...]</th>
<th>[...]</th>
<th>Last Call</th>
<th>Status</th>
<th>Duration</th>
<th>Human?</th>
<th>[...]</th>
</tr>
<tr id="tr_123456">
[...]
</tr>
</table>
This essentially gives every row a unique id preceding with 'tr_' to allow for other numbered element ids, at server script time. The jQuery script then just gets this TR_[id] element, and fills the correct indexed cell with the json return.
The advantage is you could get the complete array from the DB, and either foreach($array as $record) to create the table html, OR (if there is an update request) you can die(json_encode($array)) before displaying the table, all in the same page, but same display code.
I was also trying to run Spring Boot application in Eclipse, without any plugins.
Step 1
Right click on your project. Select "Run As" -> "Maven build...". Then in "Goals" field, enter "spring-boot:run". Apply & Run.
After this you do not have to Run again.
Step 2
After making any change, clean your project. After cleaning, it automatically builds the project once. Then when you will refresh your pages on browser, change will be reflected.
You can just type
window.jQuery
in Console . If it return a function(e,n) ... Then it is confirmed that the jquery is loaded and working successfully.
I know this may seem obvious but I also had to use a single quote around the u/n and p/w before it worked
mongo admin -u 'user' -p 'password'
I have quickly made a function that can achieve this, it may not be the best way to do this but it simply works and should be cross browser, please also know that i am NOT a expert in JavaScript so any tips are great :)
function createElement(){
var element = document.createElement(arguments[0]),
text = arguments[1],
attr = arguments[2],
append = arguments[3],
appendTo = arguments[4];
for(var key = 0; key < Object.keys(attr).length ; key++){
var name = Object.keys(attr)[key],
value = attr[name],
tempAttr = document.createAttribute(name);
tempAttr.value = value;
element.setAttributeNode(tempAttr)
}
if(append){
for(var _key = 0; _key < append.length; _key++) {
element.appendChild(append[_key]);
}
}
if(text) element.appendChild(document.createTextNode(text));
if(appendTo){
var target = appendTo === 'body' ? document.body : document.getElementById(appendTo);
target.appendChild(element)
}
return element;
}
lets see how we make this
<select name="drop1" id="Select1">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
here's how it works
var options = [
createElement('option', 'Volvo', {value: 'volvo'}),
createElement('option', 'Saab', {value: 'saab'}),
createElement('option', 'Mercedes', {value: 'mercedes'}),
createElement('option', 'Audi', {value: 'audi'})
];
createElement('select', null, // 'select' = name of element to create, null = no text to insert
{id: 'Select1', name: 'drop1'}, // Attributes to attach
[options[0], options[1], options[2], options[3]], // append all 4 elements
'body' // append final element to body - this also takes a element by id without the #
);
this is the params
createElement('tagName', 'Text to Insert', {any: 'attribute', here: 'like', id: 'mainContainer'}, [elements, to, append, to, this, element], 'body || container = where to append this element');
This function would suit if you have to append many element, if there is any way to improve this answer please let me know.
edit:
Here is a working demo
This can be highly customized to suit your project!
I don't think you'll ever get a definitive solution for this, the operating system isn't necessarily going to tell you if the file is open or not.
You might get some mileage out of java.nio.channels.FileLock
, although the javadoc is loaded with caveats.
Python: You will need to add # - * - coding: UTF-8 - * - (remove the spaces around * ) to the first line of the python file. and then add the following to the text to encode: .encode('ascii', 'xmlcharrefreplace'). This will replace all the unicode characters with it's ASCII equivalent.
Good article here https://github.com/vasanthk/react-bits/blob/master/patterns/27.passing-function-to-setState.md
// assuming this.state.count === 0
this.setState({count: this.state.count + 1});
this.setState({count: this.state.count + 1});
this.setState({count: this.state.count + 1});
// this.state.count === 1, not 3
Solution
this.setState((prevState, props) => ({
count: prevState.count + props.increment
}));
or pass callback this.setState ({.....},callback)
https://medium.com/javascript-scene/setstate-gate-abc10a9b2d82 https://medium.freecodecamp.org/functional-setstate-is-the-future-of-react-374f30401b6b
==
and !=
do not take into account the data type of the variables you compare. So these would all return true:
'0' == 0
false == 0
NULL == false
===
and !==
do take into account the data type. That means comparing a string to a boolean will never be true because they're of different types for example. These will all return false:
'0' === 0
false === 0
NULL === false
You should compare data types for functions that return values that could possibly be of ambiguous truthy/falsy value. A well-known example is strpos()
:
// This returns 0 because F exists as the first character, but as my above example,
// 0 could mean false, so using == or != would return an incorrect result
var_dump(strpos('Foo', 'F') != false); // bool(false)
var_dump(strpos('Foo', 'F') !== false); // bool(true), it exists so false isn't returned
I have another approach for Intellij users, and it is working very fine for me:
I got this error when my server ran out of disk space and closed the connection midway during generating the response and simply closed the connection
I agree with Luke Vo's solution. I thought it would better to omit justify-content: space-between;
from layout-wrapper and add margin-top: auto;
to footer.
You wouldn't want your body to be hanging in the middle and only have footer pushed to the bottom.
This approach addresses any content extending beyond the viewport.
internal
members are visible to all code in the assembly they are declared in.
(And to other assemblies referenced using the [InternalsVisibleTo]
attribute)
private
members are visible only to the declaring class. (including nested classes)
An outer (non-nested) class cannot be declared private
, as there is no containing scope to make it private to.
To answer the question you forgot to ask, protected
members are like private
members, but are also visible in all classes that inherit the declaring type. (But only on an expression of at least the type of the current class)
Two arrays can be easily added or union without chaning their original indexing by + operator. This will be very help full in laravel and codeigniter select dropdown.
$empty_option = array(
''=>'Select Option'
);
$option_list = array(
1=>'Red',
2=>'White',
3=>'Green',
);
$arr_option = $empty_option + $option_list;
Output will be :
$arr_option = array(
''=>'Select Option'
1=>'Red',
2=>'White',
3=>'Green',
);
Definitely a view is better than a nested query for SQL Server. Without knowing exactly why it is better (until I read Mark Brittingham's post), I had run some tests and experienced almost shocking performance improvements when using a view versus a nested query. After running each version of the query several hundred times in a row, the view version of the query completed in half the time. I'd say that's proof enough for me.
You need to add a dot, which means to use the Dockerfile in the local directory.
For example:
docker build -t mytag .
It means you use the Dockerfile in the local directory, and if you use docker 1.5 you can specify a Dockerfile elsewhere. Extract from the help output from docker build:
-f, --file="" Name of the Dockerfile(Default is 'Dockerfile' at context root)
<script type="text/javascript"
src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
// You may specify partial version numbers, such as "1" or "1.3",
// with the same result. Doing so will automatically load the
// latest version matching that partial revision pattern
// (e.g. 1.3 would load 1.3.2 today and 1 would load 1.7.2).
google.load("jquery", "1.7.2");
google.setOnLoadCallback(function() {
// Place init code here instead of $(document).ready()
});
</script>
But even he admits that it just doesn't compare to doing the following when it comes to optimal performance:
<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript"> window.jQuery || document.write('<script src="js/libs/jquery-1.7.2.min.js">\x3C/script>')</script>
<script type="text/javascript" src="scripts.js"></scripts>
</body>
</html>
Just for completeness and those unaware XSL 1 has choose for multiple conditions.
<xsl:choose>
<xsl:when test="expression">
... some output ...
</xsl:when>
<xsl:when test="another-expression">
... some output ...
</xsl:when>
<xsl:otherwise>
... some output ....
</xsl:otherwise>
</xsl:choose>
Click Here for full description and source code
public void saveImage(Context mContext, Bitmap bitmapImage) {
File sampleDir = new File(Environment.getExternalStorageDirectory() + "/" + "ApplicationName");
TextView tvImageLocation = (TextView) findViewById(R.id.tvImageLocation);
tvImageLocation.setText("Image Store At : " + sampleDir);
if (!sampleDir.exists()) {
createpathForImage(mContext, bitmapImage, sampleDir);
} else {
createpathForImage(mContext, bitmapImage, sampleDir);
}
}
People from other scripting languages always think theirs is better because they have a built-in function to do that and not PHP (I am looking at Pythonistas right now :-)).
In fact, it does exist, but few people know it. Meet pathinfo()
:
$ext = pathinfo($filename, PATHINFO_EXTENSION);
This is fast and built-in. pathinfo()
can give you other information, such as canonical path, depending on the constant you pass to it.
Remember that if you want to be able to deal with non ASCII characters, you need to set the locale first. E.G:
setlocale(LC_ALL,'en_US.UTF-8');
Also, note this doesn't take into consideration the file content or mime-type, you only get the extension. But it's what you asked for.
Lastly, note that this works only for a file path, not a URL resources path, which is covered using PARSE_URL.
Enjoy
Just about any error will throw an exceptions. The only errors I can think of that wouldn't work with the "pause on exceptions" option are syntax errors, which happen before any of the code gets executed, so there's no place to pause anyway and none of the code will run.
Apparently, Chrome won't pause on the exception if it's inside a try-catch block though. It only pauses on uncaught exceptions. I don't know of any way to change it.
If you just need to know what line the exception happened on (then you could set a breakpoint if the exception is reproducible), the Error
object given to the catch block has a stack
property that shows where the exception happened.
Starting from CSS Selectors 4 using multiple arguments in the :not
selector becomes possible (see here).
In CSS3, the :not selector only allows 1 selector as an argument. In level 4 selectors, it can take a selector list as an argument.
Example:
/* In this example, all p elements will be red, except for
the first child and the ones with the class special. */
p:not(:first-child, .special) {
color: red;
}
Unfortunately, browser support is limited. For now, it only works in Safari.
You have a PivotTables collection on a the VB Worksheet object. So, a quick loop like this will work:
Sub RefreshPivotTables()
Dim pivotTable As PivotTable
For Each pivotTable In ActiveSheet.PivotTables
pivotTable.RefreshTable
Next
End Sub
Notes from the trenches:
Good luck!
Robert Rossney has a good solution. Here's an alternative solution I've used in the past that separates out the "Overlay" from the rest of the content. This solution takes advantage of the attached property Panel.ZIndex
to place the "Overlay" on top of everything else. You can either set the Visibility of the "Overlay" in code or use a DataTrigger
.
<Grid x:Name="LayoutRoot">
<Grid x:Name="Overlay" Panel.ZIndex="1000" Visibility="Collapsed">
<Grid.Background>
<SolidColorBrush Color="Black" Opacity=".5"/>
</Grid.Background>
<!-- Add controls as needed -->
</Grid>
<!-- Use whatever layout you need -->
<ContentControl x:Name="MainContent" />
</Grid>
Apart from answering OP's queries, Let me throw some insights on Apache Solr from simple introduction to detailed installation and implementation.
Simple Introduction
Anyone who has had experience with the search engines above, or other engines not in the list -- I would love to hear your opinions.
Solr shouldn't be used to solve real-time problems. For search engines, Solr is pretty much game and works flawlessly.
Solr works fine on High Traffic web-applications (I read somewhere that it is not suited for this, but I am backing up that statement). It utilizes the RAM, not the CPU.
- result relevance and ranking
The boost helps you rank your results show up on top. Say, you're trying to search for a name john in the fields firstname and lastname, and you want to give relevancy to the firstname field, then you need to boost up the firstname field as shown.
http://localhost:8983/solr/collection1/select?q=firstname:john^2&lastname:john
As you can see, firstname field is boosted up with a score of 2.
More on SolrRelevancy
- searching and indexing speed
The speed is unbelievably fast and no compromise on that. The reason I moved to Solr.
Regarding the indexing speed, Solr can also handle JOINS from your database tables. A higher and complex JOIN do affect the indexing speed. However, an enormous RAM config can easily tackle this situation.
The higher the RAM, The faster the indexing speed of Solr is.
- ease of use and ease of integration with Django
Never attempted to integrate Solr and Django, however you can achieve to do that with Haystack. I found some interesting article on the same and here's the github for it.
- resource requirements - site will be hosted on a VPS, so ideally the search engine wouldn't require a lot of RAM and CPU
Solr breeds on RAM, so if the RAM is high, you don't to have to worry about Solr.
Solr's RAM usage shoots up on full-indexing if you have some billion records, you could smartly make use of Delta imports to tackle this situation. As explained, Solr is only a near real-time solution.
- scalability
Solr is highly scalable. Have a look on SolrCloud. Some key features of it.
- extra features such as "did you mean?", related searches, etc
For the above scenario, you could use the SpellCheckComponent that is packed up with Solr. There are a lot other features, The SnowballPorterFilterFactory helps to retrieve records say if you typed, books instead of book, you will be presented with results related to book.
This answer broadly focuses on Apache Solr & MySQL. Django is out of scope.
Assuming that you are under LINUX environment, you could proceed to this article further. (mine was an Ubuntu 14.04 version)
Detailed Installation
Download Apache Solr from here. That would be version is 4.8.1. You could download new versions, I found this stable.
After downloading the archive , extract it to a folder of your choice.
Say .. Downloads
or whatever.. So it will look like Downloads/solr-4.8.1/
On your prompt.. Navigate inside the directory
shankar@shankar-lenovo: cd Downloads/solr-4.8.1
So now you are here ..
shankar@shankar-lenovo: ~/Downloads/solr-4.8.1$
Jetty is available inside the examples folder of the solr-4.8.1
directory , so navigate inside that and start the Jetty Application Server.
shankar@shankar-lenovo:~/Downloads/solr-4.8.1/example$ java -jar start.jar
Now , do not close the terminal , minimize it and let it stay aside.
( TIP : Use & after start.jar to make the Jetty Server run in the background )
To check if Apache Solr runs successfully, visit this URL on the browser. http://localhost:8983/solr
It runs on the port 8983 as default. You could change the port either here or directly inside the jetty.xml
file.
java -Djetty.port=9091 -jar start.jar
This JAR file acts as a bridge between MySQL and JDBC , Download the Platform Independent Version here
After downloading it, extract the folder and copy themysql-connector-java-5.1.31-bin.jar
and paste it to the lib directory.
shankar@shankar-lenovo:~/Downloads/solr-4.8.1/contrib/dataimporthandler/lib
To put Solr to use, You need to have some tables and data to search for. For that, we will use MySQL for creating a table and pushing some random names and then we could use Solr to connect to MySQL and index that table and it's entries.
CREATE TABLE test_solr_mysql
(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(45) NULL,
created TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
);
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Jean');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Jack');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Jason');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Vego');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Grunt');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Jasper');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Fred');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Jenna');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Rebecca');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Roland');
shankar@shankar-lenovo: ~/Downloads/solr-4.8.1/example/solr/collection1/conf
Add these two directives to this file..
<lib dir="../../../contrib/dataimporthandler/lib/" regex=".*\.jar" />
<lib dir="../../../dist/" regex="solr-dataimporthandler-\d.*\.jar" />
Now add the DIH (Data Import Handler)
<requestHandler name="/dataimport"
class="org.apache.solr.handler.dataimport.DataImportHandler" >
<lst name="defaults">
<str name="config">db-data-config.xml</str>
</lst>
</requestHandler>
If the file exists then ignore, add these lines to that file. As you can see the first line, you need to provide the credentials of your MySQL database. The Database name, username and password.
<dataConfig>
<dataSource type="JdbcDataSource" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost/yourdbname" user="dbuser" password="dbpass"/>
<document>
<entity name="test_solr" query="select CONCAT('test_solr-',id) as rid,name from test_solr_mysql WHERE '${dataimporter.request.clean}' != 'false'
OR `created` > '${dataimporter.last_index_time}'" >
<field name="id" column="rid" />
<field name="solr_name" column="name" />
</entity>
</document>
</dataConfig>
( TIP : You can have any number of entities but watch out for id field, if they are same then indexing will skipped. )
Add this to your schema.xml as shown..
<uniqueKey>id</uniqueKey>
<field name="solr_name" type="string" indexed="true" stored="true" />
Implementation
This is where the real deal is. You need to do the indexing of data from MySQL to Solr inorder to make use of Solr Queries.
Hit the URL http://localhost:8983/solr on your browser. The screen opens like this.
As the marker indicates, go to Logging inorder to check if any of the above configuration has led to errors.
Ok so now you are here, As you can there are a lot of yellow messages (WARNINGS). Make sure you don't have error messages marked in red. Earlier, on our configuration we had added a select query on our db-data-config.xml, say if there were any errors on that query, it would have shown up here.
Fine, no errors. We are good to go. Let's choose collection1 from the list as depicted and select Dataimport
Using the DIH, you will be connecting to MySQL from Solr through the configuration file db-data-config.xml from the Solr interface and retrieve the 10 records from the database which gets indexed onto Solr.
To do that, Choose full-import , and check the options Clean and Commit. Now click Execute as shown.
Alternatively, you could use a direct full-import query like this too..
http://localhost:8983/solr/collection1/dataimport?command=full-import&commit=true
After you clicked Execute, Solr begins to index the records, if there were any errors, it would say Indexing Failed and you have to go back to the Logging section to see what has gone wrong.
Assuming there are no errors with this configuration and if the indexing is successfully complete., you would get this notification.
Seems like everything went well, now you could use Solr Queries to query the data that was indexed. Click the Query on the left and then press Execute button on the bottom.
You will see the indexed records as shown.
The corresponding Solr query for listing all the records is
http://localhost:8983/solr/collection1/select?q=*:*&wt=json&indent=true
Well, there goes all 10 indexed records. Say, we need only names starting with Ja , in this case, you need to target the column name solr_name
, Hence your query goes like this.
http://localhost:8983/solr/collection1/select?q=solr_name:Ja*&wt=json&indent=true
That's how you write Solr Queries. To read more about it, Check this beautiful article.
pow
only works on floating-point numbers (double
s, actually). If you want to take powers of integers, and the base isn't known to be an exponent of 2
, you'll have to roll your own.
Usually the dumb way is good enough.
int power(int base, unsigned int exp) {
int i, result = 1;
for (i = 0; i < exp; i++)
result *= base;
return result;
}
Here's a recursive solution which takes O(log n)
space and time instead of the easy O(1)
space O(n)
time:
int power(int base, int exp) {
if (exp == 0)
return 1;
else if (exp % 2)
return base * power(base, exp - 1);
else {
int temp = power(base, exp / 2);
return temp * temp;
}
}
Try like Below
var Boolify = require('node-boolify').Boolify;
if (!Boolify(val)) {
//your instruction
}
Refer node-boolify
I created a StackOverflow account JUST to answer this question. After fruitlessly searching the interwebs I just wrote something myself. This is how I did it so it can be applied to any mongoose model. Either import this function or add it directly into your code where you are doing the updating.
function upsertObject (src, dest) {
function recursiveFunc (src, dest) {
_.forOwn(src, function (value, key) {
if(_.isObject(value) && _.keys(value).length !== 0) {
dest[key] = dest[key] || {};
recursiveFunc(src[key], dest[key])
} else if (_.isArray(src) && !_.isObject(src[key])) {
dest.set(key, value);
} else {
dest[key] = value;
}
});
}
recursiveFunc(src, dest);
return dest;
}
Then to upsert a mongoose document do the following,
YourModel.upsert = function (id, newData, callBack) {
this.findById(id, function (err, oldData) {
if(err) {
callBack(err);
} else {
upsertObject(newData, oldData).save(callBack);
}
});
};
This solution may require 2 DB calls however you do get the benefit of,
Just remember that the destination object will always override the source even if the source has an existing value
Also, for arrays, if the existing object has a longer array than the one replacing it then the values at the end of the old array will remain. An easy way to upsert the entire array is to set the old array to be an empty array before the upsert if that is what you are intending on doing.
UPDATE - 01/16/2016 I added an extra condition for if there is an array of primitive values, Mongoose does not realize the array becomes updated without using the "set" function.
You just need to write the line of code to convert your string to int.
int convertedVal = Integer.parseInt(YOUR STR);
See my code which may help you. models.py
from django.db import models
class Customer(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(max_length=100)
password = models.CharField(max_length=100)
instrument_purchase = models.CharField(max_length=100)
house_no = models.CharField(max_length=100)
address_line1 = models.CharField(max_length=100)
address_line2 = models.CharField(max_length=100)
telephone = models.CharField(max_length=100)
zip_code = models.CharField(max_length=20)
state = models.CharField(max_length=100)
country = models.CharField(max_length=100)
def __str__(self):
return self.name
forms.py
from django import forms
from models import *
class CustomerForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = Customer
fields = ('name', 'email', 'password', 'instrument_purchase', 'house_no', 'address_line1', 'address_line2', 'telephone', 'zip_code', 'state', 'country')
Just add the keychain, as referenced in Ubuntu Quick Tips https://help.ubuntu.com/community/QuickTips
What
Instead of constantly starting up ssh-agent and ssh-add, it is possible to use keychain to manage your ssh keys. To install keychain, you can just click here, or use Synaptic to do the job or apt-get from the command line.
Command line
Another way to install the file is to open the terminal (Application->Accessories->Terminal) and type:
sudo apt-get install keychain
Edit File
You then should add the following lines to your ${HOME}/.bashrc or /etc/bash.bashrc:
keychain id_rsa id_dsa
. ~/.keychain/`uname -n`-sh
I tried all the above and it didn't work. This worked for me:
@Column(name="TestName")
public String getTestName(){//.........
Annotate the getter instead of the variable
c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
c3 = [list(set(c2[i]).intersection(set(c1))) for i in xrange(len(c2))]
c3
->[[32, 13], [28, 13, 7], [1, 6]]
You have to remove line import { provide } from '@angular/core';
from app.module.ts
as provide
is deprecated now. You have to use provide
as below in providers :
providers: [
{
provide: APP_BASE_HREF,
useValue: '<%= APP_BASE %>'
},
FormsModule,
ReactiveFormsModule,
// disableDeprecatedForms(),
// provideForms(),
// HTTP_PROVIDERS, //DGF needed for ng2-translate
// TRANSLATE_PROVIDERS, //DGF ng2-translate (not required, but recommended to have 1 unique instance of your service)
{
provide : TranslateLoader,
useFactory: (http: Http) => new TranslateStaticLoader(http, 'assets/i18n', '.json'),
deps: [Http]
},
{
provide : MissingTranslationHandler,
useClass: TranslationNotFoundHandler
},
AuthGuard,AppConfigService,AppConfig,
DateHelper
]
If I may add one more solution: you can simply cancel the clipboard with this command:
Application.CutCopyMode = False
Since momentjs has no control over javascript date object I found a work around to this.
const currentTime = new Date(); _x000D_
const convertTime = moment(currentTime).tz(timezone).format("YYYY-MM-DD HH:mm:ss");_x000D_
const convertTimeObject = new Date(convertTime);
_x000D_
This will give you a javascript date object with the converted time
You could use the hue-rotate
function in the filter
property. It's quite an obscure measurement though, you'd need to know how many degrees round the colour wheel you need to move in order to arrive at your desired hue, for example:
header {
filter: hue-rotate(90deg);
}
Once you'd found the correct hue, you could combine the brightness
and either grayscale
or saturate
functions to find the correct shade, for example:
header {
filter: hue-rotate(90deg) brightness(10%) grayscale(10%);
}
The filter
property has a vendor prefix in Webkit, so the final code would be:
header {
-webkit-filter: hue-rotate(90deg) brightness(10%) grayscale(10%);
filter: hue-rotate(90deg) brightness(10%) grayscale(10%);
}
I'm not really sure of your question, but if all you really want is list currently opened screen session, try:
screen -ls
When you directly run the rake task or execute any binary file of a gem, there is no guarantee that the command will behave as expected. Because it might happen that you already have the same gem installed on your system which have a version say 1.0 but in your project you have higher version say 2.0. In this case you can not predict which one will be used.
To enforce the desired gem version you take the help of bundle exec
command which would execute the binary in context of current bundle. That means when you use bundle exec, bundler checks the gem version configured for the current project and use that to perform the task.
I have also written a post about it which also shows how we can avoid using it using bin stubs.
sudo apt-get install -y mongodb
it works for 32-bit ubuntu, try it.best of luck.
Java has evolved since this issue was first brought up. You can match all manner of unicode space characters by using the \p{Zs}
group.
Thus if you wanted to replace one or more exotic spaces with a plain space you could do this:
String txt = "whatever my string is";
txt.replaceAll("\\p{Zs}+", " ")
Also worth knowing, if you've used the trim()
string function you should take a look at the (relatively new) strip()
, stripLeading()
, and stripTrailing()
functions on strings. The can help you trim off all sorts of squirrely white space characters. For more information on what what space is included, see Java's Character.isWhitespace()
function.
My solutions is to determine timezone adjustment the browser applies, and reverse it:
var timestamp = 1600913205; //retrieved from unix, that is why it is in seconds
//uncomment below line if you want to apply Pacific timezone
//timestamp += -25200;
//determine the timezone offset the browser applies to Date()
var offset = (new Date()).getTimezoneOffset() * 60;
//re-initialize the Date function to reverse the timezone adjustment
var date = new Date((timestamp + offset) * 1000);
//here continue using date functions.
This point the date will be timezone free and always UTC, You can apply your own offset to timestamp to produce any timezone.
In my case, I had to install "libz.so.1" library to make it work, on Ubuntu 15.04
sudo apt-get install lib32z1
classname.getResourceAsStream() loads a file via the classloader of classname. If the class came from a jar file, that is where the resource will be loaded from.
FileInputStream is used to read a file from the filesystem.
I ran into the 'Expecting: ANY PRIVATE KEY' error when using openssl on Windows (Ubuntu Bash and Git Bash had the same issue).
The cause of the problem was that I'd saved the key and certificate files in Notepad using UTF8. Resaving both files in ANSI format solved the problem.
A useful application for : is if you're only interested in using parameter expansions for their side-effects rather than actually passing their result to a command. In that case you use the PE as an argument to either : or false depending upon whether you want an exit status of 0 or 1. An example might be : "${var:=$1}"
. Since :
is a builtin it should be pretty fast.
Basically this happens when the assemblies you're referencing have "Copy Local" set to "True", meaning that a copy of the DLL is placed in the bin folder along with your exe.
Since Visual Studio will copy all of the dependencies of a referenced assembly as well, it's possible to end up with two different builds of the same assembly being referred to. This is more likely to happen if your projects are in separate solutions, and can therefore be compiled separately.
The way I've gotten around it is to set Copy Local to False for references in assembly projects. Only do it for executables/web applications where you need the assembly for the finished product to run.
Hope that makes sense!
I had the same problem.
I had to print the color of the nodes where the color was: enum col { WHITE, GRAY, BLACK };
and the node: typedef struct Node { col color; };
I tried to print node->color
with printf("%s\n", node->color);
but all I got on the screen was (null)\n
.
The answer bmargulies gave almost solved the problem.
So my final solution is:
static char *enumStrings[] = {"WHITE", "GRAY", "BLACK"};
printf("%s\n", enumStrings[node->color]);
If you simply moved the folder with flutter binary executable as I did, then I suggest following:
echo $PATH
to point to the correct folder. Use export PATH="$PATH:$HOME/flutter/bin"
or whatever you need (and you can also include this into your ~/.bashrc or ~/.zshrc). Use source ~/.bashrc
to update it without exiting the current terminal windowflutter clean
will clean the build/ folder with old pathsflutter doctor
just to make sure everything is installed in the OS correctlyafter that you should be able to flutter run
which will build a new app.
I thought I would expand on these answers for OSX and Linux folks (not that they need it):
I prefer to use mvnDebug too. But after OSX maverick destroyed my Java dev environment, I am starting from scratch and stubbled upon this post, and thought I would add to it.
$ mvnDebug vertx:runMod
-bash: mvnDebug: command not found
DOH! I have not set it up on this box after the new SSD drive and/or the reset of everything Java when I installed Maverick.
I use a package manager for OSX and Linux so I have no idea where mvn really lives. (I know for brief periods of time.. thanks brew.. I like that I don't know this.)
Let's see:
$ which mvn
/usr/local/bin/mvn
There you are... you little b@stard.
Now where did you get installed to:
$ ls -l /usr/local/bin/mvn
lrwxr-xr-x 1 root wheel 39 Oct 31 13:00 /
/usr/local/bin/mvn -> /usr/local/Cellar/maven30/3.0.5/bin/mvn
Aha! So you got installed in /usr/local/Cellar/maven30/3.0.5/bin/mvn. You cheeky little build tool. No doubt by homebrew...
Do you have your little buddy mvnDebug with you?
$ ls /usr/local/Cellar/maven30/3.0.5/bin/mvnDebug
/usr/local/Cellar/maven30/3.0.5/bin/mvnDebug
Good. Good. Very good. All going as planned.
Now move that little b@stard where I can remember him more easily.
$ ln -s /usr/local/Cellar/maven30/3.0.5/bin/mvnDebug /usr/local/bin/mvnDebug
ln: /usr/local/bin/mvnDebug: Permission denied
Darn you computer... You will submit to my will. Do you know who I am? I am SUDO! BOW!
$ sudo ln -s /usr/local/Cellar/maven30/3.0.5/bin/mvnDebug /usr/local/bin/mvnDebug
Now I can use it from Eclipse (but why would I do that when I have IntelliJ!!!!)
$ mvnDebug vertx:runMod
Preparing to Execute Maven in Debug Mode
Listening for transport dt_socket at address: 8000
Internally mvnDebug uses this:
MAVEN_DEBUG_OPTS="-Xdebug -Xnoagent -Djava.compiler=NONE \
-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000"
So you could modify it (I usually debug on port 9090).
This blog explains how to setup Eclipse remote debugging (shudder)
http://javarevisited.blogspot.com/2011/02/how-to-setup-remote-debugging-in.html
Ditto Netbeans
https://blogs.oracle.com/atishay/entry/use_netbeans_to_debug_a
Ditto IntelliJ http://www.jetbrains.com/idea/webhelp/run-debug-configuration-remote.html
Here is some good docs on the -Xdebug command in general.
http://docs.oracle.com/cd/E13150_01/jrockit_jvm/jrockit/jrdocs/refman/optionX.html
"-Xdebug enables debugging capabilities in the JVM which are used by the Java Virtual Machine Tools Interface (JVMTI). JVMTI is a low-level debugging interface used by debuggers and profiling tools. With it, you can inspect the state and control the execution of applications running in the JVM."
"The subset of JVMTI that is most typically used by profilers is always available. However, the functionality used by debuggers to be able to step through the code and set breakpoints has some overhead associated with it and is not always available. To enable this functionality you must use the -Xdebug option."
-Xrunjdwp:transport=dt_socket,server=y,suspend=n myApp
Check out the docs on -Xrunjdwp too. You can enable it only when a certain exception is thrown for example. You can start it up suspended or running. Anyway.. I digress.
You do not need to give an index.
Instead of doing order[0].push(a[i])
, just do order.push(a[i])
.
You need to point to the directory instead. You must not specify the dockerfile.
docker build -t ubuntu-test:latest .
does work.
docker build -t ubuntu-test:latest ./Dockerfile
does not work.
Since this topic never received a verified solution, I can offer a simple solution to the two issues I see you asked solutions for.
The string class offers a replace method for the string object you want to update:
Example:
$myString = $myString.replace(".","")
The system.int32 class (or simply [int] in powershell) has a method available called "TryParse" which will not only pass back a boolean indicating whether the string is an integer, but will also return the value of the integer into an existing variable by reference if it returns true.
Example:
[string]$convertedInt = "1500"
[int]$returnedInt = 0
[bool]$result = [int]::TryParse($convertedInt, [ref]$returnedInt)
I hope this addresses the issue you initially brought up in your question.
Guava provides an onlyElement
Collector
, but only use it if you expect the collection to have exactly one element.
Collection<String> stringCollection = ...;
String string = collection.stream().collect(MoreCollectors.onlyElement())
If you are unsure of how many elements there are, use findFirst
.
Optional<String> optionalString = collection.stream().findFirst();
In some cases (e.g. html generated and inserted by JavaScript) you also may want to try to insert a zero width joiner:
.wrapper{_x000D_
width: 290px; _x000D_
white-space: no-wrap;_x000D_
resize:both;_x000D_
overflow:auto; _x000D_
border: 1px solid gray;_x000D_
}_x000D_
_x000D_
.breakable-text{_x000D_
display: inline;_x000D_
white-space: no-wrap;_x000D_
}_x000D_
_x000D_
.no-break-before {_x000D_
padding-left: 10px;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<span class="breakable-text">Lorem dorem tralalalala LAST_WORDS</span>‍<span class="no-break-before">TOGETHER</span>_x000D_
</div>
_x000D_
The supplied answers didn't work for me.
I had an empty repo on GitHub with only the LICENSE file and a single commit locally. What worked was:
$ git fetch
$ git merge --allow-unrelated-histories
Merge made by the 'recursive' strategy.
LICENSE | 21 +++++++++++++++++++++
1 file changed, 21 insertions(+)
create mode 100644 LICENSE
Also before merge
you may want to:
$ git branch --set-upstream-to origin/master
Branch 'master' set up to track remote branch 'master' from 'origin'.
Solutions in accepted answer are being deprecated
#4 Calling prop directly
Enzyme simulate is supposed to be removed in version 4. The main maintainer is suggesting directly invoking prop functions, which is what simulate does internally. One solution is to directly test that invoking those props does the right thing; or you can mock out instance methods, test that the prop functions call them, and unit test the instance methods.
You could call click, for example:
wrapper.find('Button').prop('onClick')()
Or
wrapper.find('Button').props().onClick()
Information about deprecation: Deprecation of .simulate() #2173
Why not take the approach that GMail uses and show the number of messages in the page title?
Sometimes users don't want to be distracted when a new message arrives.
Don't forget you can also use pure JavaScript to deal with this situation, using:
window.scrollTo(x-coord, y-coord);
Simplifying @matt's answer -
git blame -L14,15 -- <file_path>
Here you will get a blame for a lines 14 to 15
.
Since -L
option expects Range
as a param we can't get a Blame
for a single line using the -L
option`.
This might not directly answer your question but for the sake of those that come with states like the below
state = {
currentstate:[
{
id: 1 ,
firstname: 'zinani',
sex: 'male'
}
]
}
Solution
const new_value = {
id: 2 ,
firstname: 'san',
sex: 'male'
}
Replace the current state with the new value
this.setState({ currentState: [...this.state.currentState, new_array] })
Image to Data:-
if let img = UIImage(named: "xxx.png") {
let pngdata = img.pngData()
}
if let img = UIImage(named: "xxx.jpeg") {
let jpegdata = img.jpegData(compressionQuality: 1)
}
Data to Image:-
let image = UIImage(data: pngData)
SELECT IDENT_CURRENT('Table')
You can use one of these examples:
SELECT * FROM Table
WHERE ID = (
SELECT IDENT_CURRENT('Table'))
SELECT * FROM Table
WHERE ID = (
SELECT MAX(ID) FROM Table)
SELECT TOP 1 * FROM Table
ORDER BY ID DESC
But the first one will be more efficient because no index scan is needed (if you have index on Id column).
The second one solution is equivalent to the third (both of them need to scan table to get max id).
I started this gist a year ago: https://gist.github.com/PascalPrecht/5411171
Brian Ford (member of the core team) has written this blog post about it: http://briantford.com/blog/angular-bower
And then we started with this component spec (which is not quite complete): https://github.com/angular/angular-component-spec
Since the last ng-conf there's this document for best practices by the core team: https://docs.google.com/document/d/1XXMvReO8-Awi1EZXAXS4PzDzdNvV6pGcuaF4Q9821Es/pub
An example with VBScript (.vbs)
Sub sety(wsh, action, typey, vary, value)
Dim wu
Set wu = wsh.Environment(typey)
wui = wu.Item(vary)
Select Case action
Case "ls"
WScript.Echo wui
Case "del"
On Error Resume Next
wu.remove(vary)
On Error Goto 0
Case "set"
wu.Item(vary) = value
Case "add"
If wui = "" Then
wu.Item(vary) = value
ElseIf InStr(UCase(";" & wui & ";"), UCase(";" & value & ";")) = 0 Then
wu.Item(vary) = value & ";" & wui
End If
Case Else
WScript.Echo "Bad action"
End Select
End Sub
Dim wsh, args
Set wsh = WScript.CreateObject("WScript.Shell")
Set args = WScript.Arguments
Select Case WScript.Arguments.Length
Case 3
value = ""
Case 4
value = args(3)
Case Else
WScript.Echo "Arguments - 0: ls,del,set,add; 1: user,system, 2: variable; 3: value"
value = "```"
End Select
If Not value = "```" Then
' 0: ls,del,set,add; 1: user,system, 2: variable; 3: value
sety wsh, args(0), args(1), UCase(args(2)), value
End If
If you close the main Activity using Activity.finish()
, I think it will close all the activities.
MAybe you can override the default function, and implement it in a static way, I'm not sure
I think this is best link for your solution to update postgres to 9.6
https://sandymadaan.wordpress.com/2017/02/21/upgrade-postgresql9-3-9-6-in-ubuntu-retaining-the-databases/
Inline elements can't be transformed, and pseudo elements are inline by default, so you must apply display: block
or display: inline-block
to transform them:
#whatever:after {
content: "\24B6";
display: inline-block;
transform: rotate(30deg);
}
_x000D_
<div id="whatever">Some text </div>
_x000D_
I learned C first, and I took a course in data structures which used C, before I learned C++. This has worked well for me. A data structures course in C gave me a solid understanding of pointers and memory management. It also made obvious the benefits of the object oriented paradigm, once I had learned what it was.
On the flip side, by learning C first, I have developed some habits that initially caused me to write bad C++ code, such as excessive use of pointers (when C++ references would do) and the preprocessor.
C++ is really a very complex language with lots of features. It is not really a superset of C, though. Rather there is a subset of C++ consisting of the basic procedural programming constructs (loops, ifs, and functions), which is very similar to C. In your case, I would start with that, and then work my way up to more advanced concepts like classes and templates.
The most important thing, IMHO, is to be exposed to different programming paradigms, like procedural, object-oriented, functional, and logical, early on, before your brain freezes into one way of looking at the world. Incidentally, I would also strongly recommend that you learn a functional programming language, like Scheme. It would really expand your horizons.
Instead of HTML entity I prefer the use of @Html.Raw("@")
.
Django database objects use the same save() method for creating and changing objects.
obj = Product.objects.get(pk=pk)
obj.name = "some_new_value"
obj.save()
How Django knows to UPDATE vs. INSERT
If the object’s primary key attribute is set to a value that evaluates to True (i.e., a value other than None or the empty string), Django executes an UPDATE. If the object’s primary key attribute is not set or if the UPDATE didn’t update anything, Django executes an INSERT.
Ref.: https://docs.djangoproject.com/en/1.9/ref/models/instances/
Check out this plugin that does exacly that - jquery.initialize
It works exacly like .each function, the difference is it takes selector you've entered and watch for new items added in future matching this selector and initialize them
Initialize looks like this
$(".some-element").initialize( function(){
$(this).css("color", "blue");
});
But now if new element matching .some-element
selector will appear on page, it will be instanty initialized.
The way new item is added is not important, you dont need to care about any callbacks etc.
So if you'd add new element like:
$("<div/>").addClass('some-element').appendTo("body"); //new element will have blue color!
it will be instantly initialized.
Plugin is based on MutationObserver
Use Fail module.
- fail: msg="The execution has failed because of errors." when: flag == "failed"
Update:
Use register to store the result of a task like you have shown in your example. Then, use a task like this:
- name: Set flag
set_fact: flag = failed
when: "'FAILED' in command_result.stderr"
From the v3 documentation (Developer's Guide > Concepts > Developing for Mobile Devices):
Android and iOS devices respect the following
<meta>
tag:<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
This setting specifies that the map should be displayed full-screen and should not be resizable by the user. Note that the iPhone's Safari browser requires this
<meta>
tag be included within the page's<head>
element.
If an object's creation/existence dependents on another object which can't be tailored, its tight coupling. And, if the dependency can be tailored, its loose coupling. Consider an example in Java:
class Car {
private Engine engine = new Engine( "X_COMPANY" ); // this car is being created with "X_COMPANY" engine
// Other parts
public Car() {
// implemenation
}
}
The client of Car
class can create one with ONLY "X_COMPANY" engine.
Consider breaking this coupling with ability to change that:
class Car {
private Engine engine;
// Other members
public Car( Engine engine ) { // this car can be created with any Engine type
this.engine = engine;
}
}
Now, a Car
is not dependent on an engine of "X_COMPANY" as it can be created with types.
A Java specific note: using Java interfaces just for de-coupling sake is not a proper desing approach. In Java, an interface has a purpose - to act as a contract which intrisically provides de-coupling behavior/advantage.
Bill Rosmus's comment in accepted answer has a good explanation.
If you use Android Annotations https://github.com/androidannotations/androidannotations
You can use @EditorAction annotation
@EditorAction(R.id.your_component_id)
void onDoneAction(EditText view, int actionId){
if(actionId == EditorInfo.IME_ACTION_DONE){
//Todo: Do your work or call a method
}
}
My coworkers helped me with this:
select CONVERT(VARCHAR(10), <tms_column>, 112), count(*)
from table where <tms_column> > '2012-09-10'
group by CONVERT(VARCHAR(10), <tms_column>, 112);
or
select CONVERT(DATE, <tms_column>, 112), count(*)
from table where <tms_column> > '2012-09-10'
group by CONVERT(DATE, <tms_column>, 112);
As noted by Mattias Nordqvist in the comments below, you can also select the radio button option "Run whether user is logged on or not". When saving the task, you will be prompted once for the user password. bambams noted that this wouldn't grant System permissions to the process, and also seems to hide the command window.
It's not an obvious solution, but to make a Scheduled Task run in the background, change the User running the task to "SYSTEM", and nothing will appear on your screen.
I created a comparison of all the solutions mentioned here to have a quick overview:
<h1>with mixin</h1>
<h2>with text-shadow</h2>
<h3>with css text-stroke-width</h3>
I think you need two case statements:
SELECT *
FROM sys.indexes i
JOIN sys.partitions p
ON i.index_id = p.index_id
JOIN sys.allocation_units a
ON
-- left side of join on statement
CASE
WHEN a.type IN (1, 3)
THEN a.container_id
WHEN a.type IN (2)
THEN a.container_id
END
=
-- right side of join on statement
CASE
WHEN a.type IN (1, 3)
THEN p.hobt_id
WHEN a.type IN (2)
THEN p.partition_id
END
This is because:
Easiest way is probably to convert from a VARCHAR to a DATE; then format it back to a VARCHAR again in the format you want;
SELECT TO_CHAR(TO_DATE(DOJ,'MM/DD/YYYY'), 'MM/DD/YYYY') FROM EmpTable;
The first part (setting the output size explictly) isn't too hard:
import matplotlib.pyplot as plt
list1 = [3,4,5,6,9,12]
list2 = [8,12,14,15,17,20]
fig = plt.figure(figsize=(4,3))
ax = fig.add_subplot(111)
ax.plot(list1, list2)
fig.savefig('fig1.png', dpi = 300)
fig.close()
But after a quick google search on matplotlib + tiff, I'm not convinced that matplotlib can make tiff
plots. There is some mention of the GDK backend being able to do it.
One option would be to convert the output with a tool like imagemagick's convert
.
(Another option is to wait around here until a real matplotlib expert shows up and proves me wrong ;-)
I had the same problem, and "export LC_ALL=c"
didn't work for me.
Try export LC_ALL="en_US.UTF-8"
(it will work).