My problem were different indices, the following code solved my problem.
df1.reset_index(drop=True, inplace=True)
df2.reset_index(drop=True, inplace=True)
df = pd.concat([df1, df2], axis=1)
Late contribution but just came across something similar in Python datetime and pandas give different timestamps for the same date.
If you have timezone-aware datetime in pandas
, technically, tz_localize(None)
changes the POSIX timestamp (that is used internally) as if the local time from the timestamp was UTC. Local in this context means local in the specified timezone. Ex:
import pandas as pd
t = pd.date_range(start="2013-05-18 12:00:00", periods=2, freq='H', tz="US/Central")
# DatetimeIndex(['2013-05-18 12:00:00-05:00', '2013-05-18 13:00:00-05:00'], dtype='datetime64[ns, US/Central]', freq='H')
t_loc = t.tz_localize(None)
# DatetimeIndex(['2013-05-18 12:00:00', '2013-05-18 13:00:00'], dtype='datetime64[ns]', freq='H')
# offset in seconds according to timezone:
(t_loc.values-t.values)//1e9
# array([-18000, -18000], dtype='timedelta64[ns]')
Note that this will leave you with strange things during DST transitions, e.g.
t = pd.date_range(start="2020-03-08 01:00:00", periods=2, freq='H', tz="US/Central")
(t.values[1]-t.values[0])//1e9
# numpy.timedelta64(3600,'ns')
t_loc = t.tz_localize(None)
(t_loc.values[1]-t_loc.values[0])//1e9
# numpy.timedelta64(7200,'ns')
In contrast, tz_convert(None)
does not modify the internal timestamp, it just removes the tzinfo
.
t_utc = t.tz_convert(None)
(t_utc.values-t.values)//1e9
# array([0, 0], dtype='timedelta64[ns]')
My bottom line would be: stick with timezone-aware datetime if you can or only use t.tz_convert(None)
which doesn't modify the underlying POSIX timestamp. Just keep in mind that you're practically working with UTC then.
(Python 3.8.2 x64 on Windows 10, pandas
v1.0.5.)
Both pandas
and matplotlib.dates
use matplotlib.units
for locating the ticks.
But while matplotlib.dates
has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).
So for the moment it seems more reasonable to use matplotlib.dates
(as mentioned by @BrenBarn in his comment).
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as dates
idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)
fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()
(my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])
Two most used ways already mentioned in most answers
obj.key3 = "value3";
obj["key3"] = "value3";
One more way to define a property is using Object.defineProperty()
Object.defineProperty(obj, 'key3', {
value: "value3", // undefined by default
enumerable: true, // false by default
configurable: true, // false by default
writable: true // false by default
});
This method is useful when you want to have more control while defining property. Property defined can be set as enumerable, configurable and writable by user.
You can't access your fieldname
as a global variable. Use document.getElementById:
function updateInput(ish){
document.getElementById("fieldname").value = ish;
}
and
onchange="updateInput(this.value)"
You can create lists and convert them into arrays or you can create array using numpy module. Below are few examples to illustrate the same. Numpy also makes it easier to work with multi-dimensional arrays.
import numpy as np
a = np.array([1, 2, 3, 4])
#For custom inputs
a = np.array([int(x) for x in input().split()])
You can also reshape this array into a 2X2 matrix using reshape function which takes in input as the dimensions of the matrix.
mat = a.reshape(2, 2)
I had the same problem I deleted the server from the server tab, and also the server folder under your eclipse workspace, restarted eclipse, set up a new server, and it appears to be running OK now.
Why not try IS?
$('selector').is(':checked') /* result true or false */
Look a FAQ: jQuery .is() enjoin us ;-)
Project->maven->Update Project->tick all checkboxes expect offline and error is solved soon.
Sorry, this might be a bit late. But I think I found a better implementation on the go docs.
buf := new(bytes.Buffer)
var num uint16 = 1234
err := binary.Write(buf, binary.LittleEndian, num)
if err != nil {
fmt.Println("binary.Write failed:", err)
}
fmt.Printf("% x", buf.Bytes())
Ahhhh, now it is clear. You seem to have problems binding back the value. Not with displaying it on the view. Indeed, that's the fault of the default model binder. You could write and use a custom one that will take into consideration the [DisplayFormat]
attribute on your model. I have illustrated such a custom model binder here: https://stackoverflow.com/a/7836093/29407
Apparently some problems still persist. Here's my full setup working perfectly fine on both ASP.NET MVC 3 & 4 RC.
Model:
public class MyViewModel
{
[DisplayName("date of birth")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? Birth { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel
{
Birth = DateTime.Now
});
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
View:
@model MyViewModel
@using (Html.BeginForm())
{
@Html.LabelFor(x => x.Birth)
@Html.EditorFor(x => x.Birth)
@Html.ValidationMessageFor(x => x.Birth)
<button type="submit">OK</button>
}
Registration of the custom model binder in Application_Start
:
ModelBinders.Binders.Add(typeof(DateTime?), new MyDateTimeModelBinder());
And the custom model binder itself:
public class MyDateTimeModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (!string.IsNullOrEmpty(displayFormat) && value != null)
{
DateTime date;
displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
// use the format specified in the DisplayFormat attribute to parse the date
if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
return date;
}
else
{
bindingContext.ModelState.AddModelError(
bindingContext.ModelName,
string.Format("{0} is an invalid date format", value.AttemptedValue)
);
}
}
return base.BindModel(controllerContext, bindingContext);
}
}
Now, no matter what culture you have setup in your web.config (<globalization>
element) or the current thread culture, the custom model binder will use the DisplayFormat
attribute's date format when parsing nullable dates.
The best way to modify a Hash's values in place is
hash.update(hash){ |_,v| "%#{v}%" }
Less code and clear intent. Also faster because no new objects are allocated beyond the values that must be changed.
What's wrong with just invoking the commands?
foo:
echo line1
echo line2
....
And for your second question, you need to escape the $
by using $$
instead, i.e. bash -c '... echo $$a ...'
.
EDIT: Your example could be rewritten to a single line script like this:
gcc $(for i in `find`; do echo $i; done)
Safe Methods : Get Resource/No modification in resource
Idempotent : No change in resource status if requested many times
Unsafe Methods : Create or Update Resource/Modification in resource
Non-Idempotent : Change in resource status if requested many times
According to your requirement :
1) For safe and idempotent operation (Fetch Resource) use --------- GET METHOD
2) For unsafe and non-idempotent operation (Insert Resource) use--------- POST METHOD
3) For unsafe and idempotent operation (Update Resource) use--------- PUT METHOD
3) For unsafe and idempotent operation (Delete Resource) use--------- DELETE METHOD
One can also use this kind of condition:
<div [ngStyle]="myBooleanVar && {'color': 'red'}"></div>
It requires a bit less string concatenation...
If you want to log errors from web-page, you should use WebChromeClient
and override its onConsoleMessage
:
webView.settings.apply {
javaScriptEnabled = true
javaScriptCanOpenWindowsAutomatically = true
domStorageEnabled = true
}
webView.webViewClient = WebViewClient()
webView.webChromeClient = MyWebChromeClient()
private class MyWebChromeClient : WebChromeClient() {
override fun onConsoleMessage(consoleMessage: ConsoleMessage): Boolean {
Timber.d("${consoleMessage.message()}")
Timber.d("${consoleMessage.lineNumber()} ${consoleMessage.sourceId()}")
return super.onConsoleMessage(consoleMessage)
}
}
1) Click the "Export" tab for the database
2) Click the "Custom" radio button
3) Go the section titled "Format-specific options" and change the dropdown for "Database system or older MySQL server to maximize output compatibility with:" from NONE to MYSQL40.
4) Scroll to the bottom and click "GO".
If it's related to wordpress, more info on why it is happening.
With v25.3.x of the Android Emulator & x86 Google API Emulator system images API Level 19 (Android 4.4 - Kitkat) and higher, you can simply copy and paste from your desktop with your mouse or keyboard.
This feature was announced with Android Studio 2.3
I don't know if I understand your question, but maybe:
foreach ($_POST as $id=>$value)
if (strncmp($id,'id[',3) $info[rtrim(ltrim($id,'id['),']')]=$_POST[$id];
would help
That is if you really want to have a different name (id[key]) on each checkbox of the html form (not very efficient). If not you can just name them all the same, i.e. 'id' and iterate on the (selected) values of the array, like: foreach ($_POST['id'] as $key=>$value)...
It allows for further querying further down the line. If this was beyond a service boundary say, then the user of this IQueryable object would be allowed to do more with it.
For instance if you were using lazy loading with nhibernate this might result in graph being loaded when/if needed.
You can use
php artisan migrate:fresh
to drop all tables and migrate then.
Hope it helps
I got it to work with:
SQLiteDatabase db= this.getWritableDatabase();
db.delete(TABLE_NAME, null, null);
You are incorrectly using the super
and this
keyword. Here is an example of how they work:
class Animal {
public name: string;
constructor(name: string) {
this.name = name;
}
move(meters: number) {
console.log(this.name + " moved " + meters + "m.");
}
}
class Horse extends Animal {
move() {
console.log(super.name + " is Galloping...");
console.log(this.name + " is Galloping...");
super.move(45);
}
}
var tom: Animal = new Horse("Tommy the Palomino");
Animal.prototype.name = 'horseee';
tom.move(34);
// Outputs:
// horseee is Galloping...
// Tommy the Palomino is Galloping...
// Tommy the Palomino moved 45m.
Explanation:
super.name
, this refers to the prototype chain of the object tom
, not the object tom
self. Because we have added a name property on the Animal.prototype
, horseee will be outputted.this.name
, the this
keyword refers to the the tom object itself. move
method of the Animal base class. This method is called from Horse class move method with the syntax super.move(45);
. Using the super
keyword in this context will look for a move
method on the prototype chain which is found on the Animal prototype.Remember TS still uses prototypes under the hood and the class
and extends
keywords are just syntactic sugar over prototypical inheritance.
The docs indicate that numpy.correlate
is not what you are looking for:
numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
Cross-correlation of two 1-dimensional sequences.
This function computes the correlation as generally defined in signal processing texts:
z[k] = sum_n a[n] * conj(v[n+k])
with a and v sequences being zero-padded where necessary and conj being the conjugate.
Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:
from scipy.stats.stats import pearsonr
a = [1,4,6]
b = [1,2,3]
print pearsonr(a,b)
This gives
(0.99339926779878274, 0.073186395040328034)
You can also use numpy.corrcoef
:
import numpy
print numpy.corrcoef(a,b)
This gives:
[[ 1. 0.99339927]
[ 0.99339927 1. ]]
These answers are no longer recommended since try_files
works faster than if
in this context. Simply add try_files
in your php location block to test if the file exists, otherwise return a 404.
location ~ \.php {
try_files $uri =404;
...
}
You can try adding a question mark as below. This worked for me.
componentWillReceiveProps(nextProps) {
this.setState({
title: nextProps?.blog?.title,
body: nextProps?.blog?.content
})
}
Another way to do this in Notepad++ is all in the Find/Replace dialog and with regex:
Ctrl + h to bring up the find replace dialog.
In the Find what:
text box include your regex: .*help.*\r?\n
(where the \r
is optional in case the file doesn't have Windows line endings).
Leave the Replace with:
text box empty.
Make sure the Regular expression radio button in the Search Mode area is selected. Then click Replace All
and voila! All lines containing your search term help
have been removed.
You can have a javascript variable which stores the number of checkboxes that are emitted, i.e in the <head>
of the page:
<script type="text/javascript">
var num_cboxes=<?php echo $number_of_checkboxes;?>;
</script>
So if there are 10 checkboxes, starting from user_group-1
to user_group-10
, in the javascript code you would get their value in this way:
var values=new Array();
for (x=1; x<=num_cboxes; x++)
{
values[x]=$("#user_group-" + x).val();
}
If you are using Android Studio-
changing com.myapp
to com.mycompany.myapp
create a new package hierarchy com.mycompany.myapp under android/app/src/main/java
Copy all classes from com.myapp
to com.mycompany.myapp
using Android studio GUI
Android studio will take care of putting suitable package name for all copied classes. This is useful if you have some custom modules and don't want to manually replace in all the .java files.
Update android/app/src/main/AndroidManifest.xml
and android/app/build.gradle
(replace com.myapp
to com.mycompany.myapp
Sync the project (gradle build)
You don't want to lose the user scaling option if you can help it. I like this JS solution from here.
<script type="text/javascript">
(function(doc) {
var addEvent = 'addEventListener',
type = 'gesturestart',
qsa = 'querySelectorAll',
scales = [1, 1],
meta = qsa in doc ? doc[qsa]('meta[name=viewport]') : [];
function fix() {
meta.content = 'width=device-width,minimum-scale=' + scales[0] + ',maximum-scale=' + scales[1];
doc.removeEventListener(type, fix, true);
}
if ((meta = meta[meta.length - 1]) && addEvent in doc) {
fix();
scales = [.25, 1.6];
doc[addEvent](type, fix, true);
}
}(document));
</script>
Or you could use the os.path.walk function, which does more work for you than just os.walk:
A stupid example:
def walk_func(blah_args, dirname,names):
print ' '.join(('In ',dirname,', called with ',blah_args))
for name in names:
print 'Walked on ' + name
if __name__ == '__main__':
import os.path
directory = './'
arguments = '[args go here]'
os.path.walk(directory,walk_func,arguments)
A really easy way to do it is to create an ODBC link in EXCEL and run SP_WHO2 from there.
You can Refresh whenever you like and because it's EXCEL everything can be manipulated easily!
For completeness, here is how you can get the Id
in Xamarin.Android
and C#:
var id = Settings.Secure.GetString(ContentResolver, Settings.Secure.AndroidId);
Or if you are not within an Activity
:
var id = Settings.Secure.GetString(context.ContentResolver, Settings.Secure.AndroidId);
Where context
is the passed in context.
Since beta.16 the parameters are not passed as array to the transform()
method anymore but instead as individual parameters:
{{ myData | date:'fullDate':'arg1':'arg2' }}
export class DatePipe implements PipeTransform {
transform(value:any, arg1:any, arg2:any):any {
...
}
https://github.com/angular/angular/blob/master/CHANGELOG.md#200-beta16-2016-04-26
pipes now take a variable number of arguments, and not an array that contains all arguments.
The problem may be that ssh is trying to connect to all the different IPs that www.google.com
resolves to. For example on my machine:
# ssh -v -o ConnectTimeout=1 -o ConnectionAttempts=1 www.google.com
OpenSSH_5.9p1, OpenSSL 0.9.8t 18 Jan 2012
debug1: Connecting to www.google.com [173.194.43.20] port 22.
debug1: connect to address 173.194.43.20 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.19] port 22.
debug1: connect to address 173.194.43.19 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.18] port 22.
debug1: connect to address 173.194.43.18 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.17] port 22.
debug1: connect to address 173.194.43.17 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.16] port 22.
debug1: connect to address 173.194.43.16 port 22: Connection timed out
ssh: connect to host www.google.com port 22: Connection timed out
If I run it with a specific IP, it returns much faster.
EDIT: I've timed it (with time
) and the results are:
One way to accomplish that is to order you records and limit to 1. For example if you have the following table ('data').
id | user | price
-------------------
1 | me | 40.23
2 | me | 10.23
Try the following sql query
select * from data where user='me' order by id desc limit 1
Instead of handcranking your models try using something like the Json2csharp.com website. Paste In an example JSON response, the fuller the better and then pull in the resultant generated classes. This, at least, takes away some moving parts, will get you the shape of the JSON in csharp giving the serialiser an easier time and you shouldnt have to add attributes.
Just get it working and then make amendments to your class names, to conform to your naming conventions, and add in attributes later.
EDIT: Ok after a little messing around I have successfully deserialised the result into a List of Job (I used Json2csharp.com to create the class for me)
public class Job
{
public string id { get; set; }
public string position_title { get; set; }
public string organization_name { get; set; }
public string rate_interval_code { get; set; }
public int minimum { get; set; }
public int maximum { get; set; }
public string start_date { get; set; }
public string end_date { get; set; }
public List<string> locations { get; set; }
public string url { get; set; }
}
And an edit to your code:
List<Job> model = null;
var client = new HttpClient();
var task = client.GetAsync("http://api.usa.gov/jobs/search.json?query=nursing+jobs")
.ContinueWith((taskwithresponse) =>
{
var response = taskwithresponse.Result;
var jsonString = response.Content.ReadAsStringAsync();
jsonString.Wait();
model = JsonConvert.DeserializeObject<List<Job>>(jsonString.Result);
});
task.Wait();
This means you can get rid of your containing object. Its worth noting that this isn't a Task related issue but rather a deserialisation issue.
EDIT 2:
There is a way to take a JSON object and generate classes in Visual Studio. Simply copy the JSON of choice and then Edit> Paste Special > Paste JSON as Classes. A whole page is devoted to this here:
http://blog.codeinside.eu/2014/09/08/Visual-Studio-2013-Paste-Special-JSON-And-Xml/
You should define the __unicode__
method on your model, and the template will call it automatically when you reference the instance.
In Windows 7 and later, this will do the trick for you
The menu item Copy as Path is not available in Windows XP.
you can also use vmware-mount from VMwares VDDK (Virtual Disk Development Kit): http://communities.vmware.com/community/vmtn/developer/forums/vddk
this allows you to mount VMDK files as disk drives in windows or linux
Use .net:
[System.IO.Path]::GetFileName("c:\foo.txt")
returns foo.txt
.
[System.IO.Path]::GetFileNameWithoutExtension("c:\foo.txt")
returns foo
One way, using hstack, is:
b = np.hstack((a, np.zeros((a.shape[0], 1), dtype=a.dtype)))
Tried the following code, worked OK on IE6 on WinXP Pro SP3.
function Resize(imgId)
{
var img = document.getElementById(imgId);
var w = img.width, h = img.height;
w /= 2; h /= 2;
img.width = w; img.height = h;
}
Also OK in FF3 and Opera 9.26.
I searched for multiple options to get my git reset to specific commit, but most of them aren't so satisfactory.
I generally use this to reset the git to the specific commit in source tree.
select commit to reset on sourcetree.
In dropdowns select the active branch , first Parent Only
And right click on "Reset branch to this commit" and select hard reset option (soft, mixed and hard)
and then go to terminal git push -f
You should be all set!
From the respective W3 specifications —which happen to be pretty unclear due to a lack of context— one can deduce the following:
word-break: break-all
is for breaking up foreign, non-CJK (say Western) words in CJK (Chinese, Japanese or Korean) character writings.word-wrap: break-word
is for word breaking in a non-mixed (let us say solely Western) language.At least, these were W3's intentions. What actually happened was a major cock-up with browser incompatibilities as a result. Here is an excellent write-up of the various problems involved.
The following code snippet may serve as a summary of how to achieve word wrapping using CSS in a cross browser environment:
-ms-word-break: break-all;
word-break: break-all;
/* Non standard for webkit */
word-break: break-word;
-webkit-hyphens: auto;
-moz-hyphens: auto;
-ms-hyphens: auto;
hyphens: auto;
Ran into the same problem on Laravel 4 trying to send e-mail using SSL encryption.
Having WAMPServer 2.2 on Windows 7 64bit I only enabled php_openssl in the php.ini, restarted WAMPServer and worked flawlessly.
Did following:
POCOs(Plain old CLR objects) are simply entities of your Domain. Normally when we use entity framework the entities are generated automatically for you. This is great but unfortunately these entities are interspersed with database access functionality which is clearly against the SOC (Separation of concern). POCOs are simple entities without any data access functionality but still gives the capabilities all EntityObject functionalities like
Here is a good start for this
You can also generate POCOs so easily from your existing Entity framework project using Code generators.
all: program
program.o: program.h headers.h
is enough. the rest is implicit
For the first part of the question, I just do a dump of both and diff them. Not sure about mysql, but postgres pg_dump has a command to just dump the schema without the table contents, so you can see if you've changed the schema any.
Each type of integer has a different range of storage capacity
Type Capacity
Int16 -- (-32,768 to +32,767)
Int32 -- (-2,147,483,648 to +2,147,483,647)
Int64 -- (-9,223,372,036,854,775,808 to +9,223,372,036,854,775,807)
As stated by James Sutherland in his answer:
int
andInt32
are indeed synonymous;int
will be a little more familiar looking,Int32
makes the 32-bitness more explicit to those reading your code. I would be inclined to use int where I just need 'an integer',Int32
where the size is important (cryptographic code, structures) so future maintainers will know it's safe to enlarge anint
if appropriate, but should take care changingInt32
variables in the same way.The resulting code will be identical: the difference is purely one of readability or code appearance.
This is a part from a REST-Service I´ve written recently.
var select = $("#productSelect")
for (var prop in data) {
var option = document.createElement('option');
option.innerHTML = data[prop].ProduktName
option.value = data[prop].ProduktName;
select.append(option)
}
The reason why im posting this is because appendChild() wasn´t working in my case so I decided to put up another possibility that works aswell.
The core of this is the replace
call. So far, I don't think any of the proposed solutions handle all of the following cases:
1000 => '1,000'
'1000' => '1,000'
10000.00 => '10,000.00'
'01000.00 => '1,000.00'
'1000.00000' => '1,000.00000'
-
or +
: '-1000.0000' => '-1,000.000'
'1000k' => '1000k'
The following function does all of the above.
addCommas = function(input){
// If the regex doesn't match, `replace` returns the string unmodified
return (input.toString()).replace(
// Each parentheses group (or 'capture') in this regex becomes an argument
// to the function; in this case, every argument after 'match'
/^([-+]?)(0?)(\d+)(.?)(\d+)$/g, function(match, sign, zeros, before, decimal, after) {
// Less obtrusive than adding 'reverse' method on all strings
var reverseString = function(string) { return string.split('').reverse().join(''); };
// Insert commas every three characters from the right
var insertCommas = function(string) {
// Reverse, because it's easier to do things from the left
var reversed = reverseString(string);
// Add commas every three characters
var reversedWithCommas = reversed.match(/.{1,3}/g).join(',');
// Reverse again (back to normal)
return reverseString(reversedWithCommas);
};
// If there was no decimal, the last capture grabs the final digit, so
// we have to put it back together with the 'before' substring
return sign + (decimal ? insertCommas(before) + decimal + after : insertCommas(before + after));
}
);
};
You could use it in a jQuery plugin like this:
$.fn.addCommas = function() {
$(this).each(function(){
$(this).text(addCommas($(this).text()));
});
};
STEP 1 :Click on the "Help"and click on "Edit Keyboard Shortcut" STEP1-screenshot
STEP 2 :Add the Shortcut you desire to the "Clear Cell" field STEP2-screenshot
The problem is that you're (probably) trying to plot a vector that consists exclusively of missing (NA
) values. Here's an example:
> x=rep(NA,100)
> y=rnorm(100)
> plot(x,y)
Error in plot.window(...) : need finite 'xlim' values
In addition: Warning messages:
1: In min(x) : no non-missing arguments to min; returning Inf
2: In max(x) : no non-missing arguments to max; returning -Inf
In your example this means that in your line plot(costs,pseudor2,type="l")
, costs
is completely NA
. You have to figure out why this is, but that's the explanation of your error.
From comments:
Scott C Wilson: Another possible cause of this message (not in this case, but in others) is attempting to use character values as X or Y data. You can use the class function to check your x and Y values to be sure if you think this might be your issue.
stevec: Here is a quick and easy solution to that problem (basically wrap x in as.factor(x)
)
Dim obj : Set obj = CreateObject("Scripting.FileSystemObject")
Dim outFile : Set outFile = obj.CreateTextFile("in.txt")
Dim inFile: Set inFile = obj.OpenTextFile("out.txt")
' Read file
Dim strRetVal : strRetVal = inFile.ReadAll
inFile.Close
' Write file
outFile.write (strRetVal)
outFile.Close
Delete your bin and obj subfolders to remove a load of incorrect reference then use windows to search for old name.
Edit any code or xml files found and rebuild, should be ok now.
$.fn.textWidth = function(){
var self = $(this),
children = self.children(),
calculator = $('<span style="display: inline-block;" />'),
width;
children.wrap(calculator);
width = children.parent().width(); // parent = the calculator wrapper
children.unwrap();
return width;
};
Basically an improvement over Rune's, that doesn't use .html
so lightly
-split outputs an array, and you can save it to a variable like this:
$a = -split 'Once upon a time'
$a[0]
Once
Another cute thing, you can have arrays on both sides of an assignment statement:
$a,$b,$c = -split 'Once upon a'
$c
a
public class GetObjectsComparison
{
public object FirstObject, SecondObject;
public BindingFlags BindingFlagsConditions= BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
}
public struct SetObjectsComparison
{
public FieldInfo SecondObjectFieldInfo;
public dynamic FirstObjectFieldInfoValue, SecondObjectFieldInfoValue;
public bool ErrorFound;
public GetObjectsComparison GetObjectsComparison;
}
private static bool ObjectsComparison(GetObjectsComparison GetObjectsComparison)
{
GetObjectsComparison FunctionGet = GetObjectsComparison;
SetObjectsComparison FunctionSet = new SetObjectsComparison();
if (FunctionSet.ErrorFound==false)
foreach (FieldInfo FirstObjectFieldInfo in FunctionGet.FirstObject.GetType().GetFields(FunctionGet.BindingFlagsConditions))
{
FunctionSet.SecondObjectFieldInfo =
FunctionGet.SecondObject.GetType().GetField(FirstObjectFieldInfo.Name, FunctionGet.BindingFlagsConditions);
FunctionSet.FirstObjectFieldInfoValue = FirstObjectFieldInfo.GetValue(FunctionGet.FirstObject);
FunctionSet.SecondObjectFieldInfoValue = FunctionSet.SecondObjectFieldInfo.GetValue(FunctionGet.SecondObject);
if (FirstObjectFieldInfo.FieldType.IsNested)
{
FunctionSet.GetObjectsComparison =
new GetObjectsComparison()
{
FirstObject = FunctionSet.FirstObjectFieldInfoValue
,
SecondObject = FunctionSet.SecondObjectFieldInfoValue
};
if (!ObjectsComparison(FunctionSet.GetObjectsComparison))
{
FunctionSet.ErrorFound = true;
break;
}
}
else if (FunctionSet.FirstObjectFieldInfoValue != FunctionSet.SecondObjectFieldInfoValue)
{
FunctionSet.ErrorFound = true;
break;
}
}
return !FunctionSet.ErrorFound;
}
If you are looking for Angular (v2+, currently version 8), try this answer or the official guide.
I have rewritten your JS fiddle here: http://jsfiddle.net/YGQT9/
<div ng-app="myApp">
<form name="saveTemplateData" action="#" ng-controller="FormCtrl" ng-submit="submitForm()">
First name: <br/><input type="text" name="form.firstname">
<br/><br/>
Email Address: <br/><input type="text" ng-model="form.emailaddress">
<br/><br/>
<textarea rows="3" cols="25">
Describe your reason for submitting this form ...
</textarea>
<br/>
<input type="radio" ng-model="form.gender" value="female" />Female
<input type="radio" ng-model="form.gender" value="male" />Male
<br/><br/>
<input type="checkbox" ng-model="form.member" value="true"/> Already a member
<input type="checkbox" ng-model="form.member" value="false"/> Not a member
<br/>
<input type="file" ng-model="form.file_profile" id="file_profile">
<br/>
<input type="file" ng-model="form.file_avatar" id="file_avatar">
<br/><br/>
<input type="submit">
</form>
</div>
Here I'm using lots of angular directives(ng-controller
, ng-model
, ng-submit
) where you were using basic html form submission.
Normally all alternatives to "The angular way" work, but form submission is intercepted and cancelled by Angular to allow you to manipulate the data before submission
BUT the JSFiddle won't work properly as it doesn't allow any type of ajax/http post/get so you will have to run it locally.
For general advice on angular form submission see the cookbook examples
UPDATE The cookbook is gone. Instead have a look at the 1.x guide for for form submission
The cookbook for angular has lots of sample code which will help as the docs aren't very user friendly.
Angularjs changes your entire web development process, don't try doing things the way you are used to with JQuery or regular html/js, but for everything you do take a look around for some sample code, as there is almost always an angular alternative.
Instead of using a std::string, you could use a std::wstring.
EDIT: Sorry this is not more explanatory, but I have to run.
Use std::wstring::c_str()
request.input("name", sql.Decimal, 155.33) // decimal(18, 0)
request.input("name", sql.Decimal(10), 155.33) // decimal(10, 0)
request.input("name", sql.Decimal(10, 2), 155.33) // decimal(10, 2)
With @Query , we can use pagination as well where you need to pass object of Pageable class at end of JPA method
For example:
Pageable pageableRequest = new PageRequest(page, size, Sort.Direction.DESC, rollNo);
Where,
page = index of page (index start from zero)
size = No. of records
Sort.Direction = Sorting as per rollNo
rollNo = Field in User class
UserRepository repo
repo.findByFirstname("John", pageableRequest);
public interface UserRepository extends JpaRepository<User, Long> {
@Query(value = "SELECT * FROM USER WHERE FIRSTNAME = :firstname)
Page<User> findByLastname(@Param("firstname") String firstname, Pageable pageable);
}
A much shorter version for getting a list of all subclasses:
from itertools import chain
def subclasses(cls):
return list(
chain.from_iterable(
[list(chain.from_iterable([[x], subclasses(x)])) for x in cls.__subclasses__()]
)
)
I need to go next only to input and select, and element have to be focusable. This script works better for me:
$('body').on('keydown', 'input, select', function(e) {
if (e.key === "Enter") {
var self = $(this), form = self.parents('form:eq(0)'), focusable, next;
focusable = form.find('input,select,textarea').filter(':visible');
next = focusable.eq(focusable.index(this)+1);
if (next.length) {
next.focus();
} else {
form.submit();
}
return false;
}
});
Maybe it helps someone.
Running:
npm install
from inside your app directory (i.e. where package.json is located) will install the dependencies for your app, rather than install it as a module, as described here. These will be placed in ./node_modules relative to your package.json file (it's actually slightly more complex than this, so check the npm docs here).
You are free to move the node_modules dir to the parent dir of your app if you want, because node's 'require' mechanism understands this. However, if you want to update your app's dependencies with install/update, npm will not see the relocated 'node_modules' and will instead create a new dir, again relative to package.json.
To prevent this, just create a symlink to the relocated node_modules from your app dir:
ln -s ../node_modules node_modules
I've found that using the Moment.js library with some of the concepts described here (comparing Jan to June) works very well.
This simple function will return whether the timezone that the user is in observes Daylight Saving Time:
function HasDST() {
return moment([2017, 1, 1]).isDST() != moment([2017, 6, 1]).isDST();
}
A simple way to check that this works (on Windows) is to change your timezone to a non DST zone, for example Arizona will return false, whereas EST or PST will return true.
In my case the problem was that the logs folder did not exist resp. the error.log file in this folder.
try the following:
myPictureBox.Image = global::mynamespace.Properties.Resources.photo1;
and replace namespace with your project namespace
This script helps you to switch over from a Parent window to a Child window and back cntrl to Parent window
String parentWindow = driver.getWindowHandle();
Set<String> handles = driver.getWindowHandles();
for(String windowHandle : handles)
{
if(!windowHandle.equals(parentWindow))
{
driver.switchTo().window(windowHandle);
<!--Perform your operation here for new window-->
driver.close(); //closing child window
driver.switchTo().window(parentWindow); //cntrl to parent window
}
}
Goto the Solution properties -> on Build right side you see the startup project type. here you need to select the console appication/windows appication.
you may want to put a break; after your location:
header("HTTP/1.1 301 Moved Permanently");
header('Location: '. $YourArrayName["YourURL"] );
break;
Monkey patching is reopening the existing classes or methods in class at runtime and changing the behavior, which should be used cautiously, or you should use it only when you really need to.
As Python is a dynamic programming language, Classes are mutable so you can reopen them and modify or even replace them.
I realize this post is old, but there's a more compact approach that is slightly different than what was asked, but may be a very helpful alternative. You can essentially declare the function in-line when calling the method (Foo
's save()
in this case). It would look something like this:
class Foo {
save(callback: (n: number) => any) : void {
callback(42)
}
multipleCallbacks(firstCallback: (s: string) => void, secondCallback: (b: boolean) => boolean): void {
firstCallback("hello world")
let result: boolean = secondCallback(true)
console.log("Resulting boolean: " + result)
}
}
var foo = new Foo()
// Single callback example.
// Just like with @RyanCavanaugh's approach, ensure the parameter(s) and return
// types match the declared types above in the `save()` method definition.
foo.save((newNumber: number) => {
console.log("Some number: " + newNumber)
// This is optional, since "any" is the declared return type.
return newNumber
})
// Multiple callbacks example.
// Each call is on a separate line for clarity.
// Note that `firstCallback()` has a void return type, while the second is boolean.
foo.multipleCallbacks(
(s: string) => {
console.log("Some string: " + s)
},
(b: boolean) => {
console.log("Some boolean: " + b)
let result = b && false
return result
}
)
The multipleCallback()
approach is very useful for things like network calls that may succeed or fail. Again assuming a network call example, when multipleCallbacks()
is called, behavior for both a success and failure can be defined in one spot, which lends itself to greater clarity for future code readers.
Generally, in my experience, this approach lends itself to being more concise, less clutter, and greater clarity overall.
Good luck all!
It sounds like you already know the unique column names. If that's the case, then df = df['Time', 'Time Relative', 'N2']
would work.
If not, your solution should work:
In [101]: vals = np.random.randint(0,20, (4,3))
vals
Out[101]:
array([[ 3, 13, 0],
[ 1, 15, 14],
[14, 19, 14],
[19, 5, 1]])
In [106]: df = pd.DataFrame(np.hstack([vals, vals]), columns=['Time', 'H1', 'N2', 'Time Relative', 'N2', 'Time'] )
df
Out[106]:
Time H1 N2 Time Relative N2 Time
0 3 13 0 3 13 0
1 1 15 14 1 15 14
2 14 19 14 14 19 14
3 19 5 1 19 5 1
In [107]: df.T.drop_duplicates().T
Out[107]:
Time H1 N2
0 3 13 0
1 1 15 14
2 14 19 14
3 19 5 1
You probably have something specific to your data that's messing it up. We could give more help if there's more details you could give us about the data.
Edit: Like Andy said, the problem is probably with the duplicate column titles.
For a sample table file 'dummy.csv' I made up:
Time H1 N2 Time N2 Time Relative
3 13 13 3 13 0
1 15 15 1 15 14
14 19 19 14 19 14
19 5 5 19 5 1
using read_table
gives unique columns and works properly:
In [151]: df2 = pd.read_table('dummy.csv')
df2
Out[151]:
Time H1 N2 Time.1 N2.1 Time Relative
0 3 13 13 3 13 0
1 1 15 15 1 15 14
2 14 19 19 14 19 14
3 19 5 5 19 5 1
In [152]: df2.T.drop_duplicates().T
Out[152]:
Time H1 Time Relative
0 3 13 0
1 1 15 14
2 14 19 14
3 19 5 1
If your version doesn't let your, you can hack together a solution to make them unique:
In [169]: df2 = pd.read_table('dummy.csv', header=None)
df2
Out[169]:
0 1 2 3 4 5
0 Time H1 N2 Time N2 Time Relative
1 3 13 13 3 13 0
2 1 15 15 1 15 14
3 14 19 19 14 19 14
4 19 5 5 19 5 1
In [171]: from collections import defaultdict
col_counts = defaultdict(int)
col_ix = df2.first_valid_index()
In [172]: cols = []
for col in df2.ix[col_ix]:
cnt = col_counts[col]
col_counts[col] += 1
suf = '_' + str(cnt) if cnt else ''
cols.append(col + suf)
cols
Out[172]:
['Time', 'H1', 'N2', 'Time_1', 'N2_1', 'Time Relative']
In [174]: df2.columns = cols
df2 = df2.drop([col_ix])
In [177]: df2
Out[177]:
Time H1 N2 Time_1 N2_1 Time Relative
1 3 13 13 3 13 0
2 1 15 15 1 15 14
3 14 19 19 14 19 14
4 19 5 5 19 5 1
In [178]: df2.T.drop_duplicates().T
Out[178]:
Time H1 Time Relative
1 3 13 0
2 1 15 14
3 14 19 14
4 19 5 1
From the command line issue
mongo --quiet --eval "printjson(db.adminCommand('listDatabases'))"
which gives output
{
"databases" : [
{
"name" : "admin",
"sizeOnDisk" : 978944,
"empty" : false
},
{
"name" : "local",
"sizeOnDisk" : 77824,
"empty" : false
},
{
"name" : "meteor",
"sizeOnDisk" : 778240,
"empty" : false
}
],
"totalSize" : 1835008,
"ok" : 1
}
RUN
and ENTRYPOINT
are two different ways to execute a script.
RUN
means it creates an intermediate container, runs the script and freeze the new state of that container in a new intermediate image. The script won't be run after that: your final image is supposed to reflect the result of that script.
ENTRYPOINT
means your image (which has not executed the script yet) will create a container, and runs that script.
In both cases, the script needs to be added, and a RUN chmod +x /bootstrap.sh
is a good idea.
It should also start with a shebang (like #!/bin/sh
)
Considering your script (bootstrap.sh
: a couple of git config --global
commands), it would be best to RUN
that script once in your Dockerfile
, but making sure to use the right user (the global git config
file is %HOME%/.gitconfig
, which by default is the /root
one)
Add to your Dockerfile:
RUN /bootstrap.sh
Then, when running a container, check the content of /root/.gitconfig
to confirm the script was run.
On my projects i give all rows the class "borders" which I want it to display more like a table with even borders. Giving each child element a border on the bottom and right and the first element of each row a left border will make all of your boxes have an even border:
First give all of the rows children a border on the right and bottom
.borders div{
border-right:1px solid #999;
border-bottom:1px solid #999;
}
Next give the first child of each or a left border
.borders div:first-child{
border-left:
1px solid #999;
}
Last make sure to clear the borders for their child elements
.borders div > div{
border:0;
}
HTML:
<div class="row borders">
<div class="col-xs-5 col-md-2">Email</div>
<div class="col-xs-7 col-md-4">[email protected]</div>
<div class="col-xs-5 col-md-2">Phone</div>
<div class="col-xs-7 col-md-4">555-123-4567</div>
</div>
The first argument denotes placeholders for the variables / parameters that follow.
For example, %s
indicates that you're expecting a String
to be your first print parameter.
Java also has a printf
, which is very similar.
WebDav-SchmebDav.. ..make sure you create the url with the ID correctly. Don't send it like http://www.fluff.com/api/Fluff?id=MyID, send it like http://www.fluff.com/api/Fluff/MyID.
Eg.
PUT http://www.fluff.com/api/Fluff/123 HTTP/1.1
Host: www.fluff.com
Content-Length: 11
{"Data":"1"}
This was busting my balls for a small eternity, total embarrassment.
The parent div (I assume the outermost div) is display: block
and will fill up all available area of its container (in this case, the body) that it can. Use a different display type -- inline-block
is probably what you are going for:
Instead of choosing Restore Database..., select Restore Files and Filegroups...
Then enter a database name, select your .bak file path as the source, check the restore checkbox, and click Ok. If the .bak file is valid, it will work.
(The SQL Server restore option names are not intuitive for what should a very simple task.)
Or you can use this one http://plugins.jquery.com/project/parseQuery, it's smaller than most (minified 449 bytes), returns an object representing name-value pairs.
This is for windows:
For example, I have a folder named "mygrapher" on my desktop. Inside, there's folders called "calculation" and "graphing" that contain Python files that my main file "grapherMain.py" needs. Also, "grapherMain.py" is stored in "graphing". To run everything without moving files, I can make a batch script. Let's call this batch file "rungraph.bat".
@ECHO OFF
setlocal
set PYTHONPATH=%cd%\grapher;%cd%\calculation
python %cd%\grapher\grapherMain.py
endlocal
This script is located in "mygrapher". To run things, I would get into my command prompt, then do:
>cd Desktop\mygrapher (this navigates into the "mygrapher" folder)
>rungraph.bat (this executes the batch file)
Suppose logical address space is **32 bit so total possible logical entries will be 2^32 and other hand suppose each page size is 4 byte then size of one page is *2^2*2^10=2^12...* now we know that no. of pages in page table is pages=total possible logical address entries/page size so pages=2^32/2^12 =2^20 Now suppose that each entry in page table takes 4 bytes then total size of page table in *physical memory will be=2^2*2^20=2^22=4mb***
BTW: Hard drive manufacturers don't count as authorities on this one!
Oh, yes they do (and the definition they assume from the S.I. is the correct one). On a related issue, see this post on CodingHorror.
Change your FirstyActivity to:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn_go=(Button)findViewById(R.id.YOUR_BUTTON_ID);
btn_go.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("clicks","You Clicked B1");
Intent i=new Intent(
MainActivity.this,
MainActivity2.class);
startActivity(i);
}
}
});
}
Hope it will help you.
As of early 2013, the ICU project, maintained by IBM, is a pretty good answer to this.
ICU is a "complete, portable Unicode library that closely tracks industry standards." For the specific problem of string comparison, the Collation object does what you want.
The Mozilla Project adopted ICU for internationalization in Firefox in mid-2012; you can track the engineering discussion, including issues of build systems and data file size, here:
Erland Sommarskog has maintained the authoritative answer to this question for the last 16 years: Arrays and Lists in SQL Server.
There are at least a dozen ways to pass an array or list to a query; each has their own unique pros and cons.
I really can't recommend enough to read the article to learn about the tradeoffs among all these options.
If you're looking to count the whole string this can works.
stri_count="If you're looking to count the whole string this can works"
print(len(stri_count))
add this dependency https://mvnrepository.com/artifact/org.slf4j/slf4j-api/1.7.28
will help fix error
Note that URI encoding is good for the query part, it's not good for the domain. The domain gets encoded using punycode. You need a library like URI.js to convert between a URI and IRI (Internationalized Resource Identifier).
This is correct if you plan on using the string later as a query string:
> encodeURIComponent("http://examplé.org/rosé?rosé=rosé")
'http%3A%2F%2Fexampl%C3%A9.org%2Fros%C3%A9%3Fros%C3%A9%3Dros%C3%A9'
If you don't want ASCII characters like /
, :
and ?
to be escaped, use encodeURI
instead:
> encodeURI("http://examplé.org/rosé?rosé=rosé")
'http://exampl%C3%A9.org/ros%C3%A9?ros%C3%A9=ros%C3%A9'
However, for other use-cases, you might need uri-js instead:
> var URI = require("uri-js");
undefined
> URI.serialize(URI.parse("http://examplé.org/rosé?rosé=rosé"))
'http://xn--exampl-gva.org/ros%C3%A9?ros%C3%A9=ros%C3%A9'
As Filburt says; but also note that it's usually better to write
test="not(Count = 'N/A')"
If there's exactly one Count element they mean the same thing, but if there's no Count, or if there are several, then the meanings are different.
6 YEARS LATER
Since this answer seems to have become popular, but may be a little cryptic to some readers, let me expand it.
The "=" and "!=" operator in XPath can compare two sets of values. In general, if A and B are sets of values, then "=" returns true if there is any pair of values from A and B that are equal, while "!=" returns true if there is any pair that are unequal.
In the common case where A selects zero-or-one nodes, and B is a constant (say "NA"), this means that not(A = "NA")
returns true if A is either absent, or has a value not equal to "NA". By contrast, A != "NA"
returns true if A is present and not equal to "NA". Usually you want the "absent" case to be treated as "not equal", which means that not(A = "NA")
is the appropriate formulation.
Shorter example using http.get:
require('http').get('http://httpbin.org/ip', (res) => {
res.setEncoding('utf8');
res.on('data', function (body) {
console.log(body);
});
});
Updated for iOS 8.0
Since iOS 8.0, you will need to use UIAlertController as the following:
-(void)alertMessage:(NSString*)message
{
UIAlertController* alert = [UIAlertController
alertControllerWithTitle:@"Alert"
message:message
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction
actionWithTitle:@"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
}
Where self in my example is a UIViewController, which implements "presentViewController" method for a popup.
David
For those looking to debug gradle dependencies in react-native
projects, the command is (executed from projectname/android
)
./gradlew app:dependencies --configuration compile
Using strcat(buffer
,"Your new string...here
"), as an option.
You could use tabs instead of spaces between columns, and/or set maximum size for a column in format strings ...
You can specify a default value for the optional argument with something that would never passed to the function and check it with the is
operator:
class _NO_DEFAULT:
def __repr__(self):return "<no default>"
_NO_DEFAULT = _NO_DEFAULT()
def func(optional= _NO_DEFAULT):
if optional is _NO_DEFAULT:
print("the optional argument was not passed")
else:
print("the optional argument was:",optional)
then as long as you do not do func(_NO_DEFAULT)
you can be accurately detect whether the argument was passed or not, and unlike the accepted answer you don't have to worry about side effects of ** notation:
# these two work the same as using **
func()
func(optional=1)
# the optional argument can be positional or keyword unlike using **
func(1)
#this correctly raises an error where as it would need to be explicitly checked when using **
func(invalid_arg=7)
The browser extension uBlock’s setting “Block remote fonts” will cause this error. (Note: Grammarly was not the problem, at least for me.)
Usually this isn’t a problem. When a remote font is blocked, you fall back to some other font and a console warning saying “ERR_BLOCKED_BY_CLIENT” is issued. However, this can be a serious problem when a site uses Font Awesome, because the icons show as boxes.
There’s not much a website can do about fixing this (but you can prevent it from being too bad by e.g. labeling font-based icons). Changing the CSP (or adding one) will not fix it. Serving the fonts from your website (and not a CDN) will not fix it either.
The uBlock user, on the other hand, has the power to fix this by doing one of the following:
build gradle:
testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0"
code:
interface MyCallback {
fun someMethod(value: String)
}
class MyTestableManager(private val callback: MyCallback){
fun perform(){
callback.someMethod("first")
callback.someMethod("second")
callback.someMethod("third")
}
}
test:
import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.mock
...
val callback: MyCallback = mock()
val manager = MyTestableManager(callback)
manager.perform()
val captor: KArgumentCaptor<String> = com.nhaarman.mockitokotlin2.argumentCaptor<String>()
verify(callback, times(3)).someMethod(captor.capture())
assertTrue(captor.allValues[0] == "first")
assertTrue(captor.allValues[1] == "second")
assertTrue(captor.allValues[2] == "third")
If you just have included a layout file at the beginning of onCreate()
inside setContentView
and want to get this layout to add new elements programmatically try this:
ViewGroup linearLayout = (ViewGroup) findViewById(R.id.linearLayoutID);
then you can create a new Button
for example and just add it:
Button bt = new Button(this);
bt.setText("A Button");
bt.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
linerLayout.addView(bt);
<form>
<label for="company">
<span>Company Name</span>
<input type="text" id="company" />
</label>
<label for="contact">
<span>Contact Name</span>
<input type="text" id="contact" />
</label>
</form>
label { width: 200px; float: left; margin: 0 20px 0 0; }
span { display: block; margin: 0 0 3px; font-size: 1.2em; font-weight: bold; }
input { width: 200px; border: 1px solid #000; padding: 5px; }
Illustrated at http://jsfiddle.net/H3y8j/
ip route get 8.8.8.8| grep src| sed 's/.*src \(.* \)/\1/g'|cut -f1 -d ' '
var months = [
{
"updated_at" : "2012-01-01T06:25:24Z",
"foo" : "bar"
},
{
"updated_at" : "2012-01-09T11:25:13Z",
"foo" : "bar"
},
{
"updated_at" : "2012-01-05T04:13:24Z",
"foo" : "bar"
}];
months.sort((a, b)=>{
var keyA = new Date(a.updated_at),
keyB = new Date(b.updated_at);
// Compare the 2 dates
if(keyA < keyB) return -1;
if(keyA > keyB) return 1;
return 0;
});
console.log(months);
Make sure you are using the latest version of JQuery. We were facing this error for JQuery 1.10.2 and the error got resolved after using JQuery 1.11.1
In case someone makes the same silly mistake I did...
I was getting this error because in renaming my source file, I accidentally removed the.
from the filename and so the compiler treated the file as a plain text file and not as source to compile.
so I meant to rename the file to
MyProtocol.swift
but accidently named it
MyProtocolswift
It's a simple mistake, but it was not readily obvious that this is what was going on.
I needed clean and lightweight solution (so no jQuery and alike), which will look exactly like plain HTML, would also continue working when only plain HTML is preset (so javascript will only enhance it), and which will allow searching by starting letters (including national UTF-8 letters) if possible where it does not add extra weight. It also must work fast on very slow browsers (think rPi - so preferably no javascript executing after page load).
In firefox it uses CSS identing and thus allow searching by letters, and in other browsers it will use
prepending (but there it does not support quick search by letters). Anyway, I'm quite happy with results.
You can try it in action here
It goes like this:
CSS:
.i0 { }
.i1 { margin-left: 1em; }
.i2 { margin-left: 2em; }
.i3 { margin-left: 3em; }
.i4 { margin-left: 4em; }
.i5 { margin-left: 5em; }
HTML (class "i1", "i2" etc denote identation level):
<form action="/filter/" method="get">
<select name="gdje" id="gdje">
<option value=1 class="i0">Svugdje</option>
<option value=177 class="i1">Bosna i Hercegovina</option>
<option value=190 class="i2">Babin Do</option>
<option value=258 class="i2">Banja Luka</option>
<option value=181 class="i2">Tuzla</option>
<option value=307 class="i1">Crna Gora</option>
<option value=308 class="i2">Podgorica</option>
<option value=2 SELECTED class="i1">Hrvatska</option>
<option value=5 class="i2">Bjelovarsko-bilogorska županija</option>
<option value=147 class="i3">Bjelovar</option>
<option value=79 class="i3">Daruvar</option>
<option value=94 class="i3">Garešnica</option>
<option value=329 class="i3">Grubišno Polje</option>
<option value=368 class="i3">Cazma</option>
<option value=6 class="i2">Brodsko-posavska županija</option>
<option value=342 class="i3">Gornji Bogicevci</option>
<option value=158 class="i3">Klakar</option>
<option value=140 class="i3">Nova Gradiška</option>
</select>
</form>
<script>
<!--
window.onload = loadFilter;
// -->
</script>
JavaScript:
function loadFilter() {
'use strict';
// indents all options depending on "i" CSS class
function add_nbsp() {
var opt = document.getElementsByTagName("option");
for (var i = 0; i < opt.length; i++) {
if (opt[i].className[0] === 'i') {
opt[i].innerHTML = Array(3*opt[i].className[1]+1).join(" ") + opt[i].innerHTML; // this means " " x (3*$indent)
}
}
}
// detects browser
navigator.sayswho= (function() {
var ua= navigator.userAgent, tem,
M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*([\d\.]+)/i) || [];
if(/trident/i.test(M[1])){
tem= /\brv[ :]+(\d+(\.\d+)?)/g.exec(ua) || [];
return 'IE '+(tem[1] || '');
}
M= M[2]? [M[1], M[2]]:[navigator.appName, navigator.appVersion, '-?'];
if((tem= ua.match(/version\/([\.\d]+)/i))!= null) M[2]= tem[1];
return M.join(' ');
})();
// quick detection if browser is firefox
function isFirefox() {
var ua= navigator.userAgent,
M= ua.match(/firefox\//i);
return M;
}
// indented select options support for non-firefox browsers
if (!isFirefox()) {
add_nbsp();
}
}
you need to wrap your text inside div and float it left while wrapper div should have height, and I've also added line height for vertical alignment
<div style="border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: gray;height:30px;">
<div style="float:left;line-height:30px;">Contact Details</div>
<button type="button" class="edit_button" style="float: right;">My Button</button>
</div>
also js fiddle here =) http://jsfiddle.net/xQgSm/
This answer has a code example, which implements the algorithm described in the paper Practical In-Place Merging by Bing-Chao Huang and Michael A. Langston. I have to admit that I do not understand the details, but the given complexity of the merge step is O(n).
From a practical perspective, there is evidence that pure in-place implementations are not performing better in real world scenarios. For example, the C++ standard defines std::inplace_merge, which is as the name implies an in-place merge operation.
Assuming that C++ libraries are typically very well optimized, it is interesting to see how it is implemented:
The implementation delegates to __inplace_merge, which dodges the problem by trying to allocate a temporary buffer:
typedef _Temporary_buffer<_BidirectionalIterator, _ValueType> _TmpBuf;
_TmpBuf __buf(__first, __len1 + __len2);
if (__buf.begin() == 0)
std::__merge_without_buffer
(__first, __middle, __last, __len1, __len2, __comp);
else
std::__merge_adaptive
(__first, __middle, __last, __len1, __len2, __buf.begin(),
_DistanceType(__buf.size()), __comp);
Otherwise, it falls back to an implementation (__merge_without_buffer), which requires no extra memory, but no longer runs in O(n) time.
Looks similar. It delegates to a function, which also tries to allocate a buffer. Depending on whether it got enough elements, it will choose the implementation. The constant-memory fallback function is called __buffered_inplace_merge.
Maybe even the fallback is still O(n) time, but the point is that they do not use the implementation if temporary memory is available.
Note that the C++ standard explicitly gives implementations the freedom to choose this approach by lowering the required complexity from O(n) to O(N log N):
Complexity: Exactly N-1 comparisons if enough additional memory is available. If the memory is insufficient, O(N log N) comparisons.
Of course, this cannot be taken as a proof that constant space in-place merges in O(n) time should never be used. On the other hand, if it would be faster, the optimized C++ libraries would probably switch to that type of implementation.
I just ran into a case where the .svn directory is on a nfs server on a different machine, and the nfs client was not running the file locking service (lockd
).
svn: E155007: '/mnt/svnworkdir' is not a working copy
This went away once lockd
was started on the nfs client host.
It seems like subversion could come up with a better error message when it has trouble locking files. This was subversion 1.10.0
CREATE GLOBAL TEMPORARY TABLE Table_name
(startdate DATE,
enddate DATE,
class CHAR(20))
ON COMMIT DELETE ROWS;
dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Blue;
p $eax
works as of GDB 7.7.1
As of GDB 7.7.1, the command you've tried works:
set $eax = 0
p $eax
# $1 = 0
set $eax = 1
p $eax
# $2 = 1
This syntax can also be used to select between different union members e.g. for ARM floating point registers that can be either floating point or integers:
p $s0.f
p $s0.u
From the docs:
Any name preceded by ‘$’ can be used for a convenience variable, unless it is one of the predefined machine-specific register names.
and:
You can refer to machine register contents, in expressions, as variables with names starting with ‘$’. The names of registers are different for each machine; use info registers to see the names used on your machine.
But I haven't had much luck with control registers so far: OSDev 2012 http://f.osdev.org/viewtopic.php?f=1&t=25968 || 2005 feature request https://www.sourceware.org/ml/gdb/2005-03/msg00158.html || alt.lang.asm 2013 https://groups.google.com/forum/#!topic/alt.lang.asm/JC7YS3Wu31I
ARM floating point registers
You need to extract the number from the string, and pass it into the Date constructor
:
var x = [{
"id": 1,
"start": "\/Date(1238540400000)\/"
}, {
"id": 2,
"start": "\/Date(1238626800000)\/"
}];
var myDate = new Date(x[0].start.match(/\d+/)[0] * 1);
The parts are:
x[0].start - get the string from the JSON
x[0].start.match(/\d+/)[0] - extract the numeric part
x[0].start.match(/\d+/)[0] * 1 - convert it to a numeric type
new Date(x[0].start.match(/\d+/)[0] * 1)) - Create a date object
Thank you drifty0pine!
The first solution, it´s works!
[a relative link](../../some/dir/filename.md)
[Link to file in another dir on same drive](/another/dir/filename.md)
[Link to file in another dir on a different drive](/D:/dir/filename.md)
but I had need put more ../
until the folder where was my file, like this:
[FileToOpen](../../../../folderW/folderX/folderY/folderZ/FileToOpen.txt)
After going down a bit of a bit of a rabbit hole trying to follow the answers to this question (maybe because I had to do this in a visual studio project), I found the easier path was to
Cut and paste the file(s) I no longer want to track into a temporary location
Commit the "deletion" of those files
Commit a modification of the .gitignore
to exclude the files I had temporarily moved
Move the files back into the folder.
I found this to be the most straight forward way to go about it (at least in a visual studio, or I would assume other IDE heave based environment like Android Studio), without accidentally shooting myself in the foot with a pretty pervasive git rm -rf --cached .
, after which the visual studio project I was working on didn't load.
Wrote a small class for doing this cleanly.
import tempfile
class FileModifierError(Exception):
pass
class FileModifier(object):
def __init__(self, fname):
self.__write_dict = {}
self.__filename = fname
self.__tempfile = tempfile.TemporaryFile()
with open(fname, 'rb') as fp:
for line in fp:
self.__tempfile.write(line)
self.__tempfile.seek(0)
def write(self, s, line_number = 'END'):
if line_number != 'END' and not isinstance(line_number, (int, float)):
raise FileModifierError("Line number %s is not a valid number" % line_number)
try:
self.__write_dict[line_number].append(s)
except KeyError:
self.__write_dict[line_number] = [s]
def writeline(self, s, line_number = 'END'):
self.write('%s\n' % s, line_number)
def writelines(self, s, line_number = 'END'):
for ln in s:
self.writeline(s, line_number)
def __popline(self, index, fp):
try:
ilines = self.__write_dict.pop(index)
for line in ilines:
fp.write(line)
except KeyError:
pass
def close(self):
self.__exit__(None, None, None)
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
with open(self.__filename,'w') as fp:
for index, line in enumerate(self.__tempfile.readlines()):
self.__popline(index, fp)
fp.write(line)
for index in sorted(self.__write_dict):
for line in self.__write_dict[index]:
fp.write(line)
self.__tempfile.close()
Then you can use it this way:
with FileModifier(filename) as fp:
fp.writeline("String 1", 0)
fp.writeline("String 2", 20)
fp.writeline("String 3") # To write at the end of the file
You can use .change()
$('input[name=myInput]').change(function() { ... });
However, this event will only fire when the selector has lost focus, so you will need to click somewhere else to have this work.
If that's not quite right for you, you could use some of the other jQuery events like keyup, keydown or keypress - depending on the exact effect you want.
If a GPU device has, for example, 4 multiprocessing units, and they can run 768 threads each: then at a given moment no more than 4*768 threads will be really running in parallel (if you planned more threads, they will be waiting their turn).
threads are organized in blocks. A block is executed by a multiprocessing unit. The threads of a block can be indentified (indexed) using 1Dimension(x), 2Dimensions (x,y) or 3Dim indexes (x,y,z) but in any case xyz <= 768 for our example (other restrictions apply to x,y,z, see the guide and your device capability).
Obviously, if you need more than those 4*768 threads you need more than 4 blocks. Blocks may be also indexed 1D, 2D or 3D. There is a queue of blocks waiting to enter the GPU (because, in our example, the GPU has 4 multiprocessors and only 4 blocks are being executed simultaneously).
Suppose we want one thread to process one pixel (i,j).
We can use blocks of 64 threads each. Then we need 512*512/64 = 4096 blocks (so to have 512x512 threads = 4096*64)
It's common to organize (to make indexing the image easier) the threads in 2D blocks having blockDim = 8 x 8 (the 64 threads per block). I prefer to call it threadsPerBlock.
dim3 threadsPerBlock(8, 8); // 64 threads
and 2D gridDim = 64 x 64 blocks (the 4096 blocks needed). I prefer to call it numBlocks.
dim3 numBlocks(imageWidth/threadsPerBlock.x, /* for instance 512/8 = 64*/
imageHeight/threadsPerBlock.y);
The kernel is launched like this:
myKernel <<<numBlocks,threadsPerBlock>>>( /* params for the kernel function */ );
Finally: there will be something like "a queue of 4096 blocks", where a block is waiting to be assigned one of the multiprocessors of the GPU to get its 64 threads executed.
In the kernel the pixel (i,j) to be processed by a thread is calculated this way:
uint i = (blockIdx.x * blockDim.x) + threadIdx.x;
uint j = (blockIdx.y * blockDim.y) + threadIdx.y;
System.String is a reference type so you don't need to do anything like
Nullable<string>
It already has a null value (the null reference):
string x = null; // No problems here
The official Jenkins documentation only mentions single line commands like the following:
// Declarative //
and (see)
pipeline {
/* insert Declarative Pipeline here */
}
The syntax of the Jenkinsfile is based on Groovy so it is also possible to use groovy syntax for comments. Quote:
/* a standalone multiline comment
spanning two lines */
println "hello" /* a multiline comment starting
at the end of a statement */
println 1 /* one */ + 2 /* two */
or
/**
* such a nice comment
*/
Here's my alternative. It also uses different DIVs for the header, body and footer but synchronised for window resizing and with searching, scrolling, sorting, filtering and positioning:
Click on the Jazz, Classical... buttons to see the tables. It's set up so that it's adequate even if JavaScript is turned off.
Seems OK on IE, FF and WebKit (Chrome, Safari).
99% of our AWS setup is recyclable. So for me it doesn't really matter if I terminate an instance -- nothing is lost ever. E.g. my application is automatically deployed on an instance from SVN, our logs are written to a central syslog server.
The only benefit of instance storage that I see are cost-savings. Otherwise EBS-backed instances win. Eric mentioned all the advantages.
[2012-07-16] I would phrase this answer a lot different today.
I haven't had any good experience with EBS-backed instances in the past year or so. The last downtimes on AWS pretty much wrecked EBS as well.
I am guessing that a service like RDS uses some kind of EBS as well and that seems to work for the most part. On the instances we manage ourselves, we have got rid off EBS where possible.
Getting rid to an extend where we moved a database cluster back to iron (= real hardware). The only remaining piece in our infrastructure is a DB server where we stripe multiple EBS volumes into a software RAID and backup twice a day. Whatever would be lost in between backups, we can live with.
EBS is a somewhat flakey technology since it's essentially a network volume: a volume attached to your server from remote. I am not negating the work done with it – it is an amazing product since essentially unlimited persistent storage is just an API call away. But it's hardly fit for scenarios where I/O performance is key.
And in addition to how network storage behaves, all network is shared on EC2 instances. The smaller an instance (e.g. t1.micro, m1.small) the worse it gets because your network interfaces on the actual host system are shared among multiple VMs (= your EC2 instance) which run on top of it.
The larger instance you get, the better it gets of course. Better here means within reason.
When persistence is required, I would always advice people to use something like S3 to centralize between instances. S3 is a very stable service. Then automate your instance setup to a point where you can boot a new server and it gets ready by itself. Then there is no need to have network storage which lives longer than the instance.
So all in all, I see no benefit to EBS-backed instances what so ever. I rather add a minute to bootstrap, then run with a potential SPOF.
You can try webshims, which is available on cdn + only loads the polyfill, if it is needed.
Here is a demo with CDN: http://jsfiddle.net/trixta/BMEc9/
<!-- cdn for modernizr, if you haven't included it already -->
<script src="http://cdn.jsdelivr.net/webshim/1.12.4/extras/modernizr-custom.js"></script>
<!-- polyfiller file to detect and load polyfills -->
<script src="http://cdn.jsdelivr.net/webshim/1.12.4/polyfiller.js"></script>
<script>
webshims.setOptions('waitReady', false);
webshims.setOptions('forms-ext', {types: 'date'});
webshims.polyfill('forms forms-ext');
</script>
<input type="date" />
In case the default configuration does not satisfy, there are many ways to configure it. Here you find the datepicker configurator.
Note: While there might be new bugfix releases for webshim in the future. There won't be any major releases anymore. This includes support for jQuery 3.0 or any new features.
Simple solution would be to remove padding from .panel-heading
and add to .panel-title a
.
.panel-heading {
padding: 0;
}
.panel-title a {
display: block;
padding: 10px 15px;
}
This solution is similar to the above one posted by calfzhou, slightly different.
You will have to access db through the ip of host machine, or if you want to access it via localhost:1521, then run webserver like -
docker run --net=host --name oracle-wls wls-image:latest
Sadly, no.
I used two methods and I found one method useful over other. Here is my answer:
My input data:
crkmod_mpp = ['M13','M18','M19','M24']
testmod_mpp = ['M13','M14','M15','M16','M17','M18','M19','M20','M21','M22','M23','M24']
Method1: np.setdiff1d
I like this approach over other because it preserves the position
test= list(np.setdiff1d(testmod_mpp,crkmod_mpp))
print(test)
['M15', 'M16', 'M22', 'M23', 'M20', 'M14', 'M17', 'M21']
Method2: Though it gives same answer as in Method1 but disturbs the order
test = list(set(testmod_mpp).difference(set(crkmod_mpp)))
print(test)
['POA23', 'POA15', 'POA17', 'POA16', 'POA22', 'POA18', 'POA24', 'POA21']
Method1 np.setdiff1d
meets my requirements perfectly.
This answer for information.
Here is a good example -
ul li{
list-style-type: disc;
list-style-position: inside;
padding: 10px 0 10px 20px;
text-indent: -1em;
}
Working Demo: http://jsfiddle.net/d9VNk/
There is a another best/effective way to solve this error,
for example, let's take a loop which counts till 10 thousand, here you may get the error Out of memory
, do to solve it you can give the computer time to recover.
So, you can sleep for 400-500ms
before you're loop counts the next number :
new Thread(new Runnable() {
public void run() {
try {
sleep(550); // 550 ms (milli seconds)
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
By doing this, will make you're program slower but you don't get any error till the heap space
is full again, so by waiting some ms
, you can prevent that error.
You can apply this method other than loop.
Hope it helped you, :D
For Swift
Create UITextField Extension
extension UITextField{
func setPlaceHolderColor(){
self.attributedPlaceholder = NSAttributedString(string: self.placeholder!, attributes: [NSForegroundColorAttributeName : UIColor.white])
}
}
If Are you set from storyboard.
extension UITextField{
@IBInspectable var placeHolderColor: UIColor? {
get {
return self.placeHolderColor
}
set {
self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSAttributedString.Key.foregroundColor : newValue!])
}
}
}
Create some public Properties on your sub-form like so
public string ReturnValue1 {get;set;}
public string ReturnValue2 {get;set;}
then set this inside your sub-form ok button click handler
private void btnOk_Click(object sender,EventArgs e)
{
this.ReturnValue1 = "Something";
this.ReturnValue2 = DateTime.Now.ToString(); //example
this.DialogResult = DialogResult.OK;
this.Close();
}
Then in your frmHireQuote form, when you open the sub-form
using (var form = new frmImportContact())
{
var result = form.ShowDialog();
if (result == DialogResult.OK)
{
string val = form.ReturnValue1; //values preserved after close
string dateString = form.ReturnValue2;
//Do something here with these values
//for example
this.txtSomething.Text = val;
}
}
Additionaly if you wish to cancel out of the sub-form you can just add a button to the form and set its DialogResult to Cancel
and you can also set the CancelButton property of the form to said button - this will enable the escape key to cancel out of the form.
I needed something similar for a task. This is the code I wrote: It calculates the next day and changes the time to whatever is required and finds seconds between currentTime and next scheduled time.
import datetime as dt
def my_job():
print "hello world"
nextDay = dt.datetime.now() + dt.timedelta(days=1)
dateString = nextDay.strftime('%d-%m-%Y') + " 01-00-00"
newDate = nextDay.strptime(dateString,'%d-%m-%Y %H-%M-%S')
delay = (newDate - dt.datetime.now()).total_seconds()
Timer(delay,my_job,()).start()
strikes = [number_map[int(x)] for x in input_str.split()]
Use square brackets to explore dictionaries.
save as png solved the problem for me.
break:- These transfer statement bypass the correct flow of execution to outside of the current loop by skipping on the remaining iteration
class test
{
public static void main(String []args)
{
for(int i=0;i<10;i++)
{
if(i==5)
break;
}
System.out.println(i);
}
}
output will be
0
1
2
3
4
Continue :-These transfer Statement will bypass the flow of execution to starting point of the loop inorder to continue with next iteration by skipping all the remaining instructions .
class test
{
public static void main(String []args)
{
for(int i=0;i<10;i++)
{
if(i==5)
continue;
}
System.out.println(i);
}
}
output will be:
0
1
2
3
4
6
7
8
9
return :- At any time in a method the return statement can be used to cause execution to branch back to the caller of the method. Thus, the return statement immediately terminates the method in which it is executed. The following example illustrates this point. Here, return causes execution to return to the Java run-time system, since it is the run-time system that calls main( ).
class test
{
public static void main(String []args)
{
for(int i=0;i<10;i++)
{
if(i==5)
return;
}
System.out.println(i)
}
}
output will be :
0
1
2
3
4
$ git commit --allow-empty -m "Trigger Build"
You can use cross platform solution https://www.npmjs.com/package/cross-env
$ cross-env PORT=1234
Go to C:\app\insolution\product\11.2.0\client_1\BIN and find oci.dll. Right click on it -->Properties -->Under Security tab, click on Edit -->Then Click on Add Button --> Here add two new users with names IUSR and IIS_IUSRS and give them full controls. That's it.
Not sure if this completely helps, but I had an issue where I needed a "smart" merge. I had two columns, A & B. I wanted to move B over only if A was blank. See below. It is based on a selection Range, which you could use to offset the first row, perhaps.
Private Sub MergeProjectNameColumns()
Dim rngRowCount As Integer
Dim i As Integer
'Loop through column C and simply copy the text over to B if it is not blank
rngRowCount = Range(dataRange).Rows.Count
ActiveCell.Offset(0, 0).Select
ActiveCell.Offset(0, 2).Select
For i = 1 To rngRowCount
If (Len(RTrim(ActiveCell.Value)) > 0) Then
Dim currentValue As String
currentValue = ActiveCell.Value
ActiveCell.Offset(0, -1) = currentValue
End If
ActiveCell.Offset(1, 0).Select
Next i
'Now delete the unused column
Columns("C").Select
selection.Delete Shift:=xlToLeft
End Sub
you can import bs4 instead of BeautifulSoup. Since bs4 is a built-in module, no additional installation is required.
from bs4 import BeautifulSoup
import re
doc = ['<html><head><title>Page title</title></head>',
'<body><p id="firstpara" align="center">This is paragraph <b>one</b>.',
'<p id="secondpara" align="blah">This is paragraph <b>two</b>.',
'</html>']
soup = BeautifulSoup(''.join(doc))
print soup.prettify()
If you want to request, using requests module.
request is using urllib
, requests
modules.
but I personally recommendation using requests
module instead of urllib
module install for using:
$ pip install requests
Here's how to use the requests module:
import requests as rq
res = rq.get('http://www.example.com')
print(res.content)
print(res.status_code)
replace:true
is DeprecatedFrom the Docs:
replace
([DEPRECATED!], will be removed in next major release - i.e. v2.0)specify what the template should replace. Defaults to
false
.
true
- the template will replace the directive's element.false
- the template will replace the contents of the directive's element.
-- AngularJS Comprehensive Directive API
From GitHub:
Caitp-- It's deprecated because there are known, very silly problems with
replace: true
, a number of which can't really be fixed in a reasonable fashion. If you're careful and avoid these problems, then more power to you, but for the benefit of new users, it's easier to just tell them "this will give you a headache, don't do it".
Note:
replace: true
is deprecated and not recommended to use, mainly due to the issues listed here. It has been completely removed in the new Angular.
transclude: element
in the replace template root can have unexpected effectsFor more information, see
is a small amount of data saved in the browser (client-side)
can be set from PHP with setcookie
and then will be sent to the client's browser (HTTP response header Set-cookie
)
can be set directly client-side in Javascript: document.cookie = 'foo=bar';
if no expiration date is set, by default, it will expire when the browser is closed.
Example: go on http://example.com, open the Console, do document.cookie = 'foo=bar';
. Close the tab, reopen the same website, open the Console, do document.cookie
: you will see foo=bar
is still there. Now close the browser and reopen it, re-visit the same website, open the Console ; you will see document.cookie
is empty.
you can also set a precise expiration date other than "deleted when browser is closed".
the cookies that are stored in the browser are sent to the server in the headers of every request of the same website (see Cookie
). You can see this for example with Chrome by opening Developer tools > Network, click on the request, see Headers:
can be read client-side with document.cookie
can be read server-side with $_COOKIE['foo']
Bonus: it can also be set/get with another language than PHP. Example in Python with "bottle" micro-framework (see also here):
from bottle import get, run, request, response
@get('/')
def index():
if request.get_cookie("visited"):
return "Welcome back! Nice to see you again"
else:
response.set_cookie("visited", "yes")
return "Hello there! Nice to meet you"
run(host='localhost', port=8080, debug=True, reloader=True)
is some data relative to a browser session saved server-side
each server-side language may implement it in a different way
in PHP, when session_start();
is called:
jo96fme9ko0f85cdglb3hl6ah6
/var/lib/php5/sess_jo96fme9ko0f85cdglb3hl6ah6
the session ID is sent to the client in the HTTP response headers, using the traditional cookie mechanism detailed above: Set-Cookie: PHPSESSID=jo96fme9ko0f85cdglb3hl6ah6; path=/
:
(it can also be be sent via the URL instead of cookie but not the default behaviour)
you can see the session ID on client-side with document.cookie
:
the PHPSESSID
cookie is set with no expiration date, thus it will expire when the browser is closed. Thus "sessions" are not valid anymore when the browser is closed / reopened.
can be set/read in PHP with $_SESSION
the client-side does not see the session data but only the ID: do this in index.php
:
<?php
session_start();
$_SESSION["abc"]="def";
?>
The only thing that is seen on client-side is (as mentioned above) the session ID:
because of this, session is useful to store data that you don't want to be seen or modified by the client
you can totally avoid using sessions if you want to use your own database + IDs and send an ID/token to the client with a traditional Cookie
I think that Spring Data ignores the FetchMode. I always use the @NamedEntityGraph
and @EntityGraph
annotations when working with Spring Data
@Entity
@NamedEntityGraph(name = "GroupInfo.detail",
attributeNodes = @NamedAttributeNode("members"))
public class GroupInfo {
// default fetch mode is lazy.
@ManyToMany
List<GroupMember> members = new ArrayList<GroupMember>();
…
}
@Repository
public interface GroupRepository extends CrudRepository<GroupInfo, String> {
@EntityGraph(value = "GroupInfo.detail", type = EntityGraphType.LOAD)
GroupInfo getByGroupName(String name);
}
Check the documentation here
Remove the slashes:
String json = {"phonetype":"N95","cat":"WP"};
try {
JSONObject obj = new JSONObject(json);
Log.d("My App", obj.toString());
} catch (Throwable t) {
Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
}
Charming Prince:
Only internet explorer allows the 4 byte hex color in the format of ARGB, where A is the Alpha channel. It can be used in gradient filters for example:
filter : ~"progid:DXImageTransform.Microsoft.Gradient(GradientType=@{dir},startColorstr=@{color1},endColorstr=@{color2})";
Where dir can be: 1(horizontal) or 0(vertical) And the color strings can be hex colors(#FFAAD3) or argb hex colors(#88FFAAD3).
You can do the following after adding class one-edge-shadow
or use as you like.
.one-edge-shadow {
-webkit-box-shadow: 0 8px 6px -6px black;
-moz-box-shadow: 0 8px 6px -6px black;
box-shadow: 0 8px 6px -6px black;
}
volatile variable is basically used for instant update (flush) in main shared cache line once it updated, so that changes reflected to all worker threads immediately.
URI = https://graph.facebook.com/{}/picture?width=500'.format(uid)
You can get the profile URI via online facebook id finder tool
You can also pass type param with possible values small, normal, large, square.
Refer the official documentation
You have two options:
Extend your .paging
class definition:
.paging:hover {
border:1px solid #999;
color:#000;
}
Use the DOM hierarchy to apply the CSS style:
div.paginate input:hover {
border:1px solid #999;
color:#000;
}
cd
has a parameter /d
, which will change drive and path with one command:
cd /d d:\temp
( see cd /?
)
you can try and solve using css only. by adding class to select
select{ width:80px;text-overflow:'...';-ms-text-overflow:ellipsis;position:absolute; z-index:+1;}
select:focus{ width:100%;}
for more reference List Box Style in a particular item (option) HTML
Use "@null" . It worked for me.
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/bkash"
android:id="@+id/bid1"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="@null" />
Why to complicate a situation if you can just write like it? (yes -> low cohesion, hardcoded -> but it is a example and unfortunately with imperative way). For additional info read code example at below ;))
package timer.test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.concurrent.*;
public class TestKitTimerWithExecuterService {
private static final Logger log = LoggerFactory.getLogger(TestKitTimerWithExecuterService.class);
private static final ScheduledExecutorService executorService
= Executors.newSingleThreadScheduledExecutor();// equal to => newScheduledThreadPool(1)/ Executor service with one Thread
private static ScheduledFuture<?> future; // why? because scheduleAtFixedRate will return you it and you can act how you like ;)
public static void main(String args[]){
log.info("main thread start");
Runnable task = () -> log.info("******** Task running ********");
LocalDateTime now = LocalDateTime.now();
LocalDateTime whenToStart = LocalDate.now().atTime(20, 11); // hour, minute
Duration duration = Duration.between(now, whenToStart);
log.info("WhenToStart : {}, Now : {}, Duration/difference in second : {}",whenToStart, now, duration.getSeconds());
future = executorService.scheduleAtFixedRate(task
, duration.getSeconds() // difference in second - when to start a job
,2 // period
, TimeUnit.SECONDS);
try {
TimeUnit.MINUTES.sleep(2); // DanDig imitation of reality
cancelExecutor(); // after canceling Executor it will never run your job again
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("main thread end");
}
public static void cancelExecutor(){
future.cancel(true);
executorService.shutdown();
log.info("Executor service goes to shut down");
}
}
You can currently do this in a couple of ways.
One is to create guidelines (right-click the design area, then click add vertical/horizontal guideline). You can then click the guideline's "header" to change the positioning to be percentage based. Finally, you can constrain views to guidelines.
Another way is to position a view using bias (percentage) and to then anchor other views to that view.
That said, we have been thinking about how to offer percentage based dimensions. I can't make any promise but it's something we would like to add.
The Standard says (at 14/3. For the non-standard folks, the names following a class definition body (or the type in a declaration in general) are "declarators")
In a template-declaration, explicit specialization, or explicit instantiation the init-declarator-list in the dec-laration shall contain at most one declarator. When such a declaration is used to declare a class template, no declarator is permitted.
Do it like Andrey shows.
I have found a npm package made with CoffeeScript that has a lot of incredible useful helpers for Handlebars. Take a look of the documentation in the following URL:
https://npmjs.org/package/handlebars-helpers
You can do a wget http://registry.npmjs.org/handlebars-helpers/-/handlebars-helpers-0.2.6.tgz
to download them and see the contents of the package.
You will be abled to do things like {{#is number 5}}
or {{formatDate date "%m/%d/%Y"}}
You have the button tag
http://www.w3schools.com/tags/tag_button.asp
<button>What ever you want</button>
Sometimes autoplay is needed. Someone once pointed out that the famous Les Paul Google Doodle (2011) required autoplay, even though the sound didn't play until you moused over the guitar strings. If it's done with class and great design it can be beautiful (especially movie websites with immersive design)
According to this blog post:
find . -type f | xargs perl -pi -e 's/oldtext/newtext/g;'
You can do this by thinking of it a little bit differently. Detect when the body is clicked (document.body.onclick
- i.e. anything on the page) and then check if the element clicked (event.srcElement
/ e.target
) has a class and that that class name is the one you want:
document.body.onclick = function(e) { //when the document body is clicked
if (window.event) {
e = event.srcElement; //assign the element clicked to e (IE 6-8)
}
else {
e = e.target; //assign the element clicked to e
}
if (e.className && e.className.indexOf('someclass') != -1) {
//if the element has a class name, and that is 'someclass' then...
alert('hohoho');
}
}
Or a more concise version of the above:
document.body.onclick= function(e){
e=window.event? event.srcElement: e.target;
if(e.className && e.className.indexOf('someclass')!=-1)alert('hohoho');
}
$_SERVER['HTTP_REFERER']
will give you the referrer page's URL if there exists any. If users use a bookmark or directly visit your site by manually typing in the URL, http_referer will be empty. Also if the users are posting to your page programatically (CURL) then they're not obliged to set the http_referer as well. You're missing all _
, is that a typo?
ON DELETE CASCADE
It specifies that the child data is deleted when the parent data is deleted.
CREATE TABLE products
( product_id INT PRIMARY KEY,
product_name VARCHAR(50) NOT NULL,
category VARCHAR(25)
);
CREATE TABLE inventory
( inventory_id INT PRIMARY KEY,
product_id INT NOT NULL,
quantity INT,
min_level INT,
max_level INT,
CONSTRAINT fk_inv_product_id
FOREIGN KEY (product_id)
REFERENCES products (product_id)
ON DELETE CASCADE
);
For this foreign key, we have specified the ON DELETE CASCADE
clause which tells SQL Server to delete the corresponding records in the child table when the data in the parent table is deleted. So in this example, if a product_id value is deleted from the products table, the corresponding records in the inventory table that use this product_id will also be deleted.
The browser cannot give access to 3rd party cookies like those received from ajax requests for security reasons, however it takes care of those automatically for you!
For this to work you need to:
1) login with the ajax request from which you expect cookies to be returned:
$.ajax("https://example.com/v2/login", {
method: 'POST',
data: {login_id: user, password: password},
crossDomain: true,
success: login_success,
error: login_error
});
2) Connect with xhrFields: { withCredentials: true }
in the next ajax request(s) to use the credentials saved by the browser
$.ajax("https://example.com/v2/whatever", {
method: 'GET',
xhrFields: { withCredentials: true },
crossDomain: true,
success: whatever_success,
error: whatever_error
});
The browser takes care of these cookies for you even though they are not readable from the headers
nor the document.cookie
We can remove unnecessary string input in front of the value.
string convert = hdnImage.Replace("data:image/png;base64,", String.Empty);
byte[] image64 = Convert.FromBase64String(convert);
The Linux Kernel does not automatically change the IO Scheduler at run-time. By this I mean, the Linux kernel, as of today, is not able to automatically choose an "optimal" scheduler depending on the type of secondary storage devise. During start-up, or during run-time, it is possible to change the IO scheduler manually.
The default scheduler is chosen at start-up based on the contents in the file located at /linux-2.6 /block/Kconfig.iosched. However, it is possible to change the IO scheduler during run-time by echo
ing a valid scheduler name into the file located at /sys/block/[DEV]/queue/scheduler. For example, echo deadline > /sys/block/hda/queue/scheduler
In my case, (windows OS), after put all those commands listed, npm kept taking the proxy in the setting of windows registry
\ HKEY_CURRENT_USER \ Environment
just remove the proxy settings there, after that, I restarted the pc and then "npm install" worked for me
Alternatively one could say having an infinite loop is normally bad practice anyway, since it needs an exit condition unless the app really runs forever. However, if this is for a cruise missile I will accept an explicit exit condition might not be required.
Though I do like this one:
for (float f = 16777216f; f < 16777217f; f++) { }
Right-click the table in DB2 Control Center and chose Generate DDL... That will give you everything you need and more.
recordId is property of the object
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Nai_record other = (Nai_record) obj;
if (recordId == null) {
if (other.recordId != null)
return false;
} else if (!recordId.equals(other.recordId))
return false;
return true;
}
Make sure that you have compiled your *.cs file before browsing the ASPX page.
my.ini LOCATION ON WINDOWS MYSQL 5.6 MSI (USING THE INSTALL WIZARD)
Open a Windows command shell and type: echo %PROGRAMDATA%
. On Windows Vista this results in: C:\ProgramData
.
According to http://dev.mysql.com/doc/refman/5.6/en/option-files.html, the first location MySQL will look under is in %PROGRAMDATA%\MySQL\MySQL Server 5.6\my.ini
. In your Windows shell if you do ls "%PROGRAMDATA%\MySQL\MySQL Server 5.6\my.ini"
, you will see that the file is there.
Unlike most suggestions you will find in Stackoverflow and around the web, putting the file in C:\Program Files\MySQL\MySQL Server 5.6\my.ini
WILL NOT WORK. Neither will C:\Program Files (x86)\MySQL\MySQL Server 5.1
. The reason being quoted on the MySQL link posted above:
On Windows, MySQL programs read startup options from the following files, in the specified order (top items are used first).
The 5.6 MSI installer does create a my.ini in the highest priority location, meaning no other file will ever be found/used, except for the one created by the installer.
The solution accepted above will not work for 5.6 MSI-based installs.
It isn't possible as DateTime is immutable. The same discussion is available here: How to change time in datetime?
I don't think it's necessary to use semi-quotes around the variables, try:
curl -XPOST 'http://localhost/Service' -d "path=%2fxyz%2fpqr%2ftest%2f&fileName=1.doc"
%2f
is the escape code for a /
.
http://www.december.com/html/spec/esccodes.html
Also, do you need to specify a port? ( just checking :) )
A performance-driven approach - calling environ
is expensive, so it's better to call it once and save it to a dictionary. Full example:
from os import environ
# Slower
print(environ["USER"], environ["NAME"])
# Faster
env_dict = dict(environ)
print(env_dict["USER"], env_dict["NAME"])
P.S- if you worry about exposing private environment variables, then sanitize env_dict
after the assignment.
I don't agree with the statement about [...] HTTP referrer leakage (an external image in the target page might leak the password) in Slough's response.
The HTTP 1.1 RFC explicitly states:
Clients SHOULD NOT include a Referer header field in a (non-secure) HTTP request if the referring page was transferred with a secure protocol.
Anyway, server logs and browser history are more than sufficient reasons not to put sensitive data in the query string.
You can also use =OFFSET([@column];-1;0)
if you are in a named table.
This also works for lists within the object:
Id:37
IdParent:26
Name:Poplet
Values[0].Id:1349
Values[0].Name:SomeName
Values[1].Id:1350
Values[1].Name:AnotherName
the equivalent JSON would be:
{
"Id": 37,
"IdParent": 26,
"Name": "Poplet",
"Values": [
{
"Id": 1349,
"Name": "SomeName"
},
{
"Id": 1350,
"Name": "AnotherName"
}
]
}
I think this should work:
String rank = card.substring(0,1);
String suit = card.substring(1);
String cards = "A23456789TJQKDHSCl";
String[] name = {"Ace","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King","Diamonds","Hearts","Spades","Clubs"};
String c ="";
for(int a = 0, b = 1; a<cards.length()-1; b=a+1, a++ )
{
if( rank.equals( cards.substring(a,b) ) )
{
c+=name[a];
}
}
System.out.println(c);
I installed 32-bit JVM and retried it again, looks like the following does tell you JVM bitness, not OS arch:
System.getProperty("os.arch");
#
# on a 64-bit Linux box:
# "x86" when using 32-bit JVM
# "amd64" when using 64-bit JVM
This was tested against both SUN and IBM JVM (32 and 64-bit). Clearly, the system property is not just the operating system arch.
You can consider shapely:
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon
point = Point(0.5, 0.5)
polygon = Polygon([(0, 0), (0, 1), (1, 1), (1, 0)])
print(polygon.contains(point))
From the methods you've mentioned I've only used the second, path.contains_points
, and it works fine. In any case depending on the precision you need for your test I would suggest creating a numpy bool grid with all nodes inside the polygon to be True (False if not). If you are going to make a test for a lot of points this might be faster (although notice this relies you are making a test within a "pixel" tolerance):
from matplotlib import path
import matplotlib.pyplot as plt
import numpy as np
first = -3
size = (3-first)/100
xv,yv = np.meshgrid(np.linspace(-3,3,100),np.linspace(-3,3,100))
p = path.Path([(0,0), (0, 1), (1, 1), (1, 0)]) # square with legs length 1 and bottom left corner at the origin
flags = p.contains_points(np.hstack((xv.flatten()[:,np.newaxis],yv.flatten()[:,np.newaxis])))
grid = np.zeros((101,101),dtype='bool')
grid[((xv.flatten()-first)/size).astype('int'),((yv.flatten()-first)/size).astype('int')] = flags
xi,yi = np.random.randint(-300,300,100)/100,np.random.randint(-300,300,100)/100
vflag = grid[((xi-first)/size).astype('int'),((yi-first)/size).astype('int')]
plt.imshow(grid.T,origin='lower',interpolation='nearest',cmap='binary')
plt.scatter(((xi-first)/size).astype('int'),((yi-first)/size).astype('int'),c=vflag,cmap='Greens',s=90)
plt.show()
, the results is this:
to load a KeyStore, you'll need to tell it the type of keystore it is (probably jceks), provide an inputstream, and a password. then, you can load it like so:
KeyStore ks = KeyStore.getInstance(TYPE_OF_KEYSTORE);
ks.load(new FileInputStream(PATH_TO_KEYSTORE), PASSWORD);
this can throw a KeyStoreException, so you can surround in a try block if you like, or re-throw. Keep in mind a keystore can contain multiple keys, so you'll need to look up your key with an alias, here's an example with a symmetric key:
SecretKeyEntry entry = (KeyStore.SecretKeyEntry)ks.getEntry(SOME_ALIAS,new KeyStore.PasswordProtection(SOME_PASSWORD));
SecretKey someKey = entry.getSecretKey();
The code says everything:
max@serv$ chmod 777 .
Okay, it doesn't say everything.
In UNIX and Linux, the ability to remove a file is not determined by the access bits of that file. It is determined by the access bits of the directory which contains the file.
Think of it this way -- deleting a file doesn't modify that file. You aren't writing to the file, so why should "w" on the file matter? Deleting a file requires editing the directory that points to the file, so you need "w" on the that directory.
Well, this might be counter-intuitive but I solved this adding esnext
to my lib
.
{
"compilerOptions": {
"lib": [
"esnext"
],
"target": "es5",
}
}
The FIX, as suggested by the compiler is to
Try changing the
lib
compiler option to es2015 or later.
$it = new RegexIterator(new DirectoryIterator("."), "/\\.xml\$/i"));
foreach ($it as $filename) {
//...
}
You can also use the recursive variants of the iterators to traverse an entire directory hierarchy.
I used the Google Apps Script method indexOf()
and its results were wrong. So I wrote the small function Myindexof()
, instead of indexOf
:
function Myindexof(s,text)
{
var lengths = s.length;
var lengtht = text.length;
for (var i = 0;i < lengths - lengtht + 1;i++)
{
if (s.substring(i,lengtht + i) == text)
return i;
}
return -1;
}
var s = 'Hello!';
var text = 'llo';
if (Myindexof(s,text) > -1)
Logger.log('yes');
else
Logger.log('no');
For Xcode 12: (beta 3)
For the code editing windows, use the new
Editor -> Font Size -> Increase
or
Editor -> Font Size -> Decrease
menu items. This globally increases or decreases the font sizes for all editing windows. There is also an
Editor -> Font Size -> Reset
option. These also respond to the ?+ or ?- keyboard shortcuts.
By default, the file navigator on the left side corresponds to the
System Preferences -> General -> Sidebar icon size
You can also override the system size inside Xcode using the
Xcode -> Preferences -> General -> Navigator Size
Just a quick warning - if you want to test in Internet Explorer without removing all console.log()'s, you'll need to use Firebug Lite or you'll get some not particularly friendly errors.
(Or create your own console.log() which just returns false.)
They changed the packaging for psycopg2. Installing the binary version fixed this issue for me. The above answers still hold up if you want to compile the binary yourself.
See http://initd.org/psycopg/docs/news.html#what-s-new-in-psycopg-2-8.
Binary packages no longer installed by default. The ‘psycopg2-binary’ package must be used explicitly.
And http://initd.org/psycopg/docs/install.html#binary-install-from-pypi
So if you don't need to compile your own binary, use:
pip install psycopg2-binary
I did it like this:
>>> utc_delta = datetime.utcnow()-datetime.now()
>>> utc_time = datetime(2008, 9, 17, 14, 2, 0) + utc_delta
>>> print(utc_time)
2008-09-17 19:01:59.999996
If you want to get fancy, you can turn this into a functor:
class to_utc():
utc_delta = datetime.utcnow() - datetime.now()
def __call__(cls, t):
return t + cls.utc_delta
Result:
>>> utc_converter = to_utc()
>>> print(utc_converter(datetime(2008, 9, 17, 14, 2, 0)))
2008-09-17 19:01:59.999996
You can use this command,
jmeter -n -t /path to the script.jmx -l /path to save results with file name file.jtl
But if you really want to run a load test in a remote machine, you should be able to make it run eventhough you close the window. So we can use nohup to ignore the HUP (hangup) signal. So you can use this command as below.
nohup sh jmeter.sh -n -t /path to the script.jmx -l /path to save results with file name file.jtl &
I am going to contribute another possible solution, one that worked for me. I was using the convenience index to collection all components into one file.
I don't believe at the time of writing this is officially supported by babel, and throws typescript into a spin - however I've seen it used in many projects and is definitely convenient.
However, when used in combination with inheritance it seems to throw the error presented in the question above.
A simple solution is, for modules that act as parents need to be imported directly instead of via a convenience index file.
./src/components/index.js
export Com1 from './com-1/Com1';
export Com2 from './com-2/Com2';
export Com3 from './com-3/Com3';
export Parent1 from './parent/Parent1';
./src/components/com-1/Com1.js
import { Com2, Com3 } from '../index';
// This works fine
class Com1 {
render() {
return (
<div>
<Com2 {...things} />
<Com3 {...things} />
</div>
);
}
}
./src/components/com-3/Com3.js
import { Parent } from '../index';
// This does _not_ work
class Com3 extends Parent {
}
./src/components/com-3/Com3.js
import Parent from '../parent/Parent';
// This does work
class Com3 extends Parent {
}
Have you looked into ZXING? I've been using it successfully to create barcodes. You can see a full working example in the bitcoin application src
// this is a small sample use of the QRCodeEncoder class from zxing
try {
// generate a 150x150 QR code
Bitmap bm = encodeAsBitmap(barcode_content, BarcodeFormat.QR_CODE, 150, 150);
if(bm != null) {
image_view.setImageBitmap(bm);
}
} catch (WriterException e) { //eek }
Don't use git reset --hard
. That will wipe their changes which may well be completely undesirable. Instead:
git pull
git reset origin/master
git checkout <file1> <file2> ...
You can of course use git fetch
instead of git pull
since it clearly isn't going to merge, but if you usually pull it makes sense to continue to pull here.
So what happens here is that git pull
updates your origin/master reference; git reset
updates your local branch reference on to be the same as origin/master without updating any files, so your checked-out state is unchanged; then git checkout
reverts files to your local branch index state as needed. In cases where exactly the same file has been added on live and on upstream master, the index already matches the file following the reset, so in the common case you don't need to do git checkout
at all.
If the upstream branch also contains commits which you want to apply automatically, you can follow a subtle variation on the process:
git pull
git merge <commit before problem commit>
git reset <problem commit>
git checkout <file1> <file2> ...
git pull
Use HAVING MIN(...)
Something like:
SELECT MIN(price) AS price, pricegroup
FROM articles_prices
WHERE articleID=10
GROUP BY pricegroup
HAVING MIN(price) > 0;
res.setHeader('Access-Control-Allow-Headers',
'Access-Control-Allow-Headers, Origin,OPTIONS,Accept,Authorization, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers');
Blockquote : you have to add OPTIONS & Authorization to the setHeader()
this change has fixed my problem, just give a try!
If you actually want a small editor for simple housekeeping in a docker, use this in your Dockerfile:
RUN apt-get install -y busybox && ln -s /bin/busybox /bin/vi
I used it on an Ubuntu 18 based docker.
(Of course you might need an RUN apt-get update
before it but if you are making your own Docker file you probably already have that.)
You can use SSH and SFTP as suggested here.
sftp -P 2222 [email protected]
; if you prefer a graphical interface, you can use FileZillaReplace user
and 10.0.2.15
with the appropriate values relevant to your configuration.