I usually run this simple command to change the git remote url from https to ssh
git remote set-url origin [email protected]:username/repo-name-here.git
Notice Allowed methods in the response
Connection: close
Date: Tue, 11 Feb 2014 15:17:24 GMT
Content-Length: 34
Content-Type: text/html
Allow: GET, DELETE
X-Powered-By: Servlet/2.5 JSP/2.1
It accepts only GET and DELETE. Hence, you need to tweak the server to enable PUT and POST as well.
Allow: GET, DELETE
Here's an extremely simple answer
yourPlot +
theme(
panel.border = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_line(colour = "black")
)
It's that easy. Source: the end of this article
you can use 'urllib' in python3 same as
https://stackoverflow.com/a/27243244/4815313 with few changes.
#python3
import urllib
page = urllib.request.urlopen("/path/").read()
print(page)
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').bind('click', function (event) {
// using this page stop being refreshing
event.preventDefault();
$.ajax({
type: 'POST',
url: 'post.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
</script>
</head>
<body>
<form>
<input name="time" value="00:00:00.00"><br>
<input name="date" value="0000-00-00"><br>
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>
PHP
<?php
if(isset($_POST["date"]) || isset($_POST["time"])) {
$time="";
$date="";
if(isset($_POST['time'])){$time=$_POST['time']}
if(isset($_POST['date'])){$date=$_POST['date']}
echo $time."<br>";
echo $date;
}
?>
If legend_out
is set to True
then legend is available thought g._legend
property and it is a part of a figure. Seaborn legend is standard matplotlib legend object. Therefore you may change legend texts like:
import seaborn as sns
tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
data=tips, markers=["o", "x"], legend_out = True)
# title
new_title = 'My title'
g._legend.set_title(new_title)
# replace labels
new_labels = ['label 1', 'label 2']
for t, l in zip(g._legend.texts, new_labels): t.set_text(l)
sns.plt.show()
Another situation if legend_out
is set to False
. You have to define which axes has a legend (in below example this is axis number 0):
import seaborn as sns
tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
data=tips, markers=["o", "x"], legend_out = False)
# check axes and find which is have legend
leg = g.axes.flat[0].get_legend()
new_title = 'My title'
leg.set_title(new_title)
new_labels = ['label 1', 'label 2']
for t, l in zip(leg.texts, new_labels): t.set_text(l)
sns.plt.show()
Moreover you may combine both situations and use this code:
import seaborn as sns
tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
data=tips, markers=["o", "x"], legend_out = True)
# check axes and find which is have legend
for ax in g.axes.flat:
leg = g.axes.flat[0].get_legend()
if not leg is None: break
# or legend may be on a figure
if leg is None: leg = g._legend
# change legend texts
new_title = 'My title'
leg.set_title(new_title)
new_labels = ['label 1', 'label 2']
for t, l in zip(leg.texts, new_labels): t.set_text(l)
sns.plt.show()
This code works for any seaborn plot which is based on Grid
class.
Well, in Java, a variable can be final not just as a parameter, but as a class-level field, like
public class Test
{
public final int a = 3;
or as a local variable, like
public static void main(String[] args)
{
final int a = 3;
If you want to access and modify a variable from an anonymous class, you might want to make the variable a class-level variable in the enclosing class.
public class Test
{
public int a;
public void doSomething()
{
Runnable runnable =
new Runnable()
{
public void run()
{
System.out.println(a);
a = a+1;
}
};
}
}
You can't have a variable as final and give it a new value. final
means just that: the value is unchangeable and final.
And since it's final, Java can safely copy it to local anonymous classes. You're not getting some reference to the int (especially since you can't have references to primitives like int in Java, just references to Objects).
It just copies over the value of a into an implicit int called a in your anonymous class.
You can simply do:
"123456".Select(q => new string(q,1)).ToArray();
to have an enumerable of integers, as per comment request, you can:
"123456".Select(q => int.Parse(new string(q,1))).ToArray();
It is a little weak since it assumes the string actually contains numbers.
I understand this question is for sql server 2012, but if the same scenario for SQL Server 2017 or SQL Azure you can use Trim
directly as below:
UPDATE *tablename*
SET *columnname* = trim(*columnname*);
It is the NextStep (= NS) heritage. NeXT was the computer company that Steve Jobs formed after he quit Apple in 1985, and NextStep was it's operating system (UNIX based) together with the Obj-C language and runtime. Together with it's libraries and tools, NextStep was later renamed OpenStep (which was also the name on an API that NeXT developed together with Sun), which in turn later became Cocoa.
These different names are actually quite confusing (especially since some of the names differs only in which characters are upper or lower case..), try this for an explanation:
Model:
namespace MvcApplicationrazor.Models
{
public class CountryModel
{
public List<State> StateModel { get; set; }
public SelectList FilteredCity { get; set; }
}
public class State
{
public int Id { get; set; }
public string StateName { get; set; }
}
public class City
{
public int Id { get; set; }
public int StateId { get; set; }
public string CityName { get; set; }
}
}
Controller:
public ActionResult Index()
{
CountryModel objcountrymodel = new CountryModel();
objcountrymodel.StateModel = new List<State>();
objcountrymodel.StateModel = GetAllState();
return View(objcountrymodel);
}
//Action result for ajax call
[HttpPost]
public ActionResult GetCityByStateId(int stateid)
{
List<City> objcity = new List<City>();
objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
return Json(obgcity);
}
// Collection for state
public List<State> GetAllState()
{
List<State> objstate = new List<State>();
objstate.Add(new State { Id = 0, StateName = "Select State" });
objstate.Add(new State { Id = 1, StateName = "State 1" });
objstate.Add(new State { Id = 2, StateName = "State 2" });
objstate.Add(new State { Id = 3, StateName = "State 3" });
objstate.Add(new State { Id = 4, StateName = "State 4" });
return objstate;
}
//collection for city
public List<City> GetAllCity()
{
List<City> objcity = new List<City>();
objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" });
objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" });
objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" });
objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" });
objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" });
objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" });
return objcity;
}
View:
@model MvcApplicationrazor.Models.CountryModel
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript">
function GetCity(_stateId) {
var procemessage = "<option value='0'> Please wait...</option>";
$("#ddlcity").html(procemessage).show();
var url = "/Test/GetCityByStateId/";
$.ajax({
url: url,
data: { stateid: _stateId },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>Select City</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$("#ddlcity").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
}
</script>
<h4>
MVC Cascading Dropdown List Using Jquery</h4>
@using (Html.BeginForm())
{
@Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { @id = "ddlstate", @style = "width:200px;", @onchange = "javascript:GetCity(this.value);" })
<br />
<br />
<select id="ddlcity" name="ddlcity" style="width: 200px">
</select>
<br /><br />
}
Here is a full example on how to transform your date in different types:
Date date = Calendar.getInstance().getTime();
// Display a date in day, month, year format
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String today = formatter.format(date);
System.out.println("Today : " + today);
// Display date with day name in a short format
formatter = new SimpleDateFormat("EEE, dd/MM/yyyy");
today = formatter.format(date);
System.out.println("Today : " + today);
// Display date with a short day and month name
formatter = new SimpleDateFormat("EEE, dd MMM yyyy");
today = formatter.format(date);
System.out.println("Today : " + today);
// Formatting date with full day and month name and show time up to
// milliseconds with AM/PM
formatter = new SimpleDateFormat("EEEE, dd MMMM yyyy, hh:mm:ss.SSS a");
today = formatter.format(date);
System.out.println("Today : " + today);
Not being a Python person, but the easiest without any libraries is just:
total = 3800
seconds = total % 60
total = total - seconds
hours = total / 3600
total = total - (hours * 3600)
mins = total / 60
Use this:
document.write('<td width="74"><button id="button" type="button" onclick="myfunction('" + name + "')">click</button></td>')
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash
sudo npm install -g n
sudo n 10.15
npm install
npm audit fix
npm start
If you're doing fragment caching, you can manually break the cache by updating your cache key, like so:
<% cache ['cool_name_for_cache_key', 'v1'] do %>
<% cache ['cool_name_for_cache_key', 'v2'] do %>
Or you can have the cache automatically reset based on the state of a non-static object, such as an ActiveRecord object, like so:
<% cache @user_object do %>
With this ^ method, any time the user object is updated, the cache will automatically be reset.
I have just include Maven integration plug-in at Eclipse:
Just follow the bellow steps:
In eclipse, from upper menu item select- "Help" ->click on "Install New Software.."-> then click on "Add" button.
set the "MavenAPI" at name text box and "http://download.eclipse.org/technology/m2e/releases" at location text box.
press Ok and select the Maven project and install by clicking next next.
Use this overload (RenderPartialExtensions.RenderPartial
on MSDN):
public static void RenderPartial(
this HtmlHelper htmlHelper,
string partialViewName,
Object model
)
so:
@{Html.RenderPartial(
"FullName",
new { firstName = model.FirstName, lastName = model.LastName});
}
You have to loop over the input array and add rules for each input as described here: Loop Over Rules
Here is a some code for ya:
$input = Request::all();
$rules = [];
foreach($input['name'] as $key => $val)
{
$rules['name.'.$key] = 'required|distinct|min:3';
}
$rules['amount'] = 'required|integer|min:1';
$rules['description'] = 'required|string';
$validator = Validator::make($input, $rules);
//Now check validation:
if ($validator->fails())
{
/* do something */
}
One possible reason could be you have upgraded the some of your projects (in the solution) to higher version e.g. from .NET 4.0 to 4.5 This happened in my case when I opened the solution in VS 2013 (originally created using VS 2010 and .NET 4.0). When I opened in VS 2013 my C++ project got updated to .NET 4.5 and I started to see the problem.
I just found out that the following works:
https://www.youtube.com/embed/[video_id]?start=[start_at_second]&end=[end_at_second]
Note: the time must be an integer number of seconds (e.g. 119, not 1m59s).
you can try this
SELECT REPLACE(columnname,'0','') FROM table
Avoid of lot of fat fingering by starting with a Dictionary in the Model
namespace EzPL8.Models
{
public class MyEggs
{
public Dictionary<int, string> Egg { get; set; }
public MyEggs()
{
Egg = new Dictionary<int, string>()
{
{ 0, "No Preference"},
{ 1, "I hate eggs"},
{ 2, "Over Easy"},
{ 3, "Sunny Side Up"},
{ 4, "Scrambled"},
{ 5, "Hard Boiled"},
{ 6, "Eggs Benedict"}
};
}
}
In the View convert it to a list for display
@Html.DropDownListFor(m => m.Egg.Keys,
new SelectList(
Model.Egg,
"Key",
"Value"))
As David notes, his suggestion does not actually fulfill the OP's request, which was an email with subject and message. It doesn't work because most, maybe all, combinations of browsers plus e-mail clients do not accept the subject
and body
attributes of the mailto:
URI when supplied as a <form>
's action
.
But here's a working example:
HTML (with Bootstrap styles):
<p><input id="subject" type="text" placeholder="type your subject here"
class="form-control"></p>
<p><input id="message" type="text" placeholder="type your message here"
class="form-control"></p>
<p><a id="mail-link" class="btn btn-primary">Create email</a></p>
JavaScript (with jQuery):
<script type="text/javascript">
function loadEvents() {
var mailString;
function updateMailString() {
mailString = '?subject=' + encodeURIComponent($('#subject').val())
+ '&body=' + encodeURIComponent($('#message').val());
$('#mail-link').attr('href', 'mailto:[email protected]' + mailString);
}
$( "#subject" ).focusout(function() { updateMailString(); });
$( "#message" ).focusout(function() { updateMailString(); });
updateMailString();
}
</script>
Notes:
<form>
element with associated action
attribute is not used.<input>
element of type button
is also not used.
<a>
styled as a button (here using Bootstrap) replaces <input type="button">
focusout()
with updateMailString()
is necessary because the <a>
tag's href
attribute does not automatically update when the input fields' values change.updateMailString()
is also called when document is loaded in case the input fields are prepopulated.encodeURIComponent()
is used to get characters such as the quotation mark (") across to Outlook.In this approach, the mailto:
URI is supplied (with subject
and body
attributes) in an a
element's href
tag. This works in all combinations of browsers and e-mail clients I have tested, which are recent (2015) versions of:
Bonus tip: In my use cases, I add some contextual text to the e-mail body
. More often than not, I want that text to contain line breaks. %0D%0A
(carriage return and linefeed) works in my tests.
Consider using cellspacing
and cellpadding
attributes for table
tag or border-spacing
css property.
I think the problem here is that you forgot to set SD card size
Follow these steps to make it work:
This works well in my emulator!
I'm doing in this way and it works .
HttpHeaders headers = createHttpHeaders(map);
public HttpHeaders createHttpHeaders(Map<String, String> map)
{
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
for (Entry<String, String> entry : map.entrySet()) {
headers.add(entry.getKey(),entry.getValue());
}
return headers;
}
// Pass headers here
String requestJson = "{ // Construct your JSON here }";
logger.info("Request JSON ="+requestJson);
HttpEntity<String> entity = new HttpEntity<String>(requestJson, headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
logger.info("Result - status ("+ response.getStatusCode() + ") has body: " + response.hasBody());
logger.info("Response ="+response.getBody());
Hope this helps
There are lots of sophisticated regex testing and development tools, but if you just want a simple test harness in Java, here's one for you to play with:
String[] tests = {
"AAA123",
"ABCDEFGH123",
"XXXX123",
"XYZ123ABC",
"123123",
"X123",
"123",
};
for (String test : tests) {
System.out.println(test + " " +test.matches(".+123"));
}
Now you can easily add new testcases and try new patterns. Have fun exploring regex.
What I believe you're looking for is a way to work with arrays as object values:
var o = {} // empty Object
var key = 'Orientation Sensor';
o[key] = []; // empty Array, which you can push() values into
var data = {
sampleTime: '1450632410296',
data: '76.36731:3.4651554:0.5665419'
};
var data2 = {
sampleTime: '1450632410296',
data: '78.15431:0.5247617:-0.20050584'
};
o[key].push(data);
o[key].push(data2);
This is standard JavaScript and not something NodeJS specific. In order to serialize it to a JSON string you can use the native JSON.stringify
:
JSON.stringify(o);
//> '{"Orientation Sensor":[{"sampleTime":"1450632410296","data":"76.36731:3.4651554:0.5665419"},{"sampleTime":"1450632410296","data":"78.15431:0.5247617:-0.20050584"}]}'
Connection in APPConfig
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=192.168.1.25;Initial Catalog=Login;Persist Security Info=True;User ID=sa;Password=example.com" providerName="System.Data.SqlClient" />
</connectionStrings>
In Class.Cs
public string ConnectionString
{
get
{
return System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
}
}
You can use the LocalForward
directive in your host yam
section of ~/.ssh/config
:
LocalForward 5901 computer.myHost.edu:5901
I would do something like this:
boolean foundQuote = false;
if(charAtIndex(currentStringIndex) == '"')
{
foundQuote = true;
}
if(foundQuote == true)
{
//do nothing
}
else
{
string[] split = currentString.split(',');
}
Call dialog.setCancelable(false);
from your activity/fragment.
Also, what helped me understand this particular scenario that you described is the Promise API documentation, specifically where it explains how the promised returned by the then
method will be resolved differently depending on what the handler fn returns:
if the handler function:
- returns a value, the promise returned by then gets resolved with the returned value as its value;
- throws an error, the promise returned by then gets rejected with the thrown error as its value;
- returns an already resolved promise, the promise returned by then gets resolved with that promise's value as its value;
- returns an already rejected promise, the promise returned by then gets rejected with that promise's value as its value.
- returns another pending promise object, the resolution/rejection of the promise returned by then will be subsequent to the resolution/rejection of the promise returned by the handler. Also, the value of the promise returned by then will be the same as the value of the promise returned by the handler.
The question raised in 2014 and it's 2019 so I guess it's good to look for better option.
You can simply use fetch
api in Javascript which provide you more flexibility.
for example, see this code
fetch('./api/some.json')
.then((response) => {
response.json().then((data) => {
...
});
})
.catch((err) => { ... });
The analytic function approach would look something like
SELECT a, some_date_column
FROM (SELECT a,
some_date_column,
rank() over (partition by a order by some_date_column desc) rnk
FROM tablename)
WHERE rnk = 1
Note that depending on how you want to handle ties (or whether ties are possible in your data model), you may want to use either the ROW_NUMBER
or the DENSE_RANK
analytic function rather than RANK
.
When you execute a method (i.e. function assigned to an object), inside it you can use this
variable to refer to this object, for example:
var obj = {_x000D_
someProperty: true,_x000D_
someMethod: function() {_x000D_
console.log(this.someProperty);_x000D_
}_x000D_
};_x000D_
obj.someMethod(); // logs true
_x000D_
If you assign a method from one object to another, its this
variable refers to the new object, for example:
var obj = {_x000D_
someProperty: true,_x000D_
someMethod: function() {_x000D_
console.log(this.someProperty);_x000D_
}_x000D_
};_x000D_
_x000D_
var anotherObj = {_x000D_
someProperty: false,_x000D_
someMethod: obj.someMethod_x000D_
};_x000D_
_x000D_
anotherObj.someMethod(); // logs false
_x000D_
The same thing happens when you assign requestAnimationFrame
method of window
to another object. Native functions, such as this, has build-in protection from executing it in other context.
There is a Function.prototype.call()
function, which allows you to call a function in another context. You just have to pass it (the object which will be used as context) as a first parameter to this method. For example alert.call({})
gives TypeError: Illegal invocation
. However, alert.call(window)
works fine, because now alert
is executed in its original scope.
If you use .call()
with your object like that:
support.animationFrame.call(window, function() {});
it works fine, because requestAnimationFrame
is executed in scope of window
instead of your object.
However, using .call()
every time you want to call this method, isn't very elegant solution. Instead, you can use Function.prototype.bind()
. It has similar effect to .call()
, but instead of calling the function, it creates a new function which will always be called in specified context. For example:
window.someProperty = true;_x000D_
var obj = {_x000D_
someProperty: false,_x000D_
someMethod: function() {_x000D_
console.log(this.someProperty);_x000D_
}_x000D_
};_x000D_
_x000D_
var someMethodInWindowContext = obj.someMethod.bind(window);_x000D_
someMethodInWindowContext(); // logs true
_x000D_
The only downside of Function.prototype.bind()
is that it's a part of ECMAScript 5, which is not supported in IE <= 8. Fortunately, there is a polyfill on MDN.
As you probably already figured out, you can use .bind()
to always execute requestAnimationFrame
in context of window
. Your code could look like this:
var support = {
animationFrame: (window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame).bind(window)
};
Then you can simply use support.animationFrame(function() {});
.
For a given application launch, you can do it as jim says.
If you want to set it for the entire workspace, you can also set it under
Window->
Preferences->
Java->
Installed JREs
Each JRE has a "Default VM arguments" (which I believe are completely ignored if any VM args are set for a run configuration.)
You could even set up different JRE/JDKs with different parameters and have some projects use one, other projects use another.
For developers who cannot change php configuration because of the webhosting. (My settings 256MB max size, 1000 max variables)
I got the same issue that just 2 out of 5 big data objects (associative arrays) with substructures were received on the server side.
I find out that the whole substructure is being "flattened" in the post request. So, one object becomes a hundreds of literal variables. At the end, instead of 5 Object variables it is in reality sending dozens of hundreds elementar variables.
Solution in this case is to serialize each of the substructures into String. Then it is received on the server as 5 String variables.
Example:
{variable1:JSON.stringify(myDataObject1),variable2:JSON.stringify(myDataObject2)...}
Properties prop = new Properties();
String fileName = "./src/test/resources/predefined.properties";
FileInputStream inputStream = new FileInputStream(fileName);
InputStreamReader reader = new InputStreamReader(inputStream,"UTF-8");
When less than 9 datasets:
colors = "bgrcmykw"
color_index = 0
for X,Y in data:
scatter(X,Y, c=colors[color_index])
color_index += 1
We can try this command instead of using && method:
try {hostname; if ($lastexitcode -eq 0) {ipconfig /all | findstr /i bios}} catch {echo err} finally {}
you could also try by wrapping an anchor, then turning its height and width to be the same with its parent. This works for me perfectly.
<div id="css_ID">
<a href="http://www.your_link.com" style="display:block; height:100%; width:100%;"></a>
</div>
in the latest version of android studio, you can just do:
./gradlew assembleRelease
or aR
for short. This will produce an unsigned release apk. Building a signed apk can be done similarly or you can use Build -> Generate Signed Apk in Android Studio.
Here is my build.gradle for reference:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.5.+'
}
}
apply plugin: 'android'
dependencies {
compile fileTree(dir: 'libs', include: '*.jar')
}
android {
compileSdkVersion 17
buildToolsVersion "17.0.0"
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
aidl.srcDirs = ['src']
renderscript.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
}
// Move the tests to tests/java, tests/res, etc...
instrumentTest.setRoot('tests')
// Move the build types to build-types/<type>
// For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...
// This moves them out of them default location under src/<type>/... which would
// conflict with src/ being used by the main source set.
// Adding new build types or product flavors should be accompanied
// by a similar customization.
debug.setRoot('build-types/debug')
release.setRoot('build-types/release')
}
buildTypes {
release {
}
}
I came across this question as I had exact same problem. Although accepted answer works good but with matplotlib version 2.1.0
, it is pretty straight forward to have two scatter plots in one plot without using a reference to Axes
import matplotlib.pyplot as plt
plt.scatter(x,y, c='b', marker='x', label='1')
plt.scatter(x, y, c='r', marker='s', label='-1')
plt.legend(loc='upper left')
plt.show()
Try this:
Calendar calendar = Calendar.getInstance();
calendar.setTime(yourdate);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);
Edit:
hours, minutes, seconds
above will be the hours, minutes and seconds after converting yourdate
to System Timezone!
plot "data.txt" using 1:2 with lines
works for me. Do you actually have blank lines in your data file? That will cause an empty plot. Can you see a plot without data? Like plot x*x. If not, then your terminal might not be set up correctly.
Okay guys another sleek option is
Application.Context.ApplicationInfo.NonLocalizedLabel
verified for hard coded android label on application element.
<application android:label="Big App"></application>
Reference: http://developer.android.com/reference/android/content/pm/PackageItemInfo.html#nonLocalizedLabel
When using Bash, the first of ~/.bash_profile
, ~/.bash_login
and ~/.profile
will be run for an interactive login shell. I believe ~/.profile
is generally run by Unix shells besides Bash. Bash will run ~/.bashrc
for a non-login interactive shell.
I typically put everything I want to always set in .bashrc
and then run it from .bash_profile
, where I also set up a few things that should run only when I'm logging in, such as setting up ssh-agent
or running screen
.
Annotate the property like below
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
To use identity columns for all value-generated properties on a new model, simply place the following in your context's OnModelCreating():
builder.ForNpgsqlUseIdentityColumns();
This will create make all keys and other properties which have .ValueGeneratedOnAdd() have Identity by default. You can use ForNpgsqlUseIdentityAlwaysColumns() to have Identity always, and you can also specify identity on a property-by-property basis with UseNpgsqlIdentityColumn() and UseNpgsqlIdentityAlwaysColumn().
See the section "5.1. Accessing Hibernate APIs from JPA" in the Hibernate ORM User Guide:
Session session = entityManager.unwrap(Session.class);
for /f "tokens=* delims= " %%f in (myfile) do
This reads a file line-by-line, removing leading spaces (thanks, jeb).
set line=%%f
sets then the line
variable to the line just read and
call :procesToken
calls a subroutine that does something with the line
:processToken
is the start of the subroutine mentioned above.
for /f "tokens=1* delims=/" %%a in ("%line%") do
will then split the line at /
, but stopping tokenization after the first token.
echo Got one token: %%a
will output that first token and
set line=%%b
will set the line
variable to the rest of the line.
if not "%line%" == "" goto :processToken
And if line
isn't yet empty (i.e. all tokens processed), it returns to the start, continuing with the rest of the line.
So Volley has been updated to Android studio build style which makes it harder create a jar. But the recommended way for eclipse was using it as a library project and this goes for android studio as well, but when working in android studio we call this a module. So here is a guide to how do it the way Google wants us to do it. Guide is based on this nice tutorial.
First get latest volley with git (git clone https://android.googlesource.com/platform/frameworks/volley).
In your current project (android studio) click [File]
--> [New]
-->[Import Module]
.
Now select the directory where you downloaded Volley to.
Now Android studio might guide you to do the rest but continue guide to verify that everything works correct
Open settings.gradle (find in root) and add (or verify this is included):
include ':app', ':volley'
Now go to your build.gradle in your project and add the dependency:
compile project(":volley")
Thats all there is to it, much simpler and easier than compiling a jar and safer than relying on third parties jars or maven uploads.
You could use convert from the hablar package:
library(dplyr)
library(hablar)
# Sample df (stolen from the solution by Luca Braglia)
df <- tibble("a" = as.character(0:5),
"b" = paste(0:5, ".1", sep = ""),
"c" = letters[1:6])
# insert variable names in num()
df %>% convert(num(a, b))
Which gives you:
# A tibble: 6 x 3
a b c
<dbl> <dbl> <chr>
1 0. 0.100 a
2 1. 1.10 b
3 2. 2.10 c
4 3. 3.10 d
5 4. 4.10 e
6 5. 5.10 f
Or if you are lazy, let retype() from hablar guess the right data type:
df %>% retype()
which gives you:
# A tibble: 6 x 3
a b c
<int> <dbl> <chr>
1 0 0.100 a
2 1 1.10 b
3 2 2.10 c
4 3 3.10 d
5 4 4.10 e
6 5 5.10 f
You need to do one thing:
async
before function.const gulp = require('gulp');
gulp.task('message', async function() {
console.log("Gulp is running...");
});
_x000D_
I used following commands from GoLang official repository, it installed GoLang version 1.6 on my Ubuntu 14.04
sudo add-apt-repository ppa:ubuntu-lxc/lxd-stable
sudo apt-get update
sudo apt-get install golang
Reference official GoLang Repo https://github.com/golang/go/wiki/Ubuntu it seems this ppa will always be updated in future.
try
.insertAfter()
here
$(content).insertAfter('#bla');
If your database StartTime = 07:00:00
and endtime = 14:00:00
, and both are time type. Your query to get the time difference would be:
SELECT TIMEDIFF(Time(endtime ), Time(StartTime )) from tbl_name
If your database startDate = 2014-07-20 07:00:00
and endtime = 2014-07-20 23:00:00
, you can also use this query.
You could use scipy.interpolate.spline
to smooth out your data yourself:
from scipy.interpolate import spline
# 300 represents number of points to make between T.min and T.max
xnew = np.linspace(T.min(), T.max(), 300)
power_smooth = spline(T, power, xnew)
plt.plot(xnew,power_smooth)
plt.show()
spline is deprecated in scipy 0.19.0, use BSpline class instead.
Switching from spline
to BSpline
isn't a straightforward copy/paste and requires a little tweaking:
from scipy.interpolate import make_interp_spline, BSpline
# 300 represents number of points to make between T.min and T.max
xnew = np.linspace(T.min(), T.max(), 300)
spl = make_interp_spline(T, power, k=3) # type: BSpline
power_smooth = spl(xnew)
plt.plot(xnew, power_smooth)
plt.show()
In your styles.xml, modify style "AppTheme" like
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<item name="android:windowActionBar">false</item>
<item name="android:windowNoTitle">true</item>
</style>
Quite easy
$timestring = '09:15:00';
echo date('h:i:s', strtotime($timestring) + (15 * 60));
What is the source of these values?
The "source" of the coefficients posted are the NTSC specifications which can be seen in Rec601 and Characteristics of Television.
The "ultimate source" are the CIE circa 1931 experiments on human color perception. The spectral response of human vision is not uniform. Experiments led to weighting of tristimulus values based on perception. Our L, M, and S cones1 are sensitive to the light wavelengths we identify as "Red", "Green", and "Blue" (respectively), which is where the tristimulus primary colors are derived.2
The linear light3 spectral weightings for sRGB (and Rec709) are:
These are specific to the sRGB and Rec709 colorspaces, which are intended to represent computer monitors (sRGB) or HDTV monitors (Rec709), and are detailed in the ITU documents for Rec709 and also BT.2380-2 (10/2018)
FOOTNOTES
(1) Cones are the color detecting cells of the eye's retina.
(2) However, the chosen tristimulus wavelengths are NOT at the "peak" of each cone type - instead tristimulus values are chosen such that they stimulate on particular cone type substantially more than another, i.e. separation of stimulus.
(3) You need to linearize your sRGB values before applying the coefficients. I discuss this in another answer here.
Missing io
? Try import org.openide.util.io.ImageUtilities
.
I would say using tryParse, it'll return 'false' if the uint is to big for an int.
Don't forget that a uint can go much bigger than a int, as long as you going > 0
If key is present table.put(key, val)
will just overwrite the value else it'll create a new entry. Poof! and you are done. :)
you can get the value from a map by using key is table.get(key);
That's about it
staticmethod
objects apparently have a __func__
attribute storing the original raw function (makes sense that they had to). So this will work:
class Klass(object):
@staticmethod # use as decorator
def stat_func():
return 42
_ANS = stat_func.__func__() # call the staticmethod
def method(self):
ret = Klass.stat_func()
return ret
As an aside, though I suspected that a staticmethod object had some sort of attribute storing the original function, I had no idea of the specifics. In the spirit of teaching someone to fish rather than giving them a fish, this is what I did to investigate and find that out (a C&P from my Python session):
>>> class Foo(object):
... @staticmethod
... def foo():
... return 3
... global z
... z = foo
>>> z
<staticmethod object at 0x0000000002E40558>
>>> Foo.foo
<function foo at 0x0000000002E3CBA8>
>>> dir(z)
['__class__', '__delattr__', '__doc__', '__format__', '__func__', '__get__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>> z.__func__
<function foo at 0x0000000002E3CBA8>
Similar sorts of digging in an interactive session (dir
is very helpful) can often solve these sorts of question very quickly.
Austin's answer works for your example case.
More generally, you would do well to look into the regular expression functions when the substring you're splitting on may differ between strings:
$variable = preg_replace('/By.*/', '', $variable);
In the real world, scenario its not about calling a simple function but a function with a proper value. So let's dive in. This is the scenario A user has a requirement to fire an event from his own component and also at the end he wants to call a function of another component as well. Let's say the service file is the same for both the components
componentOne.html
<button (click)="savePreviousWorkDetail()" data-dismiss="modal" class="btn submit-but" type="button">
Submit
</button>
When the user clicks on the submit button he needs to call savePreviousWorkDetail() in its own component componentOne.ts and in the end he needs to call a function of another component as well. So to do that a function in a service class can be called from componentOne.ts and when that called, the function from componentTwo will be fired.
componentOne.ts
constructor(private httpservice: CommonServiceClass) {
}
savePreviousWorkDetail() {
// Things to be Executed in this function
this.httpservice.callMyMethod("Niroshan");
}
commontServiceClass.ts
import {Injectable,EventEmitter} from '@angular/core';
@Injectable()
export class CommonServiceClass{
invokeMyMethod = new EventEmitter();
constructor(private http: HttpClient) {
}
callMyMethod(params: any = 'Niroshan') {
this.invokeMyMethod.emit(params);
}
}
And Below is the componentTwo which has the function that needed to be called from componentOne. And in ngOnInit() we have to subscribe for the invoked method so when it triggers methodToBeCalled() will be called
componentTwo.ts
import {Observable,Subscription} from 'rxjs';
export class ComponentTwo implements OnInit {
constructor(private httpservice: CommonServiceClass) {
}
myMethodSubs: Subscription;
ngOnInit() {
this.myMethodSubs = this.httpservice.invokeMyMethod.subscribe(res => {
console.log(res);
this.methodToBeCalled();
});
methodToBeCalled(){
//what needs to done
}
}
}
For anyone who may stumble across this old question ...
There is one thing that I think needs to be addressed.
~/.nanorc
is used to apply your user specific settings to nano, so if you are editing files that require the use of sudo nano
for permissions then this is not going to work.
When using sudo
your custom user configuration files will not be loaded when opening a program, as you are not running the program from your account so none of your configuration changes in ~/.nanorc
will be applied.
If this is the situation you find yourself in (wanting to run sudo nano
and use your own config settings) then you have three options :
sudo nano
/root/.nanorc
file/etc/nanorc
global config fileKeep in mind that /etc/nanorc
is a global configuration file and as such it affects all users, which may or may not be a problem depending on whether you have a multi-user system.
Also, user config files will override the global one, so if you were to edit /etc/nanorc
and ~/.nanorc
with different settings, when you run nano
it will load the settings from ~/.nanorc
but if you run sudo nano
then it will load the settings from /etc/nanorc
.
Same goes for /root/.nanorc
this will override /etc/nanorc
when running sudo nano
Using flags is probably the best option unless you have a lot of options.
actually the STL can do this without much code, I advise you learn a bit about the STL because it lets you do some fancy things, anyways this is what I use.
std::string GetFileExtension(const std::string& FileName)
{
if(FileName.find_last_of(".") != std::string::npos)
return FileName.substr(FileName.find_last_of(".")+1);
return "";
}
this solution will always return the extension even on strings like "this.a.b.c.d.e.s.mp3" if it cannot find the extension it will return "".
It works and save my time. Try it HTTP Error 500.19 – Internal Server Error – 0x80070021 (IIS 8.5)
An Enumerator
shows you the items in a list or collection.
Each instance of an Enumerator is at a certain position (the 1st element, the 7th element, etc) and can give you that element (IEnumerator.Current
) or move to the next one (IEnumerator.MoveNext
). When you write a foreach
loop in C#, the compiler generates code that uses an Enumerator.
An Enumerable
is a class that can give you Enumerator
s. It has a method called GetEnumerator
which gives you an Enumerator
that looks at its items. When you write a foreach
loop in C#, the code that it generates calls GetEnumerator
to create the Enumerator
used by the loop.
auto_now=True
didn't work for me in Django 1.4.1, but the below code saved me. It's for timezone aware datetime.
from django.utils.timezone import get_current_timezone
from datetime import datetime
class EntryVote(models.Model):
voted_on = models.DateTimeField(auto_now=True)
def save(self, *args, **kwargs):
self.voted_on = datetime.now().replace(tzinfo=get_current_timezone())
super(EntryVote, self).save(*args, **kwargs)
Do I even need a for loop to create a list?
No, you can (and in general circumstances should) use the built-in function range()
:
>>> range(1,5)
[1, 2, 3, 4]
i.e.
def naturalNumbers(n):
return range(1, n + 1)
Python 3's range()
is slightly different in that it returns a range
object and not a list, so if you're using 3.x wrap it all in list()
: list(range(1, n + 1))
.
Since JPA 2.0 a TypedQuery
can be used:
TypedQuery<SimpleEntity> q =
em.createQuery("select t from SimpleEntity t", SimpleEntity.class);
List<SimpleEntity> listOfSimpleEntities = q.getResultList();
for (SimpleEntity entity : listOfSimpleEntities) {
// do something useful with entity;
}
You can use sprintf-like formatting to inject values into the string. For that the string must include placeholders. Put your arguments into an array and use on of these ways: (For more info look at the documentation for Kernel::sprintf.)
fmt = 'The %s %s the %s'
res = fmt % [animal, action, other_animal] # using %-operator
res = sprintf(fmt, animal, action, other_animal) # call Kernel.sprintf
You can even explicitly specify the argument number and shuffle them around:
'The %3$s %2$s the %1$s' % ['cat', 'eats', 'mouse']
Or specify the argument using hash keys:
'The %{animal} %{action} the %{second_animal}' %
{ :animal => 'cat', :action=> 'eats', :second_animal => 'mouse'}
Note that you must provide a value for all arguments to the %
operator. For instance, you cannot avoid defining animal
.
If you wanna do it in case-insensitive way, this is better:
System.out.println(test.matches("^(?i)(https?|ftp)://.*$"));
It's already an array of C-style strings:
#include <iostream>
#include <string>
#include <vector>
int main(int argc, char *argv[]) // Don't forget first integral argument 'argc'
{
std::string current_exec_name = argv[0]; // Name of the current exec program
std::vector<std::string> all_args;
if (argc > 1) {
all_args.assign(argv + 1, argv + argc);
}
}
Argument argc
is count of arguments plus the current exec file.
After coming back to my own question after 5 year and seeing so many people found this useful, a little update.
A string variable can be split into a list
by using the split function (it can contain similar values, set
is for the assignment) . I haven't found this function in the official documentation but it works similar to normal Python. The items can be called via an index, used in a loop or like Dave suggested if you know the values, it can set variables like a tuple.
{% set list1 = variable1.split(';') %}
The grass is {{ list1[0] }} and the boat is {{ list1[1] }}
or
{% set list1 = variable1.split(';') %}
{% for item in list1 %}
<p>{{ item }}<p/>
{% endfor %}
or
{% set item1, item2 = variable1.split(';') %}
The grass is {{ item1 }} and the boat is {{ item2 }}
See also here: http://sqlblog.com/blogs/alexander_kuznetsov/archive/2008/06/26/fun-with-dbcc-chekident.aspx
This is documented behavior, why do you run CHECKIDENT if you recreate the table, in that case skip the step or use TRUNCATE (if you don't have FK relationships)
The error is also caused by quirky handling of quotes and single qutoes. To include single quotes inside the query, use doubled single quotes.
This won't work
select dbms_xmlgen.getxml("Select ....") XML from dual;
or this either
select dbms_xmlgen.getxml('Select .. where something='red'..') XML from dual;
but this DOES work
select dbms_xmlgen.getxml('Select .. where something=''red''..') XML from dual;
I would recommend that you use display: inline;
. float
is screwed up in IE. Here is an example of how I would approach it:
<ul class="side-by-side">
<li>item 1<li>
<li>item 2<li>
<li>item 3<li>
</ul>
and here's the css:
.side-by-side {
width: 100%;
border: 1px solid black;
}
.side-by-side li {
display: inline;
}
Also, if you use floats the ul
will not wrap around the li
's and will instead have a hight of 0 in this example:
.side-by-side li {
float: left;
}
An ES6 update... though both filter and map might need customization.
Object.entries(theObj)
returns a [[key, value],] array representation of an object that can be worked on using Javascript's array methods, .each(), .any(), .forEach(), .filter(), .map(), .reduce(), etc.
Saves a ton of work on iterating over parts of an object Object.keys(theObj)
, or Object.values()
separately.
const buttons = {_x000D_
button1: {_x000D_
text: 'Close',_x000D_
onclick: function(){_x000D_
_x000D_
}_x000D_
},_x000D_
button2: {_x000D_
text: 'OK',_x000D_
onclick: function(){_x000D_
_x000D_
}_x000D_
},_x000D_
button3: {_x000D_
text: 'Cancel',_x000D_
onclick: function(){_x000D_
_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
list = Object.entries(buttons)_x000D_
.filter(([key, value]) => `${key}`[value] !== 'undefined' ) //has options_x000D_
.map(([key, value], idx) => `{${idx} {${key}: ${value}}}`)_x000D_
_x000D_
console.log(list)
_x000D_
in android i did this using kotlin:
private fun angleBetweenPoints(a: PointF, b: PointF): Double {
val deltaY = abs(b.y - a.y)
val deltaX = abs(b.x - a.x)
return Math.toDegrees(atan2(deltaY.toDouble(), deltaX.toDouble()))
}
The first line moves the cursor to the last non-empty row in the column. The second line prints that columns row.
Selection.End(xlDown).Select
MsgBox(ActiveCell.Row)
All of the current answers are addressing the symptom (shared memory pool exhaustion), and not the problem, which is likely not using bind variables in your sql \ JDBC queries, even when it does not seem necessary to do so. Passing queries without bind variables causes Oracle to "hard parse" the query each time, determining its plan of execution, etc.
https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::p11_question_id:528893984337
Some snippets from the above link:
"Java supports bind variables, your developers must start using prepared statements and bind inputs into it. If you want your system to ultimately scale beyond say about 3 or 4 users -- you will do this right now (fix the code). It is not something to think about, it is something you MUST do. A side effect of this - your shared pool problems will pretty much disappear. That is the root cause. "
"The way the Oracle shared pool (a very important shared memory data structure) operates is predicated on developers using bind variables."
" Bind variables are SO MASSIVELY important -- I cannot in any way shape or form OVERSTATE their importance. "
$("a[href^='http://stackoverflow.com']")
.each(function()
{
this.href = this.href.replace(/^http:\/\/beta\.stackoverflow\.com/,
"http://stackoverflow.com");
});
System.identityHashCode(yourObject) will give the 'original' hash code of yourObject as an integer. Uniqueness isn't necessarily guaranteed. The Sun JVM implementation will give you a value which is related to the original memory address for this object, but that's an implementation detail and you shouldn't rely on it.
EDIT: Answer modified following Tom's comment below re. memory addresses and moving objects.
You can also use the following code :
package com.agileinfotech.bsviewer.ldap;
import java.util.Hashtable;
import java.util.ResourceBundle;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
public class LDAPLoginAuthentication {
public LDAPLoginAuthentication() {
// TODO Auto-generated constructor
}
ResourceBundle resBundle = ResourceBundle.getBundle("settings");
@SuppressWarnings("unchecked")
public String authenticateUser(String username, String password) {
String strUrl = "success";
Hashtable env = new Hashtable(11);
boolean b = false;
String Securityprinciple = "cn=" + username + "," + resBundle.getString("UserSearch");
env.put(Context.INITIAL_CONTEXT_FACTORY, resBundle.getString("InitialContextFactory"));
env.put(Context.PROVIDER_URL, resBundle.getString("Provider_url"));
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, Securityprinciple);
env.put(Context.SECURITY_CREDENTIALS, password);
try {
// Create initial context
DirContext ctx = new InitialDirContext(env);
// Close the context when we're done
b = true;
ctx.close();
} catch (NamingException e) {
b = false;
} finally {
if (b) {
strUrl = "success";
} else {
strUrl = "failer";
}
}
return strUrl;
}
}
CGRectOffset
has since been replaced with the instance method offsetBy
.
https://developer.apple.com/reference/coregraphics/cgrect/1454841-offsetby
For example, what used to be
aView.frame = CGRectOffset(aView.frame, 10, 10)
would now be
aView.frame = aView.frame.offsetBy(dx: CGFloat(10), dy: CGFloat(10))
Your encoded text is [B@6499375d
. That is not Base64, something went wrong while encoding. That decoding code looks good.
Use this code to convert the byte[] to a String before adding it to the URL:
String encodedEmailString = new String(encodedEmail, "UTF-8");
// ...
String confirmLink = "Complete your registration by clicking on following"
+ "\n<a href='" + confirmationURL + encodedEmailString + "'>link</a>";
Got the same problem in 11 11 19, so sorry for possible necroposting. The only what helped was next solution:
var drop = $('#product_1'); // get our element, **must be unique**;
var settings = drop.attr('data-krajee-select2'); pick krajee attrs of our elem;
var drop_id = drop.attr('id'); // take id
settings = window[settings]; // take previous settings from window;
drop.select2(settings); // initialize select2 element with it;
$('.kv-plugin-loading').remove(); // remove loading animation;
It's, maybe, not so good, nice and precise solution, and maybe I still did not clearly understood, how it works and why, but this was the only, what keeps my select2 dropdowns, gotten by ajax, alive. Hope, this solution will be usefull or may push you in right decision in problem fixing
You need to append your variables to the echoed string. For example:
echo 'This is a string '.$PHPvariable.' and this is more string';
in pyspark you can do this:
max(df.select('ColumnName').rdd.flatMap(lambda x: x).collect())
https://trac.ffmpeg.org/wiki/Encode/MP3
VBR Encoding:
ffmpeg -vn -ar 44100 -ac 2 -q:a 1 -codec:a libmp3lame output.mp3
No. Python's iterator protocol is very simple, and only provides one single method (.next()
or __next__()
), and no method to reset an iterator in general.
The common pattern is to instead create a new iterator using the same procedure again.
If you want to "save off" an iterator so that you can go back to its beginning, you may also fork the iterator by using itertools.tee
For those of us who don't remember where we are on unix, or which SID we are using.
Pop this in your .profile.
<br>function CD
<br>{
<br> unalias cd
<br> command cd "$@" && PS1="\${ORACLE_SID}:$(hostname):$PWD> "
<br> alias cd=CD
<br>}
<br>
alias cd=CD
The plain and simple answer is yes, VanillaJS === JavaScript, as prescribed by Dr B. Eich.
In simple words, if your client/user can recover from the Exception then make it a Checked Exception, if your client can't do anything to recover from the Exception then make it Unchecked RuntimeException. E.g, a RuntimeException would be a programmatic error, like division by zero, no user can do anything about it but the programmer himself, then it is a RuntimeException.
Alternatively to add downloaded box, a json file with metadata can be created. This way some additional details can be applied. For example to import box and specifying its version create file:
{
"name": "laravel/homestead",
"versions": [
{
"version": "7.0.0",
"providers": [
{
"name": "virtualbox",
"url": "file:///path/to/box/virtualbox.box"
}
]
}
]
}
Then run vagrant box add
command with parameter:
vagrant box add laravel/homestead /path/to/metadata.json
Cross join will help to join multiple tables with no common fields.But be careful while joining as this join will give cartesian resultset of two tables. QUERY:
SELECT
table1.columnA
, table2,columnA
FROM table1
CROSS JOIN table2
Alternative way to join on some condition that is always true like
SELECT
table1.columnA
, table2,columnA
FROM table1
INNER JOIN table2 ON 1=1
But this type of query should be avoided for performance as well as coding standards.
I think you are asking for this:
var part1name = someObject.part1.name;
var part2quantity = someObject.part2.qty;
var part3name1 = someObject.part3[0].name;
You could be asking for this:
var part1name = someObject["part1"]["name"];
var part2quantity = someObject["part2"]["qty"];
var part3name1 = someObject["part3"][0]["name"];
Both of which will work
Or maybe you are asking for this
var partName = "part1";
var nameStr = "name";
var part1name = someObject[partName][nameStr];
Finally you could be asking for this
var partName = "part1.name";
var partBits = partName.split(".");
var part1name = someObject[partBits[0]][partBits[1]];
EXPOSURE OF API KEYS ISN'T A SECURITY RISK BUT ANYONE CAN PUT YOUR CREDENTIALS ON THEIR SITE.
Open api keys leads to attacks that can use a lot resources at firebase that will definitely cost your hard money.
You can always restrict you firebase project keys to domains / IP's.
https://console.cloud.google.com/apis/credentials/key
select your project Id and key and restrict it to Your Android/iOs/web App.
This is a very good question and sadly many developers don't ask enough questions about IIS/ASP.NET security in the context of being a web developer and setting up IIS. So here goes....
To cover the identities listed:
IIS_IUSRS:
This is analogous to the old IIS6 IIS_WPG
group. It's a built-in group with it's security configured such that any member of this group can act as an application pool identity.
IUSR:
This account is analogous to the old IUSR_<MACHINE_NAME>
local account that was the default anonymous user for IIS5 and IIS6 websites (i.e. the one configured via the Directory Security tab of a site's properties).
For more information about IIS_IUSRS
and IUSR
see:
DefaultAppPool:
If an application pool is configured to run using the Application Pool Identity feature then a "synthesised" account called IIS AppPool\<pool name>
will be created on the fly to used as the pool identity. In this case there will be a synthesised account called IIS AppPool\DefaultAppPool
created for the life time of the pool. If you delete the pool then this account will no longer exist. When applying permissions to files and folders these must be added using IIS AppPool\<pool name>
. You also won't see these pool accounts in your computers User Manager. See the following for more information:
ASP.NET v4.0:
-
This will be the Application Pool Identity for the ASP.NET v4.0 Application Pool. See DefaultAppPool
above.
NETWORK SERVICE:
-
The NETWORK SERVICE
account is a built-in identity introduced on Windows 2003. NETWORK SERVICE
is a low privileged account under which you can run your application pools and websites. A website running in a Windows 2003 pool can still impersonate the site's anonymous account (IUSR_ or whatever you configured as the anonymous identity).
In ASP.NET prior to Windows 2008 you could have ASP.NET execute requests under the Application Pool account (usually NETWORK SERVICE
). Alternatively you could configure ASP.NET to impersonate the site's anonymous account via the <identity impersonate="true" />
setting in web.config
file locally (if that setting is locked then it would need to be done by an admin in the machine.config
file).
Setting <identity impersonate="true">
is common in shared hosting environments where shared application pools are used (in conjunction with partial trust settings to prevent unwinding of the impersonated account).
In IIS7.x/ASP.NET impersonation control is now configured via the Authentication configuration feature of a site. So you can configure to run as the pool identity, IUSR
or a specific custom anonymous account.
LOCAL SERVICE:
The LOCAL SERVICE
account is a built-in account used by the service control manager. It has a minimum set of privileges on the local computer. It has a fairly limited scope of use:
LOCAL SYSTEM:
You didn't ask about this one but I'm adding for completeness. This is a local built-in account. It has fairly extensive privileges and trust. You should never configure a website or application pool to run under this identity.
In Practice:
In practice the preferred approach to securing a website (if the site gets its own application pool - which is the default for a new site in IIS7's MMC) is to run under Application Pool Identity
. This means setting the site's Identity in its Application Pool's Advanced Settings to Application Pool Identity
:
In the website you should then configure the Authentication feature:
Right click and edit the Anonymous Authentication entry:
Ensure that "Application pool identity" is selected:
When you come to apply file and folder permissions you grant the Application Pool identity whatever rights are required. For example if you are granting the application pool identity for the ASP.NET v4.0
pool permissions then you can either do this via Explorer:
Click the "Check Names" button:
Or you can do this using the ICACLS.EXE
utility:
icacls c:\wwwroot\mysite /grant "IIS AppPool\ASP.NET v4.0":(CI)(OI)(M)
...or...if you site's application pool is called BobsCatPicBlog
then:
icacls c:\wwwroot\mysite /grant "IIS AppPool\BobsCatPicBlog":(CI)(OI)(M)
I hope this helps clear things up.
Update:
I just bumped into this excellent answer from 2009 which contains a bunch of useful information, well worth a read:
The difference between the 'Local System' account and the 'Network Service' account?
I think this will do it for you:
location / {
try_files /base.html =404;
}
I solved the problem by opening the Android SDK Manager and installing the SDK build tools for the version it is complaining about (API 24).
I had also updated using the command line previously and I suspect the Android SDK Manager has a more complete way of resolving dependencies, including the license.
Go to this link
Download version tar.gz for windows and just extract files to the folder by your needs. On the left pane, you can select which version of openjdk to download
Tutorial: unzip as expected. You need to set system variable PATH to include your directory with openjdk so you can type java -version in console.
I needed to "set a variable if undefined" in several places. I created a function using @Alnitak answer. Hopefully it helps someone.
function setDefaultVal(value, defaultValue){
return (value === undefined) ? defaultValue : value;
}
Usage:
hasPoints = setDefaultVal(this.hasPoints, true);
I think you should install API 18 from android sdk if not already installed, otherwise you can try "invalidate caches and restart" (Find: File->invalidate caches and restart).
It might be worth mentioning that you can also create a .dockerignore
file, to exclude the files that you don't want to copy:
https://docs.docker.com/engine/reference/builder/#dockerignore-file
Before the docker CLI sends the context to the docker daemon, it looks for a file named .dockerignore in the root directory of the context. If this file exists, the CLI modifies the context to exclude files and directories that match patterns in it. This helps to avoid unnecessarily sending large or sensitive files and directories to the daemon and potentially adding them to images using ADD or COPY.
After struggling for a couple of days, the only way to make it work in IntelliJ IDEA 13 was to import the library. Here are all the steps:
android-sdk-root/extras/google/google_play_services/libproject
directory.google-play-services_lib
and paste it next to your IntelliJ IDEA project (some recommend using this directory directly, but I advise to keep this code clean!).google-play-services_lib
.google-play-services_lib
library project as a dependency to the main project.google-play-services
library as a dependency library as well.On the link I provided below, you can see an image of how it looks in my IntelliJ IDEA 13. It would not work without adding only one of these two.
PS. I asked a question, Why does IntelliJ IDEA 13 require both lib project and lib itself (google-play-service) to be added as a dependency?, why is it a must in IntelliJ IDEA 13, and why we cannot import either the library or project only.
I know it is not answer but added if someone looking same in Qt
In Qt
https://wiki.qt.io/Get-OS-name-in-Qt
QString Get::osName()
{
#if defined(Q_OS_ANDROID)
return QLatin1String("android");
#elif defined(Q_OS_BLACKBERRY)
return QLatin1String("blackberry");
#elif defined(Q_OS_IOS)
return QLatin1String("ios");
#elif defined(Q_OS_MAC)
return QLatin1String("osx");
#elif defined(Q_OS_WINCE)
return QLatin1String("wince");
#elif defined(Q_OS_WIN)
return QLatin1String("windows");
#elif defined(Q_OS_LINUX)
return QLatin1String("linux");
#elif defined(Q_OS_UNIX)
return QLatin1String("unix");
#else
return QLatin1String("unknown");
#endif
}
You can change the size of the plot by adding this before you create the figure.
plt.rcParams["figure.figsize"] = [16,9]
I wanted to show how powerful it can be aside from just checking "-lt".
Example: I used it to calculate time differences take from Windows event view Application log:
Get the difference between the two date times:
PS> $Obj = ((get-date "10/22/2020 12:51:1") - (get-date "10/22/2020 12:20:1 "))
Object created:
PS> $Obj
Days : 0
Hours : 0
Minutes : 31
Seconds : 0
Milliseconds : 0
Ticks : 18600000000
TotalDays : 0.0215277777777778
TotalHours : 0.516666666666667
TotalMinutes : 31
TotalSeconds : 1860
TotalMilliseconds : 1860000
Access an item directly:
PS> $Obj.Minutes
31
Straight from the horse's moutyh: Summary of Product Advertising API Operations which has the following categories:
I'm too newbie to comment zeantsoi post ;(. So here his what I needed to do to solved on OSX on 10.9.1 the
IOError: decoder jpeg not available
1) install Xcode tools (open your terminal and execute: xcode-select --install
) - taken from this post: Can't install PIL after Mac OS X 10.9
2) install libpng and libjpeg package (combo installer) from this link: http://ethan.tira-thompson.com/Mac_OS_X_Ports.html
3) reboot (not sure it was mandatory)
4) Re-install PIL with run pip install -I PIL
(as I had initially installed PIL before having the issue)
Hope this help and don't confuse more ...
_oho
In reactjs, you can disable the resize widget using style props.
<textarea id={"multiline-id"} ref={'my-ref'} style={{resize: "none"}} className="text-area-additional-styles" />
you can make use of the below code for sorting in descending order and storing to a dictionary:
listname = []
for key, value in sorted(dictionaryName.iteritems(), key=lambda (k,v): (v,k),reverse=True):
diction= {"value":value, "key":key}
listname.append(diction)
Short answer: Command >filename 2>&1
or Command &>filename
Explanation:
Consider the following code which prints the word "stdout" to stdout and the word "stderror" to stderror.
$ (echo "stdout"; echo "stderror" >&2)
stdout
stderror
Note that the '&' operator tells bash that 2 is a file descriptor (which points to the stderr) and not a file name. If we left out the '&', this command would print stdout
to stdout, and create a file named "2" and write stderror
there.
By experimenting with the code above, you can see for yourself exactly how redirection operators work. For instance, by changing which file which of the two descriptors 1,2
, is redirected to /dev/null
the following two lines of code delete everything from the stdout, and everything from stderror respectively (printing what remains).
$ (echo "stdout"; echo "stderror" >&2) 1>/dev/null
stderror
$ (echo "stdout"; echo "stderror" >&2) 2>/dev/null
stdout
Now, we can explain why the solution why the following code produces no output:
(echo "stdout"; echo "stderror" >&2) >/dev/null 2>&1
To truly understand this, I highly recommend you read this webpage on file descriptor tables. Assuming you have done that reading, we can proceed. Note that Bash processes left to right; thus Bash sees >/dev/null
first (which is the same as 1>/dev/null
), and sets the file descriptor 1 to point to /dev/null instead of the stdout. Having done this, Bash then moves rightwards and sees 2>&1
. This sets the file descriptor 2 to point to the same file as file descriptor 1 (and not to file descriptor 1 itself!!!! (see this resource on pointers for more info)) . Since file descriptor 1 points to /dev/null, and file descriptor 2 points to the same file as file descriptor 1, file descriptor 2 now also points to /dev/null. Thus both file descriptors point to /dev/null, and this is why no output is rendered.
To test if you really understand the concept, try to guess the output when we switch the redirection order:
(echo "stdout"; echo "stderror" >&2) 2>&1 >/dev/null
stderror
The reasoning here is that evaluating from left to right, Bash sees 2>&1, and thus sets the file descriptor 2 to point to the same place as file descriptor 1, ie stdout. It then sets file descriptor 1 (remember that >/dev/null = 1>/dev/null) to point to >/dev/null, thus deleting everything which would usually be send to to the standard out. Thus all we are left with was that which was not send to stdout in the subshell (the code in the parentheses)- i.e. "stderror".
The interesting thing to note there is that even though 1 is just a pointer to the stdout, redirecting pointer 2 to 1 via 2>&1
does NOT form a chain of pointers 2 -> 1 -> stdout. If it did, as a result of redirecting 1 to /dev/null, the code 2>&1 >/dev/null
would give the pointer chain 2 -> 1 -> /dev/null, and thus the code would generate nothing, in contrast to what we saw above.
Finally, I'd note that there is a simpler way to do this:
From section 3.6.4 here, we see that we can use the operator &>
to redirect both stdout and stderr. Thus, to redirect both the stderr and stdout output of any command to \dev\null
(which deletes the output), we simply type
$ command &> /dev/null
or in case of my example:
$ (echo "stdout"; echo "stderror" >&2) &>/dev/null
Key takeaways:
2>&1 >/dev/null
is != >/dev/null 2>&1
. One generates output and the other does not!Finally have a look at these great resources:
Bash Documentation on Redirection, An Explanation of File Descriptor Tables, Introduction to Pointers
Use NETSTAT on the command-line:
netstat util
Solution without creating Service, using $rootScope:
To share properties across app Controllers you can use Angular $rootScope. This is another option to share data, putting it so that people know about it.
The preferred way to share some functionality across Controllers is Services, to read or change a global property you can use $rootscope.
var app = angular.module('mymodule',[]);
app.controller('Ctrl1', ['$scope','$rootScope',
function($scope, $rootScope) {
$rootScope.showBanner = true;
}]);
app.controller('Ctrl2', ['$scope','$rootScope',
function($scope, $rootScope) {
$rootScope.showBanner = false;
}]);
Using $rootScope in a template (Access properties with $root):
<div ng-controller="Ctrl1">
<div class="banner" ng-show="$root.showBanner"> </div>
</div>
std::fill(v.begin(), v.end(), 0);
As Johannes Gorset pointed out, the post by Thomas Ptacek from Matasano Security explains why simple, general-purpose hashing functions such as MD5, SHA1, SHA256 and SHA512 are poor password hashing choices.
Why? They are too fast--you can calculate at least 1,000,000 MD5 hashes a second per core with a modern computer, so brute force is feasible against most passwords people use. And that's much less than a GPU-based cracking server cluster!
Salting without key stretching only means that you cannot precompute the rainbow table, you need to build it ad hoc for that specific salt. But it won't really make things that much harder.
User @Will says:
Everyone is talking about this like they can be hacked over the internet. As already stated, limiting attempts makes it impossible to crack a password over the Internet and has nothing to do with the hash.
They don't need to. Apparently, in the case of LinkedIn they used the common SQL injection vulnerability to get the login DB table and cracked millions of passwords offline.
Then he goes back to the offline attack scenario:
The security really comes into play when the entire database is compromised and a hacker can then perform 100 million password attempts per second against the md5 hash. SHA512 is about 10,000 times slower.
No, SHA512 is not 10000 times slower than MD5--it only takes about twice as much. Crypt/SHA512, on the other hand, is a very different beast that, like its BCrypt counterpart, performs key stretching, producing a very different hash with a random salt built-in and will take anything between 500 and 999999 times as much to compute (stretching is tunable).
SHA512 => aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d
Crypt/SHA512 => $6$rounds=5000$usesomesillystri$D4IrlXatmP7rx3P3InaxBeoomnAihCKRVQP22JZ6EY47Wc6BkroIuUUBOov1i.S5KPgErtP/EN5mcO.ChWQW21
So the choice for PHP is either Crypt/Blowfish (BCrypt), Crypt/SHA256 or Crypt/SHA512. Or at least Crypt/MD5 (PHK). See www.php.net/manual/en/function.crypt.php
I'm a little late to the party, but I have a solution that might work for some who read this. It's in javascript instead of php, but there's a valid reason for it.
Full disclosure, I wrote this plugin...
Anyways.
The approach I've gone with is to allow a user to "Opt-In" to their profanity filtering. Basically profanity will be allowed by default, but if my users don't want to read it, they don't have to. This also helps with the "l33t sp3@k" issue.
The concept is a simple jquery plugin that gets injected by the server if the client's account is enabling profanity filtering. From there, it's just a couple simple lines that blot out the swears.
Here's the demo page
https://chaseflorell.github.io/jQuery.ProfanityFilter/demo/
<div id="foo">
ass will fail but password will not
</div>
<script>
// code:
$('#foo').profanityFilter({
customSwears: ['ass']
});
</script>
result
*** will fail but password will not
From the documentation for strtotime()
:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.
In your date string, you have 12-16-2013
. 16
isn't a valid month, and hence strtotime()
returns false
.
Since you can't use DateTime class, you could manually replace the -
with /
using str_replace()
to convert the date string into a format that strtotime()
understands:
$date = '2-16-2013';
echo date('Y-m-d', strtotime(str_replace('-','/', $date))); // => 2013-02-16
If you want to use an array, you have to keep a counter which contains the number of cars in the garage. Better use an ArrayList
instead of array:
List<Car> garage = new ArrayList<Car>();
garage.add(redCar);
This can be done using driver.execute_script():-
driver.execute_script("document.getElementById('myelementid').scrollIntoView();")
(inline if) in java won't work if you are using 'if' statement .. the right syntax is in the following example:
int y = (c == 19) ? 7 : 11 ;
or
String y = (s > 120) ? "Slow Down" : "Safe";
System.out.println(y);
as You can see the type of the variable Y is the same as the return value ...
in your case it is better to use the normal if statement not inline if as it is in the pervious answer without "?"
if (compareChar(curChar, toChar("0"))) getButtons().get(i).setText("§");
You could checkout Moment.js, Luxon, date-fns or Day.js for nice date manipulation.
Or just extract the first part of your ISO string, it already contains what you want.
Here is an example by splitting on the T
:
"2013-03-10T02:00:00Z".split("T")[0] // "2013-03-10"
Usually it happen in TochableHighlight. Anyway error mean that you must used single element inside the whatever component.
Solution : You can use single view inside parent and anything can be used inside that View. See the attached picture
When you create an object in a .Net framework application, you don't need to think about how the data is stored in memory. Because the .Net Framework takes care of that for you. However, if you want to store the contents of an object to a file, send an object to another process or transmit it across the network, you do have to think about how the object is represented because you will need to convert to a different format. This conversion is called SERIALIZATION.
Serialization allows the developer to save the state of an object and recreate it as needed, providing storage of objects as well as data exchange. Through serialization, a developer can perform actions like sending the object to a remote application by means of a Web Service, passing an object from one domain to another, passing an object through a firewall as an XML string, or maintaining security or user-specific information across applications.
Apply SerializableAttribute
to a type to indicate that instances of this type can be serialized. Apply the SerializableAttribute
even if the class also implements the ISerializable
interface to control the serialization process.
All the public and private fields in a type that are marked by the SerializableAttribute
are serialized by default, unless the type implements the ISerializable
interface to override the serialization process. The default serialization process excludes fields that are marked with NonSerializedAttribute
. If a field of a serializable type contains a pointer, a handle, or some other data structure that is specific to a particular environment, and cannot be meaningfully reconstituted in a different environment, then you might want to apply NonSerializedAttribute
to that field.
See MSDN for more details.
Edit 1
Any reason to not mark something as serializable
When transferring or saving data, you need to send or save only the required data. So there will be less transfer delays and storage issues. So you can opt out unnecessary chunk of data when serializing.
Another way of doing this is using nested IF statements. Suppose you have companies table and you want to count number of records in it. A sample query would be something like this
SELECT IF(
count(*) > 15,
'good',
IF(
count(*) > 10,
'average',
'poor'
)
) as data_count
FROM companies
Here second IF condition works when the first IF condition fails. So Sample Syntax of the IF statement would be IF ( CONDITION, THEN, ELSE). Hope it helps someone.
Relative sys.path example:
# /lib/my_module.py
# /src/test.py
if __name__ == '__main__' and __package__ is None:
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../lib')))
import my_module
Based on this answer.
Easiest way is replace this default bootstrap code:
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
by this :
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="" role="button" ><i class="fa fa-bars" aria-hidden="true" style="color:#e6e6ff"></i></span>
</button>
And don't forget to add this code also to your file:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
Hope it helps!!
This has worked for me:
System.out.println((char)27 + "[31mThis text would show up red" + (char)27 + "[0m");
You need the ending "[37m" to return the color to white (or whatever you were using). If you don't it may make everything that follows "red".
I think It's a best approach to use Apache lang dependency to decide which OS you're running programmatically through Java
import org.apache.commons.lang3.SystemUtils;
public class App {
public static void main( String[] args ) {
if(SystemUtils.IS_OS_WINDOWS_7)
System.out.println("It's a Windows 7 OS");
if(SystemUtils.IS_OS_WINDOWS_8)
System.out.println("It's a Windows 8 OS");
if(SystemUtils.IS_OS_LINUX)
System.out.println("It's a Linux OS");
if(SystemUtils.IS_OS_MAC)
System.out.println("It's a MAC OS");
}
}
Same Problem I had... I was writing all the script in a seperate file and was adding it through tag into the end of the HTML file after body tag. After moving the the tag inside the body tag it works fine. before :
</body>
<script>require('../script/viewLog.js')</script>
after :
<script>require('../script/viewLog.js')</script>
</body>
It depends a bit on the specific filesystem in use on the Linux server. Nowadays the default is ext3 with dir_index, which makes searching large directories very fast.
So speed shouldn't be an issue, other than the one you already noted, which is that listings will take longer.
There is a limit to the total number of files in one directory. I seem to remember it definitely working up to 32000 files.
ISO standards cost money, from a moderate amount (for a PDF version), to a bit more (for a book version).
While they aren't finalised however, they can usually be found online, as drafts. Most of the times the final version doesn't differ significantly from the last draft, so while not perfect, they'll suit just fine.
Maybe this has been added to Git, but the files that have yet to be resolved are listed in the status message (git status) like this:
#
# Unmerged paths:
# (use "git add/rm <file>..." as appropriate to mark resolution)
#
# both modified: syssw/target/libs/makefile
#
Note that this is the Unmerged paths section.
This works for me :
CREATE DEFINER=`root`@`%` PROCEDURE `save_package_as_template`( IN package_id int ,
IN bus_fun_temp_id int , OUT o_message VARCHAR (50) ,
OUT o_number INT )
BEGIN
DECLARE v_pkg_name varchar(50) ;
DECLARE v_pkg_temp_id int(10) ;
DECLARE v_workflow_count INT(10);
-- checking if workflow created for package
select count(*) INTO v_workflow_count from workflow w where w.package_id =
package_id ;
this_proc:BEGIN -- this_proc block start here
IF v_workflow_count = 0 THEN
select 'no work flow ' as 'workflow_status' ;
SET o_message ='Work flow is not created for this package.';
SET o_number = -2 ;
LEAVE this_proc;
END IF;
select 'work flow created ' as 'workflow_status' ;
-- To send some message
SET o_message ='SUCCESSFUL';
SET o_number = 1 ;
END ;-- this_proc block end here
END
Maybe a more Laravel way to solve this problem is to use a collection and loop it inserting with the model taking advantage of the timestamps.
<?php
use App\Continent;
use Illuminate\Database\Seeder;
class InitialSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
collect([
['name' => 'América'],
['name' => 'África'],
['name' => 'Europa'],
['name' => 'Asia'],
['name' => 'Oceanía'],
])->each(function ($item, $key) {
Continent::forceCreate($item);
});
}
}
EDIT:
Sorry for my misunderstanding. For bulk inserting this could help and maybe with this you can make good seeders and optimize them a bit.
<?php
use App\Continent;
use Carbon\Carbon;
use Illuminate\Database\Seeder;
class InitialSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$timestamp = Carbon::now();
$password = bcrypt('secret');
$continents = [
[
'name' => 'América'
'password' => $password,
'created_at' => $timestamp,
'updated_at' => $timestamp,
],
[
'name' => 'África'
'password' => $password,
'created_at' => $timestamp,
'updated_at' => $timestamp,
],
[
'name' => 'Europa'
'password' => $password,
'created_at' => $timestamp,
'updated_at' => $timestamp,
],
[
'name' => 'Asia'
'password' => $password,
'created_at' => $timestamp,
'updated_at' => $timestamp,
],
[
'name' => 'Oceanía'
'password' => $password,
'created_at' => $timestamp,
'updated_at' => $timestamp,
],
];
Continent::insert($continents);
}
}
API 11 added a setRotation() method to all views.
Python's if
can be used as a ternary operator:
>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'
Add this to html:
<svg id="mySVG" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"/>
Try this function and adapt for you program:
var svgNS = "http://www.w3.org/2000/svg";
function createCircle()
{
var myCircle = document.createElementNS(svgNS,"circle"); //to create a circle. for rectangle use "rectangle"
myCircle.setAttributeNS(null,"id","mycircle");
myCircle.setAttributeNS(null,"cx",100);
myCircle.setAttributeNS(null,"cy",100);
myCircle.setAttributeNS(null,"r",50);
myCircle.setAttributeNS(null,"fill","black");
myCircle.setAttributeNS(null,"stroke","none");
document.getElementById("mySVG").appendChild(myCircle);
}
Button1.CssClass += " newClass";
This will not erase your original classes for that control. Try this, it should work.
If you need the result to be timezone-aware, you can use the replace()
method of datetime
objects. This preserves timezone, so you can do
>>> from django.utils import timezone
>>> now = timezone.now()
>>> now
datetime.datetime(2018, 8, 30, 14, 15, 43, 726252, tzinfo=<UTC>)
>>> now.replace(hour=0, minute=0, second=0, microsecond=0)
datetime.datetime(2018, 8, 30, 0, 0, tzinfo=<UTC>)
Note that this returns a new datetime object -- now
remains unchanged.
mtcars[do.call(order, mtcars[cols]), ]
PARTITION BY
segregate sets, this enables you to be able to work(ROW_NUMBER(),COUNT(),SUM(),etc) on related set independently.
In your query, the related set comprised of rows with similar cdt.country_code, cdt.account, cdt.currency. When you partition on those columns and you apply ROW_NUMBER on them. Those other columns on those combination/set will receive sequential number from ROW_NUMBER
But that query is funny, if your partition by some unique data and you put a row_number on it, it will just produce same number. It's like you do an ORDER BY on a partition that is guaranteed to be unique. Example, think of GUID as unique combination of cdt.country_code, cdt.account, cdt.currency
newid()
produces GUID, so what shall you expect by this expression?
select
hi,ho,
row_number() over(partition by newid() order by hi,ho)
from tbl;
...Right, all the partitioned(none was partitioned, every row is partitioned in their own row) rows' row_numbers are all set to 1
Basically, you should partition on non-unique columns. ORDER BY on OVER needed the PARTITION BY to have a non-unique combination, otherwise all row_numbers will become 1
An example, this is your data:
create table tbl(hi varchar, ho varchar);
insert into tbl values
('A','X'),
('A','Y'),
('A','Z'),
('B','W'),
('B','W'),
('C','L'),
('C','L');
Then this is analogous to your query:
select
hi,ho,
row_number() over(partition by hi,ho order by hi,ho)
from tbl;
What will be the output of that?
HI HO COLUMN_2
A X 1
A Y 1
A Z 1
B W 1
B W 2
C L 1
C L 2
You see thee combination of HI HO? The first three rows has unique combination, hence they are set to 1, the B rows has same W, hence different ROW_NUMBERS, likewise with HI C rows.
Now, why is the ORDER BY
needed there? If the previous developer merely want to put a row_number on similar data (e.g. HI B, all data are B-W, B-W), he can just do this:
select
hi,ho,
row_number() over(partition by hi,ho)
from tbl;
But alas, Oracle(and Sql Server too) doesn't allow partition with no ORDER BY
; whereas in Postgresql, ORDER BY
on PARTITION is optional: http://www.sqlfiddle.com/#!1/27821/1
select
hi,ho,
row_number() over(partition by hi,ho)
from tbl;
Your ORDER BY
on your partition look a bit redundant, not because of the previous developer's fault, some database just don't allow PARTITION
with no ORDER BY
, he might not able find a good candidate column to sort on. If both PARTITION BY columns and ORDER BY columns are the same just remove the ORDER BY, but since some database don't allow it, you can just do this:
SELECT cdt.*,
ROW_NUMBER ()
OVER (PARTITION BY cdt.country_code, cdt.account, cdt.currency
ORDER BY newid())
seq_no
FROM CUSTOMER_DETAILS cdt
You cannot find a good column to use for sorting similar data? You might as well sort on random, the partitioned data have the same values anyway. You can use GUID for example(you use newid()
for SQL Server). So that has the same output made by previous developer, it's unfortunate that some database doesn't allow PARTITION
with no ORDER BY
Though really, it eludes me and I cannot find a good reason to put a number on the same combinations (B-W, B-W in example above). It's giving the impression of database having redundant data. Somehow reminded me of this: How to get one unique record from the same list of records from table? No Unique constraint in the table
It really looks arcane seeing a PARTITION BY with same combination of columns with ORDER BY, can not easily infer the code's intent.
Live test: http://www.sqlfiddle.com/#!3/27821/6
But as dbaseman have noticed also, it's useless to partition and order on same columns.
You have a set of data like this:
create table tbl(hi varchar, ho varchar);
insert into tbl values
('A','X'),
('A','X'),
('A','X'),
('B','Y'),
('B','Y'),
('C','Z'),
('C','Z');
Then you PARTITION BY hi,ho; and then you ORDER BY hi,ho. There's no sense numbering similar data :-) http://www.sqlfiddle.com/#!3/29ab8/3
select
hi,ho,
row_number() over(partition by hi,ho order by hi,ho) as nr
from tbl;
Output:
HI HO ROW_QUERY_A
A X 1
A X 2
A X 3
B Y 1
B Y 2
C Z 1
C Z 2
See? Why need to put row numbers on same combination? What you will analyze on triple A,X, on double B,Y, on double C,Z? :-)
You just need to use PARTITION on non-unique column, then you sort on non-unique column(s)'s unique-ing column. Example will make it more clear:
create table tbl(hi varchar, ho varchar);
insert into tbl values
('A','D'),
('A','E'),
('A','F'),
('B','F'),
('B','E'),
('C','E'),
('C','D');
select
hi,ho,
row_number() over(partition by hi order by ho) as nr
from tbl;
PARTITION BY hi
operates on non unique column, then on each partitioned column, you order on its unique column(ho), ORDER BY ho
Output:
HI HO NR
A D 1
A E 2
A F 3
B E 1
B F 2
C D 1
C E 2
That data set makes more sense
Live test: http://www.sqlfiddle.com/#!3/d0b44/1
And this is similar to your query with same columns on both PARTITION BY and ORDER BY:
select
hi,ho,
row_number() over(partition by hi,ho order by hi,ho) as nr
from tbl;
And this is the ouput:
HI HO NR
A D 1
A E 1
A F 1
B E 1
B F 1
C D 1
C E 1
See? no sense?
Live test: http://www.sqlfiddle.com/#!3/d0b44/3
Finally this might be the right query:
SELECT cdt.*,
ROW_NUMBER ()
OVER (PARTITION BY cdt.country_code, cdt.account -- removed: cdt.currency
ORDER BY
-- removed: cdt.country_code, cdt.account,
cdt.currency) -- keep
seq_no
FROM CUSTOMER_DETAILS cdt
I bumped into this problem lately with Windows 10 from another direction, and found the answer from @JonSkeet very helpful in solving my problem.
I also did som further research with a test form and found that when the the current culture was set to "no"
or "nb-NO"
at runtime (Thread.CurrentThread.CurrentCulture = new CultureInfo("no");
), the ToString("yyyy-MM-dd HH:mm:ss") call responded differently in Windows 7 and Windows 10. It returned what I expected in Windows 7 and HH.mm.ss in Windows 10!
I think this is a bit scary! Since I believed that a culture was a culture in any Windows version at least.
select to_char(sysdate, 'Month') from dual
in your example will be:
select to_char(to_date('15-11-2010', 'DD-MM-YYYY'), 'Month') from dual
For some reason, none of the above worked for me. This DID however:
,
Replace All
Somehow CTRL + SHIFT + J is registered as a linebreak.
I checked your XAML, it works fine - e.g. both labels have a gray foreground.
My guess is that you have some style which is affecting the way it looks...
Try moving your XAML to a brand-new window and see for yourself... Then, check if you have any themes or styles (in the Window.Resources
for instance) which might be affecting the labels...
Steps For Hide the status bar in iOS 7:
1.Go to your application info.plist file.
2.And Set, View controller-based status bar appearance : Boolean NO
Hope i solved the status bar issue.....
This is programatically set background color as transparent
ImageButton btn=(ImageButton)findViewById(R.id.ImageButton01);
btn.setBackgroundColor(Color.TRANSPARENT);
In my case i have a main.py that have dependencies with other files. After I build that app with py installer using this command:
pyinstaller --onefile --windowed main.py
I got the main.exe inside dist folder. I double clicked on this file, and I raised the error mentioned above. To fix this, I just copy the main.exe from dist directory to previous directory, which is the root directory of my main.py and the dependency files, and I got no error after run the main.exe.
There is no "right way". If you want a universal (but suboptimal) solution you can use a boost::lexical cast
.
A common solution for C++ is to use std::ostream
and << operator
. You can use a stringstream
and stringstream::str()
method for conversion to string.
If you really require a fast mechanism (remember the 20/80 rule) you can look for a "dedicated" solution like C++ String Toolkit Library
Best Regards,
Marcin
Just adding to Jason's answer, the .
selector is only for classes. If you want to select something other than the element, id, or class, you need to wrap it in square brackets.
e.g.
$('element[attr=val]')
What worked for me:
Go to config.inc.php.
Change
$cfg['Servers'][$i]['AllowNoPassword'] = true;
to
$cfg['Servers'][$i]['AllowNoPassword'] = false;
Change
$cfg['Servers'][$i]['password'] = '';
to
$cfg['Servers'][$i]['password'] = ' ';
Change
$cfg['Servers'][$i]['auth_type'] = 'config';
to
$cfg['Servers'][$i]['auth_type'] = 'http';
Reload the page http://localhost/phpmyadmin
Type : root
pass : (empty)
Now you have access to it. :)
There are no industry standard definitions for Architect job titles -- Application/System/Software/Solution Architect all refer in general to a senior developer with strong design and leadership skills. The balance of design, strategy, development (often of core services or frameworks) and management differ based on the organization and project.
The only "Architect" job title that really has a different meaning for me is "Enterprise Architect", which I see as more of a IT strategy position.
There isn't currently a built-in PowerShell method for doing the SFTP part. You'll have to use something like psftp.exe or a PowerShell module like Posh-SSH.
Here is an example using Posh-SSH:
# Set the credentials
$Password = ConvertTo-SecureString 'Password1' -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential ('root', $Password)
# Set local file path, SFTP path, and the backup location path which I assume is an SMB path
$FilePath = "C:\FileDump\test.txt"
$SftpPath = '/Outbox'
$SmbPath = '\\filer01\Backup'
# Set the IP of the SFTP server
$SftpIp = '10.209.26.105'
# Load the Posh-SSH module
Import-Module C:\Temp\Posh-SSH
# Establish the SFTP connection
$ThisSession = New-SFTPSession -ComputerName $SftpIp -Credential $Credential
# Upload the file to the SFTP path
Set-SFTPFile -SessionId ($ThisSession).SessionId -LocalFile $FilePath -RemotePath $SftpPath
#Disconnect all SFTP Sessions
Get-SFTPSession | % { Remove-SFTPSession -SessionId ($_.SessionId) }
# Copy the file to the SMB location
Copy-Item -Path $FilePath -Destination $SmbPath
Some additional notes:
That should give you a decent starting point.
This could help.
It requires the footer height to be a fixed number. Basically, you have a div inside the footer div with it's normal content, with position: absolute
, and then the image with position: relative
, a negative z-index
so it stays "below" everything, and a negative top
value of the footer's height minus the image height (in my example, 50px - 600px = -550px
). Tested in Chrome 8, FireFox 3.6 and IE 9.
For my aggregations I usually end up wanting to see mean and "how big is this group" (a.k.a. length). So this is my handy snippet for those occasions;
agg.mean <- aggregate(columnToMean ~ columnToAggregateOn1*columnToAggregateOn2, yourDataFrame, FUN="mean")
agg.count <- aggregate(columnToMean ~ columnToAggregateOn1*columnToAggregateOn2, yourDataFrame, FUN="length")
aggcount <- agg.count$columnToMean
agg <- cbind(aggcount, agg.mean)
If your goal is to simply display some static files you can use the Connect package. I have had some success (I'm still pretty new to NodeJS myself), using it and the twitter bootstrap API in combination.
at the command line
:\> cd <path you wish your server to reside>
:\> npm install connect
Then in a file (I named) Server.js
var connect = require('connect'),
http = require('http');
connect()
.use(connect.static('<pathyouwishtoserve>'))
.use(connect.directory('<pathyouwishtoserve>'))
.listen(8080);
Finally
:\>node Server.js
Caveats:
If you don't want to display the directory contents, exclude the .use(connect.directory line.
So I created a folder called "server" placed index.html in the folder and the bootstrap API in the same folder. Then when you access the computers IP:8080 it's automagically going to use the index.html file.
If you want to use port 80 (so just going to http://, and you don't have to type in :8080 or some other port). you'll need to start node with sudo, I'm not sure of the security implications but if you're just using it for an internal network, I don't personally think it's a big deal. Exposing to the outside world is another story.
I haven't had to do the following on my latest versions of things, so try it out like above first, if it doesn't work (and you read the errors complaining it can't find nodejs), go ahead and possibly try the below.
Additionally when running in ubuntu I ran into a problem using nodejs as the name (with NPM), if you're having this problem, I recommend using an alias or something to "rename" nodejs to node.
Commands I used (for better or worse):
Create a new file called node
:\>gedit /usr/local/bin/node
#!/bin/bash
exec /nodejs "$@"
sudo chmod -x /usr/local/bin/node
That ought to make
node Server.js
work just fine
Programmatic ICMP ping is complicated due to the elevated privileges required to send raw ICMP packets, and calling ping
binary is ugly. For server monitoring, you can achieve the same result using a technique called TCP ping:
# pip3 install tcping
>>> from tcping import Ping
# Ping(host, port, timeout)
>>> ping = Ping('212.69.63.54', 22, 60)
>>> ping.ping(3)
Connected to 212.69.63.54[:22]: seq=1 time=23.71 ms
Connected to 212.69.63.54[:22]: seq=2 time=24.38 ms
Connected to 212.69.63.54[:22]: seq=3 time=24.00 ms
Internally, this simply establishes a TCP connection to the target server and drops it immediately, measuring time elapsed. This particular implementation is a bit limited in that it doesn't handle closed ports but for your own servers it works pretty well.
Dim evaluator As New Thread(Sub() Me.testthread(goodList, 1))
With evaluator
.IsBackground = True ' not necessary...
.Start()
End With
You didn't say what version you were using, but in SQL 2005 and above, you can use a common table expression with the OVER Clause. It goes a little something like this:
WITH cte AS (
SELECT[foo], [bar],
row_number() OVER(PARTITION BY foo, bar ORDER BY baz) AS [rn]
FROM TABLE
)
DELETE cte WHERE [rn] > 1
Play around with it and see what you get.
(Edit: In an attempt to be helpful, someone edited the ORDER BY
clause within the CTE. To be clear, you can order by anything you want here, it needn't be one of the columns returned by the cte. In fact, a common use-case here is that "foo, bar" are the group identifier and "baz" is some sort of time stamp. In order to keep the latest, you'd do ORDER BY baz desc
)
I found that none of the answers here applied to my specific use case, so I thought I would share my solution.
I was looking to redirect an unauthentciated user to public version of an app page with any possible URL params. Example:
/app/4903294/my-great-car?email=coolguy%40gmail.com to
/public/4903294/my-great-car?email=coolguy%40gmail.com
Here's the solution that worked for me.
return redirect(url_for('app.vehicle', vid=vid, year_make_model=year_make_model, **request.args))
Hope this helps someone!
You can either go for f5 it will execute all the scrips on the tab.
Or
You can create a sql file and put all the insert statements in it and than give the file path in sql plus and execute.
This issue appears to be causing ongoing consternation, so I will attempt to give a clearer answer than the previously posted answers, which only contain partial hints as to what's happening.
Rosetta Flash
that demonstrated a way for hackers to run malicious Flash SWF files from a remote domain in a manner which tricks browsers into thinking it came from the same domain the user was currently browsing. This allows bypassing of the "same-origin policy" and can permit hackers a variety of exploits. You can read the details here: https://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
Content-Disposition: attachment; filename=f.txt
on the returns from JSONP endpoints. This has the annoyance of causing the browser to automatically download a file called f.txt
that you didn't request—but it is far better than your browser automatically running a possibly malicious Flash file.ad.doubleclick.net
probably serves out hundreds of thousands of different ads and only a small percentage likely contain malicious content. This is why various users online are confused thinking they fixed the issue or somehow affected it by uninstalling this program or running that scan, when in fact it is all unrelated. The f.txt
download just means you were protected from a recent potential attack with this exploit and you should have no reason to believe you were compromised in any way.f.txt
file from being downloaded again in the future would be to block the most common domains that appear to be serving this exploit. I've put a short list below of some of the ones implicated in various posts. If you wanted to block these domains from touching your computer, you could add them to your firewall or alternatively you could use the HOSTS
file technique described in the second section of this link: http://www.chromefans.org/chrome-tutorial/how-to-block-a-website-in-google-chrome.htmad.doubleclick.net
adclick.g.doubleclick.net
secure-us.imrworldwide.com
d.turn.com
ad.turn.com
secure.insightexpressai.com
core.insightexpressai.com
Actually the minimum amount of Angular to be used (as requested in the original question) is just adding a class to the DOM element when show
variable is true, and perform the animation/transition via CSS.
So your minimum Angular code is this:
<div class="box-opener" (click)="show = !show">
Open/close the box
</div>
<div class="box" [class.opened]="show">
<!-- Content -->
</div>
With this solution, you need to create CSS rules for the transition, something like this:
.box {
background-color: #FFCC55;
max-height: 0px;
overflow-y: hidden;
transition: ease-in-out 400ms max-height;
}
.box.opened {
max-height: 500px;
transition: ease-in-out 600ms max-height;
}
If you have retro-browser-compatibility issues, just remember to add the vendor prefixes in the transition
s.
See the example here
variable=" Hello..."
print (variable)
print("This is the Test File "+variable)
for integer type ...
variable=" 10"
print (variable)
print("This is the Test File "+str(variable))
Here is a extension method, this allows coding like the SQL IN command.
public static bool In<T>(this T o, params T[] values)
{
if (values == null) return false;
return values.Contains(o);
}
public static bool In<T>(this T o, IEnumerable<T> values)
{
if (values == null) return false;
return values.Contains(o);
}
This allows stuff like that:
List<int> ints = new List<int>( new[] {1,5,7});
int i = 5;
bool isIn = i.In(ints);
Or:
int i = 5;
bool isIn = i.In(1,2,3,4,5);
In addition to Michael's answer, consider a second way: adding linterOptions.exclude to tslint.json
For example, you may have tslint.json
with following lines:
{
"linterOptions": {
"exclude": [
"someDirectory/*.d.ts"
]
}
}
For me, this is what worked using Apache HttpComponents ~ HttpClient 4.x:
KeyStore keyStore = KeyStore.getInstance("PKCS12");
FileInputStream instream = new FileInputStream(new File("client-p12-keystore.p12"));
try {
keyStore.load(instream, "helloworld".toCharArray());
} finally {
instream.close();
}
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom()
.loadKeyMaterial(keyStore, "helloworld".toCharArray())
//.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()) //custom trust store
.build();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext,
new String[] { "TLSv1" },
null,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); //TODO
CloseableHttpClient httpclient = HttpClients.custom()
.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER) //TODO
.setSSLSocketFactory(sslsf)
.build();
try {
HttpGet httpget = new HttpGet("https://localhost:8443/secure/index");
System.out.println("executing request" + httpget.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
The P12 file contains the client certificate and client private key, created with BouncyCastle:
public static byte[] convertPEMToPKCS12(final String keyFile, final String cerFile,
final String password)
throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException,
NoSuchProviderException
{
// Get the private key
FileReader reader = new FileReader(keyFile);
PEMParser pem = new PEMParser(reader);
PEMKeyPair pemKeyPair = ((PEMKeyPair)pem.readObject());
JcaPEMKeyConverter jcaPEMKeyConverter = new JcaPEMKeyConverter().setProvider("BC");
KeyPair keyPair = jcaPEMKeyConverter.getKeyPair(pemKeyPair);
PrivateKey key = keyPair.getPrivate();
pem.close();
reader.close();
// Get the certificate
reader = new FileReader(cerFile);
pem = new PEMParser(reader);
X509CertificateHolder certHolder = (X509CertificateHolder) pem.readObject();
java.security.cert.Certificate x509Certificate =
new JcaX509CertificateConverter().setProvider("BC")
.getCertificate(certHolder);
pem.close();
reader.close();
// Put them into a PKCS12 keystore and write it to a byte[]
ByteArrayOutputStream bos = new ByteArrayOutputStream();
KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
ks.load(null);
ks.setKeyEntry("key-alias", (Key) key, password.toCharArray(),
new java.security.cert.Certificate[]{x509Certificate});
ks.store(bos, password.toCharArray());
bos.close();
return bos.toByteArray();
}
Plenty of good solutions exist for finding all the prime factors of not too large numbers. I just wanted to point out, that once you have them, no computation is required to get all the factors.
if N = p_1^{a}*p_{2}^{b}*p_{3}^{c}.....
Then the number of factors is clearly (a+1)(b+1)(c+1)....
since every factor can occur zero up to a times.
e.g. 12 = 2^2*3^1
so it has 3*2 = 6
factors. 1,2,3,4,6,12
======
I originally thought that you just wanted the number of distinct factors. But the same logic applies. You just iterate over the set of numbers corresponding to the possible combinations of exponents.
so int he example above:
00
01
10
11
20
21
gives you the 6
factors.
The best explanation of how core.autocrlf
works is found on the gitattributes man page, in the text
attribute section.
This is how core.autocrlf
appears to work currently (or at least since v1.7.2 from what I am aware):
core.autocrlf = true
LF
characters are normalized to CRLF
in your working tree; files that contain CRLF
in the repository will not be touchedLF
characters in the repository, are normalized from CRLF
to LF
when committed back to the repository. Files that contain CRLF
in the repository will be committed untouched.core.autocrlf = input
CRLF
characters are normalized to LF
when committed back to the repository.core.autocrlf = false
core.eol
dictates EOL characters in the text files of your working tree.core.eol = native
by default, which means Windows EOLs are CRLF
and *nix EOLs are LF
in working trees.gitattributes
settings determines EOL character normalization for commits to the repository (default is normalization to LF
characters).I've only just recently researched this issue and I also find the situation to be very convoluted. The core.eol
setting definitely helped clarify how EOL characters are handled by git.
Make sure of the conflict origin: if it is the result of a git merge
, see Brian Campbell's answer.
But if is the result of a git rebase
, in order to discard remote (their) changes and use local changes, you would have to do a:
git checkout --theirs -- .
See "Why is the meaning of “ours
” and “theirs
” reversed"" to see how ours
and theirs
are swapped during a rebase (because the upstream branch is checked out).
To show months as Jan 2017 Feb 2017 etc:
scale_x_date(date_breaks = "1 month", date_labels = "%b %Y")
Angle the dates if they take up too much space:
theme(axis.text.x=element_text(angle=60, hjust=1))
The above - findByBookIdRegion() did not work for me. The following works with the latest release of String Data JPA:
Page<QueuedBook> findByBookId_Region(Region region, Pageable pageable);
If you're willing to use IronPython, you can execute scripts directly in C#:
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
private static void doPython()
{
ScriptEngine engine = Python.CreateEngine();
engine.ExecuteFile(@"test.py");
}
I haven't had a problem just using Unix-style path separators, even on Windows (though it is good practice to check File.separatorChar).
The technique of using ClassLoader.getResource() is best for read-only resources that are going to be loaded from JAR files. Sometimes, you can programmatically determine the application directory, which is useful for admin-configurable files or server applications. (Of course, user-editable files should be stored somewhere in the System.getProperty("user.home") directory.)
Let me explain what is happening here, because it isn't obvious!
First, Stream.max()
accepts an instance of Comparator
so that items in the stream can be compared against each other to find the minimum or maximum, in some optimal order that you don't need to worry too much about.
So the question is, of course, why is Integer::max
accepted? After all it's not a comparator!
The answer is in the way that the new lambda functionality works in Java 8. It relies on a concept which is informally known as "single abstract method" interfaces, or "SAM" interfaces. The idea is that any interface with one abstract method can be automatically implemented by any lambda - or method reference - whose method signature is a match for the one method on the interface. So examining the Comparator
interface (simple version):
public Comparator<T> {
T compare(T o1, T o2);
}
If a method is looking for a Comparator<Integer>
, then it's essentially looking for this signature:
int xxx(Integer o1, Integer o2);
I use "xxx" because the method name is not used for matching purposes.
Therefore, both Integer.min(int a, int b)
and Integer.max(int a, int b)
are close enough that autoboxing will allow this to appear as a Comparator<Integer>
in a method context.
Using the SSH URL from GitLab:
Step 1: Generate an SSH Key with default values from GitLab.
GitLab provides the commands to generate it. Just copy them, edit the email, and paste it in the terminal. Using the default values is important. Else SourceTree will not be able to access the SSH key without additional configuration.
STEP 2: Add the SSH key to your keychain using the command ssh-add -K
.
Open the terminal and paste the above command in it. This will add the key to your keychain.
STEP 3: Restart SourceTree and clone remote repo using URL.
Restarting SourceTree is needed so that SourceTree picks the new key.
STEP 4: Copy the SSH URL provided by GitLab.
STEP 5: Paste the SSH URL into the Source URL field of SourceTree.
These steps were successfully performed on Mac OS 10.13.2 using SourceTree 2.7.1.
function curl_int(); cause server error,install sudo apt-get install php5-curl restart apache2 server .. it will work like charm
I have read all answers and I want to summarize for better understanding at first glance like following:
Firstly, the whole command that gets executed in the container includes two parts: the command and the arguments
ENTRYPOINT defines the executable invoked when the container is started (for command)
CMD specifies the arguments that get passed to the ENTRYPOINT (for arguments)
In the Kubernetes In Action book points an important note about it. (chapter 7)
Although you can use the CMD instruction to specify the command you want to execute when the image is run, the correct way is to do it through the ENTRYPOINT instruction and to only specify the CMD if you want to define the default arguments.
You can also read this article for great explanation in a simple way
It's an old question, but if you wanted to catch a backspace event on input, and not keydown, keypress, or keyup—as I've noticed any one of these break certain functions I've written and cause awkward delays with automated text formatting—you can catch a backspace using inputType:
document.getElementsByTagName('input')[0].addEventListener('input', function(e) {
if (e.inputType == "deleteContentBackward") {
// your code here
}
});
Step 1 : Create two view inside a linear layout
Step 2 : First view must set to android:layout_weight="1"
Step 3 : Second view will automatically putted downwards
<LinearLayout
android:id="@+id/botton_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<View
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<Button
android:id="@+id/btn_health_advice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
In eclipse,
.jrxml
file and select Open with JasperReports Book Editor
Design
tab for the .jrxml
file.Compile Report
icon.Use --auto-open-devtools-for-tabs
flag while running chrome from command line
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --auto-open-devtools-for-tabs
https://developers.google.com/web/tools/chrome-devtools/open#auto
If your choices are not pre-decided or they are coming from some other source, you can generate them in your view and pass it to the form .
Example:
views.py:
def my_view(request, interview_pk):
interview = Interview.objects.get(pk=interview_pk)
all_rounds = interview.round_set.order_by('created_at')
all_round_names = [rnd.name for rnd in all_rounds]
form = forms.AddRatingForRound(all_round_names)
return render(request, 'add_rating.html', {'form': form, 'interview': interview, 'rounds': all_rounds})
forms.py
class AddRatingForRound(forms.ModelForm):
def __init__(self, round_list, *args, **kwargs):
super(AddRatingForRound, self).__init__(*args, **kwargs)
self.fields['name'] = forms.ChoiceField(choices=tuple([(name, name) for name in round_list]))
class Meta:
model = models.RatingSheet
fields = ('name', )
template:
<form method="post">
{% csrf_token %}
{% if interview %}
{{ interview }}
{% endif %}
{% if rounds %}
<hr>
{{ form.as_p }}
<input type="submit" value="Submit" />
{% else %}
<h3>No rounds found</h3>
{% endif %}
</form>
In Visual C++ the project options under, Output Files I believe has an option for outputing the ASM listing with source code. So you will see the C/C++ source code and the resulting ASM all in the same file.
I like Alex FTPS Client which is written by a Microsoft MVP name Alex Pilotti. It's a C# library you can use in Console apps, Windows Forms, PowerShell, ASP.NET (in any .NET language). If you have a multithreaded app you will have to configure the library to run syncronously, but overall a good client that will most likely get you what you need.
Post to the UI thread works for me.
final ImageView iv = (ImageView)findViewById(R.id.scaled_image);
iv.post(new Runnable() {
@Override
public void run() {
int width = iv.getMeasuredWidth();
int height = iv.getMeasuredHeight();
}
});
The simple command 'keytool' also works on Windows and/or with Cygwin.
IF you're using Cygwin here is the modified command that I used from the bottom of "S.Botha's" answer :
Execute the keytool command from inside it, where you provide the path to your new Cert at the end, like so:
./keytool.exe -import -trustcacerts -keystore ../lib/security/cacerts -storepass changeit -noprompt -alias myownaliasformysystem -file "D:\Stuff\saved-certs\ca.cert"
Notice, because if this is under Cygwin you're giving a path to a non-Cygwin program, so the path is DOS-like and in quotes.
Try:
$a1=@(1,2,3,4,5)
$b1=@(1,2,3,4,5,6)
(Compare-Object $a1 $b1).InputObject
Or, you can use:
(Compare-Object $b1 $a1).InputObject
The order doesn't matter.
AngularJS form elements look for the required
attribute to perform validation functions. ng-required
allows you to set the required
attribute depending on a boolean test (for instance, only require field B - say, a student number - if the field A has a certain value - if you selected "student" as a choice)
As an example, <input required>
and <input ng-required="true">
are essentially the same thing
If you are wondering why this is this way, (and not just make <input required="true">
or <input required="false">
), it is due to the limitations of HTML - the required
attribute has no associated value - its mere presence means (as per HTML standards) that the element is required - so angular needs a way to set/unset required value (required="false"
would be invalid HTML)
In any case you are confused with your password.You can use hit and trial. It will ask you for password.If it right then it will show you the list.
$ keytool -list -v -keystore filename
There's parameter substitution, though it may be un-PC as well ...like indirection.
#!/bin/bash
# Array pretending to be a Pythonic dictionary
ARRAY=( "cow:moo"
"dinosaur:roar"
"bird:chirp"
"bash:rock" )
for animal in "${ARRAY[@]}" ; do
KEY="${animal%%:*}"
VALUE="${animal##*:}"
printf "%s likes to %s.\n" "$KEY" "$VALUE"
done
printf "%s is an extinct animal which likes to %s\n" "${ARRAY[1]%%:*}" "${ARRAY[1]##*:}"
The BASH 4 way is better of course, but if you need a hack ...only a hack will do. You could search the array/hash with similar techniques.