let startDate = moment(new Date('2017-05-12')); // yyyy-MM-dd
let endDate = moment(new Date('2018-09-14')); // yyyy-MM-dd
let Years = newDate.diff(date, 'years');
let months = newDate.diff(date, 'months');
let days = newDate.diff(date, 'days');
console.log("Year: " + Years, ", Month: " months-(Years*12), ", Days: " days-(Years*365.25)-((365.25*(days- (Years*12)))/12));
Above snippet will print: Year: 1, Month: 4, Days: 2
By the way, in Notepad++ there's built-in plugin that can handle this:
TextFX -> TextFX Edit -> Delete Blank Lines
(first press CTRL+A to select all).
Comment to Skelly's really helpful workaround: in Bootstrap-sass 3.3.6, utilities.scss, line 19: .pull-left
has float:left !important
. Since that, I recommend to use !important in his CSS as well:
.dropdown-submenu.pull-left {
float:none !important;
}
I think a suitable replacement for when you have three to five screens of equal importance is the BottomNavigationActivity,this can be used to switch fragments.
You will notice a wizard exists for this in Android Studio, take care however as Android Studio has a tendency to produce overly complex boiler plate code.
A tutorial can be found here: https://android.jlelse.eu/ultimate-guide-to-bottom-navigation-on-android-75e4efb8105f
Another quality tutorial can be found at Android Hive here: https://www.androidhive.info/2017/12/android-working-with-bottom-navigation/
Just set the property of textbox that is
PasswordChar and set the *
as a property
of textbox. That will work for password.
passwordtextbox.PasswordChar = '*';
where passwordtextbox
is the text box name.
Copy and Paste Your .html file in the assets folder of your Project and add below code in your Activity on onCreate().
WebView view = new WebView(this);
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl("file:///android_asset/**YOUR FILE NAME**.html");
view.setBackgroundColor(Color.TRANSPARENT);
setContentView(view);
As mentioned by @pinouchon you can pass it with the help of array index
my_array[0] value
my_array[1] value
In addition to this, to pass list of hashes, you can follow something like:
my_array[0][key1] value1
my_array[0][key2] value2
Example:
To pass param1=[{name:test_name, value:test_value}, {...}]
param1[0][name] test_name
param1[0][value] test_value
This is a modified version of Tim Post's method; I used /dev/tty instead of /dev/stdout. I don't know why it doesn't work with stdout (which is a link to /proc/self/fd/1):
freopen("log.txt","w",stdout);
...
...
freopen("/dev/tty","w",stdout);
By using /dev/tty the output is redirected to the terminal from where the app was launched.
Hope this info is useful.
NB.: Now instead of
runProguard false
you'll need to use
minifyEnabled false
It will work for sure
import java.io.*;
import java.util.*;
public class JavaPingExampleProgram
{
public static void main(String args[])
throws IOException
{
// create the ping command as a list of strings
JavaPingExampleProgram ping = new JavaPingExampleProgram();
List<String> commands = new ArrayList<String>();
commands.add("ping");
commands.add("-c");
commands.add("5");
commands.add("74.125.236.73");
ping.doCommand(commands);
}
public void doCommand(List<String> command)
throws IOException
{
String s = null;
ProcessBuilder pb = new ProcessBuilder(command);
Process process = pb.start();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null)
{
System.out.println(s);
}
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null)
{
System.out.println(s);
}
}
}
If by all permissions you mean 777
Navigate to folder and
chmod -R 777 .
I believe, it is not possible to mock constructors using mockito. Instead, I suggest following approach
Class First {
private Second second;
public First(int num, String str) {
if(second== null)
{
//when junit runs, you get the mocked object(not null), hence don't
//initialize
second = new Second(str);
}
this.num = num;
}
... // some other methods
}
And, for test:
class TestFirst{
@InjectMock
First first;//inject mock the real testable class
@Mock
Second second
testMethod(){
//now you can play around with any method of the Second class using its
//mocked object(second),like:
when(second.getSomething(String.class)).thenReturn(null);
}
}
None of these answers work if the variable is an uninitialized generic type
And from what I can find, it's only possible using an extremely ugly workaround, or by passing in an initialized parameter to your function, making it in-place, see here:
<T> T MyMethod(...){ if(T.class == MyClass.class){...}}
Is NOT valid because you cannot pull the type out of the T
parameter directly, since it is erased at runtime time.
<T> void MyMethod(T out, ...){ if(out.getClass() == MyClass.class){...}}
This works because the caller is responsible to instantiating the variable out
before calling. This will still throw an exception if out is null when called, but compared to the linked solution, this is by far the easiest way to do this
I know this is a kind of specific application, but since this is the first result on google for finding the type of a variable with java (and given that T
is a kind of variable), I feel it should be included
From the doc:
:write ++enc=utf-8 russian.txt
So you should be able to change the encoding as part of the write command.
Accessing colors from a non-activity class can be difficult. One of the alternatives that I found was using enum
. enum
offers a lot of flexibility.
public enum Colors
{
COLOR0(0x26, 0x32, 0x38), // R, G, B
COLOR1(0xD8, 0x1B, 0x60),
COLOR2(0xFF, 0xFF, 0x72),
COLOR3(0x64, 0xDD, 0x17);
private final int R;
private final int G;
private final int B;
Colors(final int R, final int G, final int B)
{
this.R = R;
this.G = G;
this.B = B;
}
public int getColor()
{
return (R & 0xff) << 16 | (G & 0xff) << 8 | (B & 0xff);
}
public int getR()
{
return R;
}
public int getG()
{
return G;
}
public int getB()
{
return B;
}
}
rlang::has_name()
can do this too:
foo = list(a = 1, bb = NULL)
rlang::has_name(foo, "a") # TRUE
rlang::has_name(foo, "b") # FALSE. No partial matching
rlang::has_name(foo, "bb") # TRUE. Handles NULL correctly
rlang::has_name(foo, "c") # FALSE
As you can see, it inherently handles all the cases that @Tommy showed how to handle using base R and works for lists with unnamed items. I would still recommend exists("bb", where = foo)
as proposed in another answer for readability, but has_name
is an alternative if you have unnamed items.
Try this
keys = [next(iter(x.keys())) for x in test]
print(list(keys))
The result looks like this. ['foo', 'hello']
You can find more possible solutions here.
To close this question, what seemed to have worked is indeed running
docker-compose stop
docker-compose rm -f
docker-compose -f docker-compose.yml up -d
I.e. remove the containers before running up
again.
What one needs to keep in mind when doing it like this is that data volume containers are removed as well if you just run rm -f
. In order to prevent that I specify explicitly each container to remove:
docker-compose rm -f application nginx php
As I said in my question, I don't know if this is the correct process. But this seems to work for our use case, so until we find a better solution we'll roll with this one.
I confirm. We must add:
webPreferences: {
nodeIntegration: true
}
For example:
mainWindow = new BrowserWindow({webPreferences: {
nodeIntegration: true
}});
For me, the problem has been resolved with that.
Using the .EditedFormattedValue property solves the problem
To be notified each time a checkbox in a cell toggles a value when clicked, you can use the CellContentClick event and access the preliminary cell value .EditedFormattedValue.
As the event is fired the .EditedFormattedValue is not yet applied visually to the checkbox and not yet committed to the .Value property.
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
var checkbox = dataGridView1.CurrentCell as DataGridViewCheckBoxCell;
bool isChecked = (bool)checkbox.EditedFormattedValue;
}
The event fires on each Click and the .EditedFormattedValue toggles
Use CONVERT
with the Value
specifier of 101
, whilst casting your data to date
:
CONVERT(VARCHAR(10), CAST(Created_TS AS DATE), 101)
java.lang.UnsupportedClassVersionError
happens because of a higher JDK during compile time and lower JDK during runtime.
Here's the list of versions:
Java SE 9 = 53,
Java SE 8 = 52,
Java SE 7 = 51,
Java SE 6.0 = 50,
Java SE 5.0 = 49,
JDK 1.4 = 48,
JDK 1.3 = 47,
JDK 1.2 = 46,
JDK 1.1 = 45
In my case it was Avast Antivirus interfering with the connection. Actions to disable this feature: Avast -> Settings-> Components -> Mail Shield (Customize) -> SSL scanning -> uncheck "Scan SSL connections".
If you search for an image base-64 converter, you can embed some small image texture files as code into your @import url('')
section of code. It will look like a lot of code; but at least all your data is now stored locally - rather than having to call a separate resource to load the image.
Example link: http://www.base64-image.de/
When I take a file from my own inventory of a simple icon in PNG format, and convert it to base-64, it looks like this in my CSS:
url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAm0SURBVHjaRFdLrF1lFf72++xzzj33nMPt7QuhxNJCY4smGomKCQlWxMSJgQ4dyEATE3FCSDRxjnHiwMTUAdHowIGJOqBEg0RDCCESKIgCWtqCfd33eeyz39vvW/vcctvz2nv/61/rW9/61vqd7CIewMT5VlnChf059t40QBwB7io+vjx3kczb++D9Tof3x1xWNu39hP9nHhxH62t0u7zWb9rFtl73G1veXamrs98rf+5Pbjnnnv5p+IPNiQvXreF7AZ914bgOv/PBOIDH767HH/DgO4F9d7hLHPkYrIRw+d1x2/sufBRViboCgkCvBmmWcw2v5zWStABv4+iBOe49enXqb2x4a79+wYfidx2XRgP4vm8QBLTgBx4CLva4QRjyO+9FUUjndD1ATJjkgNaEoW/R6ZmyqgxFvU3nCTzaqLhzURSoGWJ82cN9d3r3+Z5TV6srni30fAdNXSP0a3ToiCHvVuh1mQsua+gl98Zqz0PNEIOAv4OidZToNU1OG8TAbUC7qGirdV6bV0SGa3gvISKrPUcoFj5xt/S4xDtktFVZMRrXItDiKAxRFiVh9HH2y+s05OHVizvod+mJ4yEnebSOROCzAfJ5ZgRxGHmXzwQ+U+aKFJ5oQ8fllGfp0XM+f0OsaaoaHnPq8U4YtFAqz0rL+riDR7+4guPrGaK4i8+dWMdotYdBf8CIPaatgzCKEHdi7hPRTg9uvIoLL76DC39+DcN+F4s8ZaAOCkYfEOmCQenPl3ftho4xmxcYfcmcCZGAMALjUYBvf2WM3//pDcwZoVKSzyNUowHGa2Pc0R9iOFjFcMSHhwxtQHNjDye+8Bht1Hj+wpsCy3i0N19gY3sPZ+5ty8uXVyFh8jyXm7EW+RkwZ47jmjNFJXKEGJ06g8ebDi5vptjYnWJvj68iR87vO2R3b0bHtmck4jYOjVYQuR8gHr2L73z3NN68eBm3NqbGo7gTMoAu6qatbV8wi70iiCL2/ZaQIfPZYf59eiBYcfdXMbj7NJ55+Cf4x1sfYkUiYSZ3jbie267LyKFPfXKI809/BjsfXMPpPMPjZ4/g2fNvg5mywEaDFa5JSNpGDihSMZU64Dlkr2uElCqVJFhJV4UEsMLXacTdIY4cSCwNYrdSKEOeZ1Q2Qv7n6iZ+99IlPHCwwot/3cDxU/dynWdk3v9ToJVs101lP1zWrgzJjGwpFULBzWs0t6WwINNd3HnwgPHGZbUIpZIIqFpqcqcbx2R4jJcv3sLdD6Z4+587JG6Fg+MAl6+1xAZajShLiR/Z4Wszwh9zw7gTWemYoFgZtvxgUsyJcOl5oOtcW0uwpHKMTrbmSYLVfoyk6OLUqZM4uNbF1asf4cBKTkHKuGll61MqYl0JXXrU68ao5RjRUNk5vpQtMkmuyQ1Yrb7H15qRJwj2hUvpkxPUfTpeSX+ZljTNMZmXOHLsJJ48t4KbWzso329w4ZUNOuuaGrpMiVBw95uPR0csWhrsdTv2aSXK+vYIPfK/86m/8VpDKe7cblAtOjClExpCQtfSJMVOcBL+I9/A0bMP4cFP32NaoHQrCD2vunddzwTbUqA8Rp2gLUEJDKOS5ktmceMScP1dNpQCi6Tk3gGBabBIMxmhdtS2eV21FRGFEa5f36Ht+4HRw7jnzEOMlmsXKbI8NxQkAf5w6FD3QyNU20Rqay5Mj5GwMS9ZDTf/S+MhTnyiD9w1RK/XwTvv7xqRxKG8rFoSEzUJmch2a3PXCtVY3+tzuwZ50d7LGYhs+8qnOlrJHRtGpM3F8IqkUDRMLzepceNGQjHZxFPfHGJ1MKMTx/DMDz1c/rCy3NdNc1u+hYQSu8gFc2R9Qn8qaVF5v71rhV+r+ZA46myN8iiPJcl+YAQTS8TByZ6Dm9cb7O7usgNu4+T2BJvbazQxREG9EHo5YVUqFWmWMx3FhPc3IG3O0tIqQMaLggZj64aQ5toEo1w7hDLJarBCrBv2SUb1gpSOTCYNtjYqE5QgcrC7UxtitfX/wHIqIs+ThTnuqP8vrvPu83wdxtbNErMkp050DLGcPNCw4jtUuR7FQ4YWWYlzjw5wZJSwZoXEzEpuPkvRFBk0FtQFiZext6eOkdV1GBFTFAStFoiA83RBljfoRZzR/vdvDhA7eOftGerSMfbnRMcjlWwCExOlhjVFZJIU+PqXYqyevAJc2cJ8K8KlzRDFSoXd6RCDO2GbiS83FyusdTJewxP7ha7LeJoVbU/gJr6zg/zyFYRHZnj9YorabTki5CRGxgFYvgoSMVBxYpYGWB0dZ+ncg9d/VeKRJ1/FGtuxmF4pHyp7Qd9McezoHTh8IG51QE6oFMtWB+KY82J3gX+9N8MJ9xZeeSNDh2gusgwpn8mLZXUIxsDGk8aYmU83We8sn/EYvf4Yp08cZvPpGbzyuVr2CxMvEyENpLCB0+Y93q8KDbcVIke8qXGpW+Kt9xc2U+oZIZCXRTsRzea+abgm2YybTKc587YH8LNOGoyHKrvISrGNHuaIUNPoXTF9FYlbL0tRk9WMLD60RpImFCmOYn95rcH2XoW1VXc5Z/LVOK0QZWllRhSWCDWdpsg/ShAOK+xMBtie5lailSlcKzgWad1+qnekWWojuSon10heB3jqCYpYlmD98AjPPbdLojsMsK0UNSH9k5KqB1tX23dCjeTGjRzhdoED4QTff2Idh8YhK8CxuVgGoDLT6KZzAk8navN1vocimZCYKdaHCe5f2+AGfTz7h5zzAW2NQrKfaRJqFZYtXkLEN83tIcdwTbJXthwMj64jM/hdPPZZ1rWXstY9SjbTxTyio5ZI/uocEPF3OCIAh0kEcifZQbO7wT4Q4Jd/3MbPfnuNLbnHlFXYP1KpAjTsiEu+8uiYmHh2FPvx+Q8NSqFScEaUUtoMQQLoWXmuKbu2SmjssKH7MqrkNstzXcnjWsXX0YN944/WFrJlnbO2IWY5lMIOEMkiMxk9cdchu6nGUi6xUr4ko4I9YxmpWozNS/0vjBeVafx+dNZofHdZ722FqOKKsp2GHBNspaCq/e0pdSByLRKeifhZW3cET0U6SIg03ZglqgEV7TGMMxQluzQnijLntdCMS2Z1DlyQS1nRmGhlWeu8KsRxWjscF3itcfz+ILv5tc9vYGui+a6FUP0ey8OymF812qD1WPOATkeSUxMgpklqaNMQS6soVSGu1Xpp3ZTNLsBSQ9oUSIPuO9aQsKj8H/2i+M14cIVV5UZZThrWikhQtOdEhxOqH1ZQI6PysyQdO93q/KdeHbC/hp2P+aG3PG1aiCVahDWIm49p77RHf/LHfeFlvPR/AQYAyMIq/fJRUogAAAAASUVORK5CYII=')
With your texture images, you'll want to employ a similar process.
You can try this:
//Your class instance
Publication publication = new Publication();
//Get class with full path(with package name)
Class<?> c = Class.forName("com.example.publication.models.Publication");
//Get method
Method method = c.getDeclaredMethod ("setTitle", String.class);
//set value
method.invoke (publication, "Value to want to set here...");
You can use .indexOf()
and .substr()
like this:
var val = $("input").val();
var myString = val.substr(val.indexOf("?") + 1)
You can test it out here. If you're sure of the format and there's only one question mark, you can just do this:
var myString = $("input").val().split("?").pop();
I think this issue following model class wrong import.
import org.springframework.data.annotation.Id;
Normally, it should be:
import javax.persistence.Id;
Any reason they can't just click on the tab for your sheet when they want it?
You are checking Parent
properties for null in your delegate. The same should work with lambda expressions too.
List<AnalysisObject> analysisObjects = analysisObjectRepository
.FindAll()
.Where(x =>
(x.ID == packageId) ||
(x.Parent != null &&
(x.Parent.ID == packageId ||
(x.Parent.Parent != null && x.Parent.Parent.ID == packageId)))
.ToList();
A fast solution is using the gnu utility truncate
:
[ -z $(tail -c1 file) ] && truncate -s-1 file
The test will be true if the file does have a trailing new line.
The removal is very fast, truly in place, no new file is needed and the search is also reading from the end just one byte (tail -c1
).
Here is an example of Jon Adams suggestion above in order to fix a div (toolbar) to the right hand side of your page element using jQuery. The idea is to find the distance from the right hand side of the viewport to the right hand side of the page element and to keep the right hand side of the toolbar there!
<div id="pageElement"></div>
<div id="toolbar"></div>
#toolbar {
position: fixed;
}
....
function placeOnRightHandEdgeOfElement(toolbar, pageElement) {
$(toolbar).css("right", $(window).scrollLeft() + $(window).width()
- $(pageElement).offset().left
- parseInt($(pageElement).css("borderLeftWidth"),10)
- $(pageElement).width() + "px");
}
$(document).ready(function() {
$(window).resize(function() {
placeOnRightHandEdgeOfElement("#toolbar", "#pageElement");
});
$(window).scroll(function () {
placeOnRightHandEdgeOfElement("#toolbar", "#pageElement");
});
$("#toolbar").resize();
});
Below code will give the output for number of days, by taking out the difference between two dates..
$str = "Jul 02 2013";
$str = strtotime(date("M d Y ")) - (strtotime($str));
echo floor($str/3600/24);
If you just want to show label below the marker, then you can extend google maps Marker to add a setter method for label and you can define the label object by extending google maps overlayView like this..
<script type="text/javascript">
var point = { lat: 22.5667, lng: 88.3667 };
var markerSize = { x: 22, y: 40 };
google.maps.Marker.prototype.setLabel = function(label){
this.label = new MarkerLabel({
map: this.map,
marker: this,
text: label
});
this.label.bindTo('position', this, 'position');
};
var MarkerLabel = function(options) {
this.setValues(options);
this.span = document.createElement('span');
this.span.className = 'map-marker-label';
};
MarkerLabel.prototype = $.extend(new google.maps.OverlayView(), {
onAdd: function() {
this.getPanes().overlayImage.appendChild(this.span);
var self = this;
this.listeners = [
google.maps.event.addListener(this, 'position_changed', function() { self.draw(); })];
},
draw: function() {
var text = String(this.get('text'));
var position = this.getProjection().fromLatLngToDivPixel(this.get('position'));
this.span.innerHTML = text;
this.span.style.left = (position.x - (markerSize.x / 2)) - (text.length * 3) + 10 + 'px';
this.span.style.top = (position.y - markerSize.y + 40) + 'px';
}
});
function initialize(){
var myLatLng = new google.maps.LatLng(point.lat, point.lng);
var gmap = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 5,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var myMarker = new google.maps.Marker({
map: gmap,
position: myLatLng,
label: 'Hello World!',
draggable: true
});
}
</script>
<style>
.map-marker-label{
position: absolute;
color: blue;
font-size: 16px;
font-weight: bold;
}
</style>
This will work.
Remove the course_enrollment_settings.base_price
immediately after CASE
:
SELECT
CASE
WHEN course_enrollment_settings.base_price = 0 THEN 1
...
END
CASE
has two different forms, as detailed in the manual. Here, you want the second form since you're using search conditions.
I had a similar issue reading the serial output from a digital scale. I was reading [3:12] out of a 18 characters long output string.
In my case sometimes there is a null character "\x00" (NUL) which magically appears in the scale's reply string and is not printed.
I was getting the error:
> ' 0.00'
> 3 0 fast loop, delta = 10.0 weight = 0.0
> ' 0.00'
> 1 800 fast loop, delta = 10.0 weight = 0.0
> ' 0.00'
> 6 0 fast loop, delta = 10.0 weight = 0.0
> ' 0\x00.0'
> Traceback (most recent call last):
> File "measure_weight_speed.py", line 172, in start
> valueScale = float(answer_string)
> ValueError: invalid literal for float(): 0
After some research I wrote few lines of code that work in my case.
replyScale = scale_port.read(18)
answer = replyScale[3:12]
answer_decode = answer.replace("\x00", "")
answer_strip = str(answer_decode.strip())
print(repr(answer_strip))
valueScale = float(answer_strip)
The answers in these posts helped:
Try requests instead of urllib and you don't need to bother with urlencode!
import requests
requests.get('http://youraddress.com', params=evt.fields)
EDIT:
If you need ordered name-value pairs or multiple values for a name then set params like so:
params=[('name1','value11'), ('name1','value12'), ('name2','value21'), ...]
instead of using a dictionary.
Since that method is static, it already has everything you need to use it, so it defeats the purpose of mocking. Mocking the static methods is considered to be a bad practice.
If you try to do that, it means there is something wrong with the way you want to perform testing.
Of course you can use PowerMockito or any other framework capable of doing that, but try to rethink your approach.
For example: try to mock/provide the objects, which that static method consumes instead.
svn revert . -R
to reset everything.
svn revert path/to/file
for a single file
Think of "BeforeClass" as a static initializer for your test case - use it for initializing static data - things that do not change across your test cases. You definitely want to be careful about static resources that are not thread safe.
Finally, use the "AfterClass" annotated method to clean up any setup you did in the "BeforeClass" annotated method (unless their self destruction is good enough).
"Before" & "After" are for unit test specific initialization. I typically use these methods to initialize / re-initialize the mocks of my dependencies. Obviously, this initialization is not specific to a unit test, but general to all unit tests.
that's simple:
A <cookie-name> can be any US-ASCII characters except control characters (CTLs), spaces, or tabs. It also must not contain a separator character like the following: ( ) < > @ , ; : \ " / [ ] ? = { }.
A <cookie-value> can optionally be set in double quotes and any US-ASCII characters excluding CTLs, whitespace, double quotes, comma, semicolon, and backslash are allowed. Encoding: Many implementations perform URL encoding on cookie values, however it is not required per the RFC specification. It does help satisfying the requirements about which characters are allowed for though.
Link: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#Directives
It might be worth adding here there are a few pointers when using the @ you should be aware of, for a complete run down view this post: http://mstd.eu/index.php/2016/06/30/php-rapid-fire-what-is-the-symbol-used-for-in-php/
The error handler is still fired even with the @ symbol prepended, it just means a error level of 0 is set, this will have to be handled appropriately in a custom error handler.
Prepending a include with @ will set all errors in the include file to an error level of 0
The question is tagged "php" so as Tom said, the way to do that would look like this:
date('Y-m-d', strtotime('next tuesday'));
If you put position:relative;
on the outer element, the inner element will place itself according to this one. Then a width:auto;
on the inner element will be the same as the width of the outer.
You can delete the "work" directory.
Are you sure it's not a browser caching issue?
Html Code:
<form class="validateDontSubmit">
....
<button style="dislay:none">submit</button>
</form>
<button class="outside"></button>
javascript( using Jquery):
<script type="text/javascript">
$(document).on('submit','.validateDontSubmit',function (e) {
//prevent the form from doing a submit
e.preventDefault();
return false;
})
$(document).ready(function(){
// using button outside trigger click
$('.outside').click(function() {
$('.validateDontSubmit button').trigger('click');
});
});
</script>
Hope this will help you
I would just create a separate CSS class:
.ButtonClicked {
background-color:red;
}
And then add the class on click:
$('#ButtonId').on('click',function(){
!$(this).hasClass('ButtonClicked') ? addClass('ButtonClicked') : '';
});
This should do what you're looking for, showing by this jsFiddle. If you're curious about the logic with the ?
and such, its called ternary (or conditional) operators, and its just a concise way to do the simple if logic to check if the class has already been added.
You can also create the ability to have an "on/off" switch feel by toggling the class:
$('#ButtonId').on('click',function(){
$(this).toggleClass('ButtonClicked');
});
Shown by this jsFiddle. Just food for thought.
That's the non-null assertion operator. It is a way to tell the compiler "this expression cannot be null
or undefined
here, so don't complain about the possibility of it being null
or undefined
." Sometimes the type checker is unable to make that determination itself.
It is explained here:
A new
!
post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. Specifically, the operationx!
produces a value of the type ofx
withnull
andundefined
excluded. Similar to type assertions of the forms<T>x
andx as T
, the!
non-null assertion operator is simply removed in the emitted JavaScript code.
I find the use of the term "assert" a bit misleading in that explanation. It is "assert" in the sense that the developer is asserting it, not in the sense that a test is going to be performed. The last line indeed indicates that it results in no JavaScript code being emitted.
If you apply utf8_encode()
to an already UTF8 string it will return a garbled UTF8 output.
I made a function that addresses all this issues. It´s called Encoding::toUTF8()
.
You dont need to know what the encoding of your strings is. It can be Latin1 (ISO8859-1), Windows-1252 or UTF8, or the string can have a mix of them. Encoding::toUTF8()
will convert everything to UTF8.
I did it because a service was giving me a feed of data all messed up, mixing those encodings in the same string.
Usage:
require_once('Encoding.php');
use \ForceUTF8\Encoding; // It's namespaced now.
$utf8_string = Encoding::toUTF8($mixed_string);
$latin1_string = Encoding::toLatin1($mixed_string);
I've included another function, Encoding::fixUTF8(), which will fix every UTF8 string that looks garbled product of having been encoded into UTF8 multiple times.
Usage:
require_once('Encoding.php');
use \ForceUTF8\Encoding; // It's namespaced now.
$utf8_string = Encoding::fixUTF8($garbled_utf8_string);
Examples:
echo Encoding::fixUTF8("Fédération Camerounaise de Football");
echo Encoding::fixUTF8("Fédération Camerounaise de Football");
echo Encoding::fixUTF8("FÃÂédÃÂération Camerounaise de Football");
echo Encoding::fixUTF8("Fédération Camerounaise de Football");
will output:
Fédération Camerounaise de Football
Fédération Camerounaise de Football
Fédération Camerounaise de Football
Fédération Camerounaise de Football
Download:
You can use the function below which replaces the first occurrence of the word from right.
def replace_from_right(text: str, original_text: str, new_text: str) -> str:
""" Replace first occurrence of original_text by new_text. """
return text[::-1].replace(original_text[::-1], new_text[::-1], 1)[::-1]
If you want to insert text inside your EditText view that stays there after the field is selected (unlike how hint behaves), do this:
In Java:
// Cast Your EditText as a TextView
((TextView) findViewById(R.id.email)).setText("your Text")
In Kotlin:
// Cast your EditText into a TextView
// Like this
(findViewById(R.id.email) as TextView).text = "Your Text"
// Or simply like this
findViewById<TextView>(R.id.email).text = "Your Text"
OCR which stands for Optical Character Recognition is a computer vision technique used to identify the different types of handwritten digits that are used in common mathematics. To perform OCR in OpenCV we will use the KNN algorithm which detects the nearest k neighbors of a particular data point and then classifies that data point based on the class type detected for n neighbors.
Data Used
This data contains 5000 handwritten digits where there are 500 digits for every type of digit. Each digit is of 20×20 pixel dimensions. We will split the data such that 250 digits are for training and 250 digits are for testing for every class.
Below is the implementation.
import numpy as np import cv2 # Read the image image = cv2.imread( 'digits.png' ) # gray scale conversion gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # We will divide the image # into 5000 small dimensions # of size 20x20 divisions = list (np.hsplit(i, 100 ) for i in np.vsplit(gray_img, 50 )) # Convert into Numpy array # of size (50,100,20,20) NP_array = np.array(divisions) # Preparing train_data # and test_data. # Size will be (2500,20x20) train_data = NP_array[:,: 50 ].reshape( - 1 , 400 ).astype(np.float32) # Size will be (2500,20x20) test_data = NP_array[:, 50 : 100 ].reshape( - 1 , 400 ).astype(np.float32) # Create 10 different labels # for each type of digit k = np.arange( 10 ) train_labels = np.repeat(k, 250 )[:,np.newaxis] test_labels = np.repeat(k, 250 )[:,np.newaxis] # Initiate kNN classifier knn = cv2.ml.KNearest_create() # perform training of data knn.train(train_data, cv2.ml.ROW_SAMPLE, train_labels) # obtain the output from the # classifier by specifying the # number of neighbors. ret, output ,neighbours, distance = knn.findNearest(test_data, k = 3 ) # Check the performance and # accuracy of the classifier. # Compare the output with test_labels # to find out how many are wrong. matched = output = = test_labels correct_OP = np.count_nonzero(matched) #Calculate the accuracy. accuracy = (correct_OP * 100.0 ) / (output.size) # Display accuracy. print (accuracy) |
Output
91.64
Well, I decided to workout myself on my question to solve the above problem. What I wanted is to implement a simple OCR using KNearest or SVM features in OpenCV. And below is what I did and how. (it is just for learning how to use KNearest for simple OCR purposes).
1) My first question was about letter_recognition.data
file that comes with OpenCV samples. I wanted to know what is inside that file.
It contains a letter, along with 16 features of that letter.
And this SOF
helped me to find it. These 16 features are explained in the paper Letter Recognition Using Holland-Style Adaptive Classifiers
.
(Although I didn't understand some of the features at the end)
2) Since I knew, without understanding all those features, it is difficult to do that method. I tried some other papers, but all were a little difficult for a beginner.
So I just decided to take all the pixel values as my features. (I was not worried about accuracy or performance, I just wanted it to work, at least with the least accuracy)
I took the below image for my training data:
(I know the amount of training data is less. But, since all letters are of the same font and size, I decided to try on this).
To prepare the data for training, I made a small code in OpenCV. It does the following things:
key press manually
. This time we press the digit key ourselves corresponding to the letter in the box..txt
files.At the end of the manual classification of digits, all the digits in the training data (train.png
) are labeled manually by ourselves, image will look like below:
Below is the code I used for the above purpose (of course, not so clean):
import sys
import numpy as np
import cv2
im = cv2.imread('pitrain.png')
im3 = im.copy()
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)
################# Now finding Contours ###################
contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
samples = np.empty((0,100))
responses = []
keys = [i for i in range(48,58)]
for cnt in contours:
if cv2.contourArea(cnt)>50:
[x,y,w,h] = cv2.boundingRect(cnt)
if h>28:
cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),2)
roi = thresh[y:y+h,x:x+w]
roismall = cv2.resize(roi,(10,10))
cv2.imshow('norm',im)
key = cv2.waitKey(0)
if key == 27: # (escape to quit)
sys.exit()
elif key in keys:
responses.append(int(chr(key)))
sample = roismall.reshape((1,100))
samples = np.append(samples,sample,0)
responses = np.array(responses,np.float32)
responses = responses.reshape((responses.size,1))
print "training complete"
np.savetxt('generalsamples.data',samples)
np.savetxt('generalresponses.data',responses)
Now we enter in to training and testing part.
For the testing part, I used the below image, which has the same type of letters I used for the training phase.
For training we do as follows:
.txt
files we already saved earlierFor testing purposes, we do as follows:
I included last two steps (training and testing) in single code below:
import cv2
import numpy as np
####### training part ###############
samples = np.loadtxt('generalsamples.data',np.float32)
responses = np.loadtxt('generalresponses.data',np.float32)
responses = responses.reshape((responses.size,1))
model = cv2.KNearest()
model.train(samples,responses)
############################# testing part #########################
im = cv2.imread('pi.png')
out = np.zeros(im.shape,np.uint8)
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2)
contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
if cv2.contourArea(cnt)>50:
[x,y,w,h] = cv2.boundingRect(cnt)
if h>28:
cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
roi = thresh[y:y+h,x:x+w]
roismall = cv2.resize(roi,(10,10))
roismall = roismall.reshape((1,100))
roismall = np.float32(roismall)
retval, results, neigh_resp, dists = model.find_nearest(roismall, k = 1)
string = str(int((results[0][0])))
cv2.putText(out,string,(x,y+h),0,1,(0,255,0))
cv2.imshow('im',im)
cv2.imshow('out',out)
cv2.waitKey(0)
And it worked, below is the result I got:
Here it worked with 100% accuracy. I assume this is because all the digits are of the same kind and the same size.
But anyway, this is a good start to go for beginners (I hope so).
URLs are case-preserving, between client and server. But portions of URLs may or may not be case-sensitive, depending on the server, for a couple of reasons.
The following bold parts of URLs may be case-sensitive, depending on the site and/or server configuration.
http:// www. example.com /abc/def.ghi?jkl=mno#pqr
user @ example.com
Case-sensitivity in URLs can have several uses. Mainly:
As a developer, I believe the above can often be handled in better ways, but I also understand there are cases where a situation may not permit this.
For example, imagine an existing product that requires a lot of data placed in the "GET" URL, yet it must be compatible with the maximum URL lengths of all major servers, browsers, and caching/proxy mechanisms. To fit even a moderate-length command string (under 1,024 characters for some older browsers), you'd need to use every unique URL-safe character you could (which is basically what base64url encoding is).
Whether or not URLs should be case-sensitive is debatable. I personally believe they should not be, for simplicity (though it may create longer URLs, we have percent-escapes to easily handle cases where we must ensure preservation of exact characters, and there are ways to transfer data other than right in the URL).
Many seem to agree based on the fact that case-insensitive URLs are explicitly enabled for many popular sites and services, in order to increase usability. The most prominent example is the username portion of email addresses. Most email providers will ignore case and sometimes even dots and other symbols (like "[email protected]" being the same as "[email protected]"). Even though email usernames are case-sensitive by default, according to spec.
However, the fact is that despite what I or others might want, this is the state of how things currently work. And while an eventual worldwide transition to a case-insensitive URL standard is certainly possible, it would likely take quite a long time since case-sensitivity is currently used extensively around the web for various purposes.
As far as best practices go, as a user you can reasonably stick to lowercase for most situations and expect things to work. The main exceptions would be URLs that use case-based encoding or document paths with direct filesystem equivalents. However, such complex URLs are typically copy-pasted (or simply clicked) rather than manually typed.
As a web developer, you should consider keeping URLs as case-insensitive as possible. Though there are clearly some difficult-to-avoid situations, depending on context, as noted above.
I don't have Python 2.7 installed, but in Python 3.3 calling Popen
with stdout
set to sys.stdout
worked just fine. Not before I had escaped the backslashes in the path, though.
>>> import subprocess
>>> import sys
>>> p = subprocess.Popen(['powershell.exe', 'C:\\Temp\\test.ps1'], stdout=sys.stdout)
>>> Hello World
_
If you are using tortoise git.
please follow the below steps.
Now your changes moved from BranchA to BranchB
you need to specify the min
and target sdk
version in the manifest file.
If not the android.permission.READ_PHONE_STATE
will be added automaticly while exporting your apk file.
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="19" />
Try this:
CGFloat statusBarHeight = [[UIApplication sharedApplication] statusBarFrame].size.height;
first you need to add 2 columns to datagrid. you may do it at design time. see Columns property. then add rows as much as you need.
this.dataGridView1.Rows.Add("1", "XX");
Make sure you have a service started and listening on the port.
netstat -ln | grep 8080
and
sudo netstat -tulpn
I know this is an old question but just for the record this can also be done by passing appropriate connection options as arguments to the _mysql.connect
call. For example,
con = _mysql.connect(host='localhost', user='dell-pc', passwd='', db='test',
connect_timeout=1000)
Notice the use of keyword parameters (host, passwd, etc.). They improve the readability of your code.
For detail about different arguments that you can pass to _mysql.connect
, see MySQLdb API documentation
The standard way of using merge to undo the entire check-in works great, if that's what you want to do. Sometimes, though, all you want to do is revert a single file. There's no legitimate way to do that, but there is a hack:
Use svn's export subcommand:
svn export http://url-to-your-file@123 /tmp/filename
(Where 123 is the revision number for a good version of the file.) Then either move or copy that single file to overwrite the old one. Check in the modified file and you are done.
java.lang.UnsupportedOperationException
Thrown to indicate that the requested operation is not supported.
Add the following environment variable:
NODE_TLS_REJECT_UNAUTHORIZED=0
e.g. with export
:
export NODE_TLS_REJECT_UNAUTHORIZED=0
(with great thanks to Juanra)
I found very good link for JSON: http://code.google.com/p/json-simple/wiki/EncodingExamples#Example_1-1_-_Encode_a_JSON_object
Here's code to add multiple JSONObjects to JSONArray.
JSONArray Obj = new JSONArray();
try {
for(int i = 0; i < 3; i++) {
// 1st object
JSONObject list1 = new JSONObject();
list1.put("val1",i+1);
list1.put("val2",i+2);
list1.put("val3",i+3);
obj.put(list1);
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Toast.makeText(MainActivity.this, ""+obj, Toast.LENGTH_LONG).show();
I'm not amazing at PHP, but I think this is what you do:
$password = md5($password)
and $password
would be the $_POST['password']
or whatever
In Firefox, https://bug743252.bugzilla.mozilla.org/attachment.cgi?id=714383 (view page source :: tag HTML).
In your code, replace <html>
with <html moznomarginboxes mozdisallowselectionprint>
.
In others browsers, I don't know, but you can view http://www.mintprintables.com/print-tips/header-footer-windows/
Set the colspan
attribute to 2.
An immediately-invoked function expression (IIFE) immediately calls a function. This simply means that the function is executed immediately after the completion of the definition.
Three more common wordings:
// Crockford's preference - parens on the inside
(function() {
console.log('Welcome to the Internet. Please follow me.');
}());
//The OPs example, parentheses on the outside
(function() {
console.log('Welcome to the Internet. Please follow me.');
})();
//Using the exclamation mark operator
//https://stackoverflow.com/a/5654929/1175496
!function() {
console.log('Welcome to the Internet. Please follow me.');
}();
If there are no special requirements for its return value, then we can write:
!function(){}(); // => true
~function(){}(); // => -1
+function(){}(); // => NaN
-function(){}(); // => NaN
Alternatively, it can be:
~(function(){})();
void function(){}();
true && function(){ /* code */ }();
15.0, function(){ /* code */ }();
You can even write:
new function(){ /* code */ }
31.new function(){ /* code */ }() //If no parameters, the last () is not required
The os.exec*()
functions replace the current programm with the new one. When this programm ends so does your process. You probably want os.system()
.
In my case, i tried all solutions but nothing worked.
My SO is windows 7 x64, with all the Redistributable Packages (x86,x64 / 2010,2013,2015)
The problem was that i tried to install the x64 workbench, but for some reason did not work (even my SO is x64).
so, the solution was download the x86 installer from : https://downloads.mysql.com/archives/workbench/
when should we use it
Quentin's answer is right: use multipart/form-data
if the form contains a file upload, and application/x-www-form-urlencoded
otherwise, which is the default if you omit enctype
.
I'm going to:
There are three possibilities for enctype
:
application/x-www-form-urlencoded
multipart/form-data
(spec points to RFC7578)text/plain
. This is "not reliably interpretable by computer", so it should never be used in production, and we will not look further into it.Once you see an example of each method, it becomes obvious how they work, and when you should use each one.
You can produce examples using:
nc -l
or an ECHO server: HTTP test server accepting GET/POST requestsSave the form to a minimal .html
file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>upload</title>
</head>
<body>
<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
<p><input type="text" name="text1" value="text default">
<p><input type="text" name="text2" value="aωb">
<p><input type="file" name="file1">
<p><input type="file" name="file2">
<p><input type="file" name="file3">
<p><button type="submit">Submit</button>
</form>
</body>
</html>
We set the default text value to aωb
, which means a?b
because ?
is U+03C9
, which are the bytes 61 CF 89 62
in UTF-8.
Create files to upload:
echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html
# Binary file containing 4 bytes: 'a', 1, 2 and 'b'.
printf 'a\xCF\x89b' > binary
Run our little echo server:
while true; do printf '' | nc -l 8000 localhost; done
Open the HTML on your browser, select the files and click on submit and check the terminal.
nc
prints the request received.
Tested on: Ubuntu 14.04.3, nc
BSD 1.105, Firefox 40.
Firefox sent:
POST / HTTP/1.1
[[ Less interesting headers ... ]]
Content-Type: multipart/form-data; boundary=---------------------------735323031399963166993862150
Content-Length: 834
-----------------------------735323031399963166993862150
Content-Disposition: form-data; name="text1"
text default
-----------------------------735323031399963166993862150
Content-Disposition: form-data; name="text2"
a?b
-----------------------------735323031399963166993862150
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain
Content of a.txt.
-----------------------------735323031399963166993862150
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html
<!DOCTYPE html><title>Content of a.html.</title>
-----------------------------735323031399963166993862150
Content-Disposition: form-data; name="file3"; filename="binary"
Content-Type: application/octet-stream
a?b
-----------------------------735323031399963166993862150--
For the binary file and text field, the bytes 61 CF 89 62
(a?b
in UTF-8) are sent literally. You could verify that with nc -l localhost 8000 | hd
, which says that the bytes:
61 CF 89 62
were sent (61
== 'a' and 62
== 'b').
Therefore it is clear that:
Content-Type: multipart/form-data; boundary=---------------------------735323031399963166993862150
sets the content type to multipart/form-data
and says that the fields are separated by the given boundary
string.
But note that the:
boundary=---------------------------735323031399963166993862150
has two less dadhes --
than the actual barrier
-----------------------------735323031399963166993862150
This is because the standard requires the boundary to start with two dashes --
. The other dashes appear to be just how Firefox chose to implement the arbitrary boundary. RFC 7578 clearly mentions that those two leading dashes --
are required:
4.1. "Boundary" Parameter of multipart/form-data
As with other multipart types, the parts are delimited with a boundary delimiter, constructed using CRLF, "--", and the value of the "boundary" parameter.
every field gets some sub headers before its data: Content-Disposition: form-data;
, the field name
, the filename
, followed by the data.
The server reads the data until the next boundary string. The browser must choose a boundary that will not appear in any of the fields, so this is why the boundary may vary between requests.
Because we have the unique boundary, no encoding of the data is necessary: binary data is sent as is.
TODO: what is the optimal boundary size (log(N)
I bet), and name / running time of the algorithm that finds it? Asked at: https://cs.stackexchange.com/questions/39687/find-the-shortest-sequence-that-is-not-a-sub-sequence-of-a-set-of-sequences
Content-Type
is automatically determined by the browser.
How it is determined exactly was asked at: How is mime type of an uploaded file determined by browser?
Now change the enctype
to application/x-www-form-urlencoded
, reload the browser, and resubmit.
Firefox sent:
POST / HTTP/1.1
[[ Less interesting headers ... ]]
Content-Type: application/x-www-form-urlencoded
Content-Length: 51
text1=text+default&text2=a%CF%89b&file1=a.txt&file2=a.html&file3=binary
Clearly the file data was not sent, only the basenames. So this cannot be used for files.
As for the text field, we see that usual printable characters like a
and b
were sent in one byte, while non-printable ones like 0xCF
and 0x89
took up 3 bytes each: %CF%89
!
File uploads often contain lots of non-printable characters (e.g. images), while text forms almost never do.
From the examples we have seen that:
multipart/form-data
: adds a few bytes of boundary overhead to the message, and must spend some time calculating it, but sends each byte in one byte.
application/x-www-form-urlencoded
: has a single byte boundary per field (&
), but adds a linear overhead factor of 3x for every non-printable character.
Therefore, even if we could send files with application/x-www-form-urlencoded
, we wouldn't want to, because it is so inefficient.
But for printable characters found in text fields, it does not matter and generates less overhead, so we just use it.
This seems to work for me:
LANG=C grep --only-matching --byte-offset --binary --text --perl-regexp "<\x-hex pattern>" <file>
short form:
LANG=C grep -obUaP "<\x-hex pattern>" <file>
Example:
LANG=C grep -obUaP "\x01\x02" /bin/grep
Output (cygwin binary):
153: <\x01\x02>
33210: <\x01\x02>
53453: <\x01\x02>
So you can grep this again to extract offsets. But don't forget to use binary mode again.
Note: LANG=C
is needed to avoid utf8 encoding issues.
Sorting by C and D needs to be put into number form for the corresponding column, ie 3 and 4, respectively. Eg Order By 2 asc")
Iterating over the generator expression or the list comprehension will do the same thing. However, the list comprehension will create the entire list in memory first while the generator expression will create the items on the fly, so you are able to use it for very large (and also infinite!) sequences.
Here's an alternative to Arun's first solution, with a simpler Perl-like regular expression:
as.numeric(gsub("[^\\d]+", "", years, perl=TRUE))
You're getting None
because list.sort()
it operates in-place, meaning that it doesn't return anything, but modifies the list itself. You only need to call a.sort()
without assigning it to a
again.
There is a built in function sorted()
, which returns a sorted version of the list - a = sorted(a)
will do what you want as well.
To have a constant date format irrespective of the computer settings, you must use 3 different input elements to capture day, month, and year respectively. However, you need to validate the user input to ensure that you have a valid date as shown bellow
<input id="txtDay" type="text" placeholder="DD" />
<input id="txtMonth" type="text" placeholder="MM" />
<input id="txtYear" type="text" placeholder="YYYY" />
<button id="but" onclick="validateDate()">Validate</button>
function validateDate() {
var date = new Date(document.getElementById("txtYear").value, document.getElementById("txtMonth").value, document.getElementById("txtDay").value);
if (date == "Invalid Date") {
alert("jnvalid date");
}
}
For posterity....I figured out how to get what I needed. Here it is in case it might be useful to somebody else.
$alist = "Name`tAccountName`tDescription`tEmailAddress`tLastLogonDate`tManager`tTitle`tDepartment`tCompany`twhenCreated`tAcctEnabled`tGroups`n"
$userlist = Get-ADUser -Filter * -Properties * | Select-Object -Property Name,SamAccountName,Description,EmailAddress,LastLogonDate,Manager,Title,Department,Company,whenCreated,Enabled,MemberOf | Sort-Object -Property Name
$userlist | ForEach-Object {
$grps = $_.MemberOf | Get-ADGroup | ForEach-Object {$_.Name} | Sort-Object
$arec = $_.Name,$_.SamAccountName,$_.Description,$_.EmailAddress,$_LastLogonDate,$_.Manager,$_.Title,$_.Department,$_.Company,$_.whenCreated,$_.Enabled
$aline = ($arec -join "`t") + "`t" + ($grps -join "`t") + "`n"
$alist += $aline
}
$alist | Out-File D:\Temp\ADUsers.csv
Please read this: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
You should set indicies for your html elements "name" attributes like planCompareViewModel[0].PlanId
, planCompareViewModel[1].PlanId
to make binder able to parse them into IEnumerable.
Instead of @foreach (var planVM in Model)
use for
loop and render names with indexes.
I just added H:i:s to Rocket's answer to get the time along with the date.
echo date('m/d/Y H:i:s', 1299446702);
Output: 03/06/2011 16:25:02
You can pass an access level to the @Getter
and @Setter
annotations. This is useful to make getters or setters protected or private. It can also be used to override the default.
With @Data
, you have public access to the accessors by default. You can now use the special access level NONE
to completely omit the accessor, like this:
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private int mySecret;
I am a little late but I used this:
dir /B *.* > dir_file.txt
then you can make a simple FOR loop to extract the file name and use them. e.g:
for /f "tokens=* delims= " %%a in (dir_file.txt) do (
gawk -f awk_script_file.awk %%a
)
or store them into Vars (!N1!, !N2!..!Nn!) for later use. e.g:
set /a N=0
for /f "tokens=* delims= " %%a in (dir_file.txt) do (
set /a N+=1
set v[!N!]=%%a
)
Seen from a non-PHP guru perspective, this should do exactly what us desired to:
<style>
[name$='pdf'] { width:100%; height: auto;}
</style>
It is also possible to set the error action preference on individual cmdlets, not just for the whole script. This is done using the parameter ErrorAction (alisa EA) which is available on all cmdlets.
Example
try
{
Write-Host $ErrorActionPreference; #Check setting for ErrorAction - the default is normally Continue
get-item filethatdoesntexist; # Normally generates non-terminating exception so not caught
write-host "You will hit me as exception from line above is non-terminating";
get-item filethatdoesntexist -ErrorAction Stop; #Now ErrorAction parameter with value Stop causes exception to be caught
write-host "you won't reach me as exception is now caught";
}
catch
{
Write-Host "Caught the exception";
Write-Host $Error[0].Exception;
}
While that error message is on the screen (before the rollback begins) go to Control Panel -> Administrative Tools -> Services and see if the service is actually installed. Also check what account it is using to run as. If it's not using Local System, then double and triple check that the account it's using has rights to the program directory where MS SQL installed to.
2020 Solution Please comment if no longer available.
In order to get profile URL from authenticated user.
GET https://people.googleapis.com/v1/people/[THE_USER_ID_OF_THE_AUTHENTICATED_USER]?personFields=photos&key=[YOUR_API_KEY] HTTP/1.1
Authorization: Bearer [YOUR_ACCESS_TOKEN]
Accept: application/json
Response:
{
"resourceName": "people/[THE_USER_ID_OF_THE_AUTHENTICATED_USER]",
"etag": "12345",
"photos": [
{
"metadata": {
"primary": true,
"source": {
"type": "PROFILE",
"id": "[THE_USER_ID_OF_THE_AUTHENTICATED_USER]"
}
},
"url": "https://lh3.googleusercontent.com/a-/blablabla=s100"
}
]
}
and the link can be used as:
<img src="https://lh3.googleusercontent.com/a-/blablabla=s100">
Was getting the same error message when trying to run from Cygwin with links to the mingw install.
Using the same install of mingw32-make-3.80.0-3.exe from http://www.mingw.org/wiki/FAQ and the mingw shell option from Start -> Programs -> on a WinXP SP3 and gcc is working fine.
ffmpeg has been substituted by avconv: just substitute avconb to Louis Marascio's answer.
avconv -i file.mp4 2>&1 | grep Duration | sed 's/Duration: \(.*\), start.*/\1/g'
Note: the aditional .* after start to get the time alone !!
//Call .noConflict() to restore JQuery reference.
jQuery.noConflict(); OR $.noConflict();
//Do something with jQuery.
jQuery( "div.class" ).hide(); OR $( "div.class" ).show();
The below are the typical situation where we shall get ERR_FILE_NOT_FOUND even file avail in respective folder.
Code:
@font-face {
font-family: Eau_Sans_Bold;
src: url("/fonts/eau_sans_bold.otf") format("opentype");
}
Error:
GET file:///C:/fonts/eau_sans_bold.otf net::ERR_FILE_NOT_FOUND
Answer or Solution.:
@font-face {
font-family: Eau_Sans_Book;
src: url("../fonts/eau_sans_book.otf") format("opentype");
}
Basically browser not able to pick if we metion just /font/. We should to mention ../fonts/ This will work. So, we wont get ERR_FILE_NOT_FOUND.
I did this. sudo
is necessary.
$ sudo play debug -Dhttp.port=80
...
[MyPlayApp] $ run
EDIT: I had problems because of using sudo
so take care. Finally I cleaned up the project and I haven't used that trick anymore.
Probably, not the cleanest solution, but it is definitely simpler than removing one-by-one:
document.getElementById("DropList").innerHTML = "";
Most of the answers here are wrong. The right answer is it depends. For example, here are two C functions which walks through a tree. First the recursive one:
static
void mm_scan_black(mm_rc *m, ptr p) {
SET_COL(p, COL_BLACK);
P_FOR_EACH_CHILD(p, {
INC_RC(p_child);
if (GET_COL(p_child) != COL_BLACK) {
mm_scan_black(m, p_child);
}
});
}
And here is the same function implemented using iteration:
static
void mm_scan_black(mm_rc *m, ptr p) {
stack *st = m->black_stack;
SET_COL(p, COL_BLACK);
st_push(st, p);
while (st->used != 0) {
p = st_pop(st);
P_FOR_EACH_CHILD(p, {
INC_RC(p_child);
if (GET_COL(p_child) != COL_BLACK) {
SET_COL(p_child, COL_BLACK);
st_push(st, p_child);
}
});
}
}
It's not important to understand the details of the code. Just that p
are nodes and that P_FOR_EACH_CHILD
does the walking. In the iterative version we need an explicit stack st
onto which nodes are pushed and then popped and manipulated.
The recursive function runs much faster than the iterative one. The reason is because in the latter, for each item, a CALL
to the function st_push
is needed and then another to st_pop
.
In the former, you only have the recursive CALL
for each node.
Plus, accessing variables on the callstack is incredibly fast. It means you are reading from memory which is likely to always be in the innermost cache. An explicit stack, on the other hand, has to be backed by malloc
:ed memory from the heap which is much slower to access.
With careful optimization, such as inlining st_push
and st_pop
, I can reach roughly parity with the recursive approach. But at least on my computer, the cost of accessing heap memory is bigger than the cost of the recursive call.
But this discussion is mostly moot because recursive tree walking is incorrect. If you have a large enough tree, you will run out of callstack space which is why an iterative algorithm must be used.
If you want to return a char*
from a function, make sure you malloc()
it. Stack initialized character arrays make no sense in returning, as accessing them after returning from that function is undefined behavior.
change it to
char* createStr() {
char char1= 'm';
char char2= 'y';
char *str = malloc(3 * sizeof(char));
if(str == NULL) return NULL;
str[0] = char1;
str[1] = char2;
str[2] = '\0';
return str;
}
A 50% padding wont center your child, it will place it below the center. I think you really want a padding-top of 25%. Maybe you're just running out of space as your content gets taller? Also have you tried setting the margin-top instead of padding-top?
EDIT: Nevermind, the w3schools site says
% Specifies the padding in percent of the width of the containing element
So maybe it always uses width? I'd never noticed.
What you are doing can be acheived using display:table though (at least for modern browsers). The technique is explained here.
Inspired by samneric's answer using DataRowComparer.Default but needing something that would only compare a subset of columns within a DataTable, I made a DataTableComparer object where you can specify which columns to use in the comparison. Especially great if they have different columns/schemas.
DataRowComparer.Default works because it implements IEqualityComparer. Then I created an object where you can define which columns of the DataRow will be compared.
public class DataTableComparer : IEqualityComparer<DataRow>
{
private IEnumerable<String> g_TestColumns;
public void SetCompareColumns(IEnumerable<String> p_Columns)
{
g_TestColumns = p_Columns;
}
public bool Equals(DataRow x, DataRow y)
{
foreach (String sCol in g_TestColumns)
if (!x[sCol].Equals(y[sCol])) return false;
return true;
}
public int GetHashCode(DataRow obj)
{
StringBuilder hashBuff = new StringBuilder();
foreach (String sCol in g_TestColumns)
hashBuff.AppendLine(obj[sCol].ToString());
return hashBuff.ToString().GetHashCode();
}
}
You can use this by:
DataTableComparer comp = new DataTableComparer();
comp.SetCompareColumns(new String[] { "Name", "DoB" });
DataTable celebrities = SomeDataTableSource();
DataTable politicians = SomeDataTableSource2();
List<DataRow> celebrityPoliticians = celebrities.AsEnumerable().Intersect(politicians.AsEnumerable(), comp).ToList();
To see if two maps have the same values, you can do the following:
Collection<V> values()
viewsList<V>
Collections.sort
those listsequals
Something like this works (though its type bounds can be improved on):
static <V extends Comparable<V>>
boolean valuesEquals(Map<?,V> map1, Map<?,V> map2) {
List<V> values1 = new ArrayList<V>(map1.values());
List<V> values2 = new ArrayList<V>(map2.values());
Collections.sort(values1);
Collections.sort(values2);
return values1.equals(values2);
}
Test harness:
Map<String, String> map1 = new HashMap<String,String>();
map1.put("A", "B");
map1.put("C", "D");
Map<String, String> map2 = new HashMap<String,String>();
map2.put("A", "D");
map2.put("C", "B");
System.out.println(valuesEquals(map1, map2)); // prints "true"
This is O(N log N)
due to Collections.sort
.
To test if the keys are equals is easier, because they're Set<K>
:
map1.keySet().equals(map2.keySet())
<RichTextBox>
<FlowDocument PageHeight="180">
<Paragraph>
<Run Text="{Binding Text, Mode=TwoWay}"/>
</Paragraph>
</FlowDocument>
</RichTextBox>
This seems to be the easiest way by far and isn't displayed in any of these answers.
In the view model just have the Text
variable.
//backend.
@PostMapping("/")
public List<A> addList(@RequestBody A aObject){
//......ur code
}
class A{
int num;
String name;
List<B> bList;
//getters and setters and default constructor
}
class B{
int d;
//defalut Constructor & gettes&setters
}
// postman
{
"num":value,
"name":value,
"bList":[{
"key":"value",
"key":"value",.....
}]
}
Organizing your application using class make it easy to you and others who work with you to debug problems and improve the app easily.
You can easily organize your application like this:
class hello(Tk):
def __init__(self):
super(hello, self).__init__()
self.btn = Button(text = "Click me", command=close)
self.btn.pack()
def close():
self.destroy()
app = hello()
app.mainloop()
If you want to see the array as an array, you can say
alert(JSON.stringify(aCustomers));
instead of all those document.write
s.
However, if you want to display them cleanly, one per line, in your popup, do this:
alert(aCustomers.join("\n"));
I hope this can help someone who was faced with my same problem.
This answer uses the Bootstrap DatePicker Plugin, which is not native to bootstrap.
Make sure you install Bootstrap DatePicker through NuGet
Create a small piece of JavaScript and name it DatePickerReady.js save it in Scripts dir. This will make sure it works even in non HTML5 browsers although those are few nowadays.
if (!Modernizr.inputtypes.date) {
$(function () {
$(".datecontrol").datepicker();
});
}
Set the bundles
bundles.Add(New ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/bootstrap-datepicker.js",
"~/Scripts/DatePickerReady.js",
"~/Scripts/respond.js"))
bundles.Add(New StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/bootstrap-datepicker3.css",
"~/Content/site.css"))
Now set the Datatype so that when EditorFor is used MVC will identify what is to be used.
<Required>
<DataType(DataType.Date)>
Public Property DOB As DateTime? = Nothing
Your view code should be
@Html.EditorFor(Function(model) model.DOB, New With {.htmlAttributes = New With {.class = "form-control datecontrol", .PlaceHolder = "Enter Date of Birth"}})
and voila
I currently use this statusbar settings:
set laststatus=2
set statusline=\ %f%m%r%h%w\ %=%({%{&ff}\|%{(&fenc==\"\"?&enc:&fenc).((exists(\"+bomb\")\ &&\ &bomb)?\",B\":\"\")}%k\|%Y}%)\ %([%l,%v][%p%%]\ %)
My complete .vimrc file: http://gabriev82.altervista.org/projects/vim-configuration/
An example of using logging.basicConfig
rather than logging.fileHandler()
logging.basicConfig(filename=logname,
filemode='a',
format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
datefmt='%H:%M:%S',
level=logging.DEBUG)
logging.info("Running Urban Planning")
self.logger = logging.getLogger('urbanGUI')
In order, the five parts do the following:
filename=logname
)filemode='a'
)format=...
)datefmt='%H:%M:%S'
)level=logging.DEBUG
).I'm a little late, and I'm not sure if this is what you're looking for, but I thought I'd add it just in case someone else finds it useful.
Suppose this is your file structure:
/BulutDepoProject
/bin
Main.exe
/FolderIcon
Folder.ico
Main.cs
You need to write your path relative to the Main.exe
file. So, you want to access Folder.ico
, in your Main.cs
you can use:
String path = "..\\FolderIcon\\Folder.ico"
That seemed to work for me!
I solved this by using 2 custom functions like so:
function slash_replace($query){
return str_replace('/','_', $query);
}
function slash_unreplace($query){
return str_replace('_','/', $query);
}
So to encode I could call:
rawurlencode(slash_replace($param))
and to decode I could call
slash_unreplace(rawurldecode($param);
Cheers!
Try moving <uses-permission>
outside the <application>
tag.
A late post, but for those who searched this post.
Imagine this:
[Authorize(Roles = "Administrator")]
[Authorize(Roles = "Director")]
[Authorize(Roles = "Human Resources")]
[HttpGet]
public ActionResult GetUserData(string UserIdGuidKey)
{
if (UserIdGuidKey!= null)
{
var guidUserId = new Guid(UserIdGuidKey);
var memuser = Membership.GetUser(guidUserId);
var profileuser = Profile.GetUserProfile(memuser.UserName);
var list = new {
UserName = memuser.UserName,
Email = memuser.Email ,
IsApproved = memuser.IsApproved.ToString() ,
IsLockedOut = memuser.IsLockedOut.ToString() ,
LastLockoutDate = memuser.LastLockoutDate.ToString() ,
CreationDate = memuser.CreationDate.ToString() ,
LastLoginDate = memuser.LastLoginDate.ToString() ,
LastActivityDate = memuser.LastActivityDate.ToString() ,
LastPasswordChangedDate = memuser.LastPasswordChangedDate.ToString() ,
IsOnline = memuser.IsOnline.ToString() ,
FirstName = profileuser.FirstName ,
LastName = profileuser.LastName ,
NickName = profileuser.NickName ,
BirthDate = profileuser.BirthDate.ToString() ,
};
return Json(list, JsonRequestBehavior.AllowGet);
}
return Redirect("Index");
}
As you can see, I'm utilizing C# 3.0's feature for creating the "Auto" Generics. It's a bit lazy, but I like it and it works. Just a note: Profile is a custom class I've created for my web application project.
((KidsStoryDashboard)getActivity()).values(title_txt,bannerImgUrl);
public void values(String title_txts, String bannerImgUrl) {
if (!title_txts.isEmpty()) {
//Do something to set text
}
imageLoader.displayImage(bannerImgUrl, htab_header_image, doption);
}
Another interesting solution would be:
DESTINY=[Give the output that you intend]
# Don't forget to change from .ZIP to .zip.
# In my case the files were in .ZIP.
# The echo were for debug purpose.
find . -name "*.ZIP" | while read filename; do
ADDRESS=$filename
#echo "Address: $ADDRESS"
BASENAME=`basename $filename .ZIP`
#echo "Basename: $BASENAME"
unzip -d "$DESTINY$BASENAME" "$ADDRESS";
done;
Worked by lowering the spring boot starter parent to 1.5.13
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.13.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
EXE:
DLL:
For More Details: http://www.c-sharpcorner.com/Interviews/Answer/Answers.aspxQuestionId=1431&MajorCategoryId=1&MinorCategoryId=1 http://wiki.answers.com/Q/What_is_the_difference_between_an_EXE_and_a_DLL
Reference: http://www.dotnetspider.com/forum/34260-What-difference-between-dll-exe.aspx
Just add : @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class })
works for me.
I was getting same error I tried with @EnableAutoConfiguration(exclude=...)
didn't work.
Now you can upload your app binary with the Transporter app.
You can download Transporter from Mac AppStore Here
Here apple mentioned its used for uploading.
You can use the FindByValue method to search the DropDownList for an Item with a Value matching the parameter.
dropdownlist.ClearSelection();
dropdownlist.Items.FindByValue(value).Selected = true;
Alternatively you can use the FindByText method to search the DropDownList for an Item with Text matching the parameter.
Before using the FindByValue method, don't forget to reset the DropDownList so that no items are selected by using the ClearSelection() method. It clears out the list selection and sets the Selected property of all items to false. Otherwise you will get the following exception.
"Cannot have multiple items selected in a DropDownList"
For fedora/centos/redhat:
yum install php-mbstring
Then restart apache
You need to set the Identity seed to that value:
CREATE TABLE orders
(
id int IDENTITY(9586,1)
)
To alter an existing table:
ALTER TABLE orders ALTER COLUMN Id INT IDENTITY (9586, 1);
More info on CREATE TABLE (Transact-SQL) IDENTITY (Property)
Constraints in SQL are the rules defined for the data in a table. Constraints also limit the types of data that go into the table. If new data does not abide by these rules the action is aborted.
select * from INFORMATION_SCHEMA.TABLE_CONSTRAINTS where CONSTRAINT_TYPE = 'FOREIGN KEY';
You can view all constraints by using select * from information_schema.table_constraints;
(This will produce a lot of table data).
You can also use this for MySQL:
show create table tableName;
You can use the _getexif()
protected method of a PIL Image.
import PIL.Image
img = PIL.Image.open('img.jpg')
exif_data = img._getexif()
This should give you a dictionary indexed by EXIF numeric tags. If you want the dictionary indexed by the actual EXIF tag name strings, try something like:
import PIL.ExifTags
exif = {
PIL.ExifTags.TAGS[k]: v
for k, v in img._getexif().items()
if k in PIL.ExifTags.TAGS
}
bit
. It stores 1 or 0 (or NULL
).Alternatively, you could use the strings 'true'
and 'false'
in place of 1 or 0, like so-
declare @b1 bit = 'false'
print @b1 --prints 0
declare @b2 bit = 'true'
print @b2 --prints 1
Also, any non 0 value (either positive or negative) evaluates to (or converts to in some cases) a 1.
declare @i int = -42
print cast(@i as bit) --will print 1, because @i is not 0
Note that SQL Server uses three valued logic (true
, false
, and NULL
), since NULL
is a possible value of the bit
data type. Here are the relevant truth tables -
More information on three valued logic-
Example of three valued logic in SQL Server
http://www.firstsql.com/idefend3.htm
https://www.simple-talk.com/sql/learn-sql-server/sql-and-the-snare-of-three-valued-logic/
I had the same error when multiline string included new line (\n
) characters. Merging all lines into one (thus removing all new line characters) and sending it to a browser used to solve. But was very inconvenient to code.
Often could not understand why this was an issue in Chrome until I came across to a statement which said that the current version of JavaScript engine in Chrome doesn't support multiline strings which are wrapped in single quotes and have new line (\n
) characters in them. To make it work, multiline string need to be wrapped in double quotes. Changing my code to this, resolved this issue.
I will try to find a reference to a standard or Chrome doc which proves this. Until then, try this solution and see if works for you as well.
I was able to set the env. variables by sourcing (source command inside the shell (ksh) scirpt) the file that was settign them. Then I called the .ksh script from the external Tools
Very easy with responsive voice. Just include the js and voila!
<script src='https://code.responsivevoice.org/responsivevoice.js'></script>
<input onclick="responsiveVoice.speak('This is the text you want to speak');" type='button' value=' Play' />
Some years have passed and there is now a proper Homebrew Tap for sshpass
, maintained by Aleks Hudochenkov. To install sshpass
from this tap, run:
brew install hudochenkov/sshpass/sshpass
Annotations can be applied to declarations: declarations of classes, fields, methods, and other program elements. When used on a declaration, each annotation often appears, by convention, on its own line.
Java SE 8 Update: annotations can also be applied to the use of types. Here are some examples:
Class instance creation expression:
new @Interned MyObject();
Type cast:
myString = (@NonNull String) str;
implements clause:
class UnmodifiableList implements @Readonly List<@Readonly T> { ... }
Thrown exception declaration:
void monitorTemperature() throws @Critical TemperatureException { ... }
var start=moment(1541243900000);
var end=moment(1541243942882);
var duration = moment.duration(end.diff(startTime));
var hours = duration.asHours();
As you can see, the start and end date needed to be moment objects for this method to work.
I know it is a late answer but it was useful to me! Just to complete, using the $.grep
function you can emulate the linq where()
.
Linq:
var maleNames = people
.Where(p => p.Sex == "M")
.Select(p => p.Name)
Javascript:
// replace where with $.grep
// select with $.map
var maleNames = $.grep(people, function (p) { return p.Sex == 'M'; })
.map(function (p) { return p.Name; });
based on JustinStolle code (thank you), I wanted a solution that could be generic without having to specify the column names.
This sample is using the data of a temp table but of course it can be adjusted as required.
Here is what I got:
DECLARE @htmlTH VARCHAR(MAX) = '',
@htmlTD VARCHAR(MAX)
--get header, columns name
SELECT @htmlTH = @htmlTH + '<TH>' + name + '</TH>' FROM tempdb.sys.columns WHERE object_id = OBJECT_ID('tempdb.dbo.#results')
--convert table to XML PATH, ELEMENTS XSINIL is used to include NULL values
SET @htmlTD = (SELECT * FROM #results FOR XML PATH('TR'), ELEMENTS XSINIL)
--convert the way ELEMENTS XSINIL display NULL to display word NULL
SET @htmlTD = REPLACE(@htmlTD, ' xsi:nil="true"/>', '>NULL</TD>')
SET @htmlTD = REPLACE(@htmlTD, '<TR xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">', '<TR>')
--FOR XML PATH will set tags for each column name, <columnName1>abc</columnName1><columnName2>def</columnName2>
--this will replace all the column names with TD (html table data tag)
SELECT @htmlTD = REPLACE(REPLACE(@htmlTD, '<' + name + '>', '<TD>'), '</' + name + '>', '</TD>')
FROM tempdb.sys.columns WHERE object_id = OBJECT_ID('tempdb.dbo.#results')
SELECT '<TABLE cellpadding="2" cellspacing="2" border="1">'
+ '<TR>' + @htmlTH + '</TR>'
+ @htmlTD
+ '</TABLE>'
As seen in Install crontab on CentOS, the crontab package in CentOS is vixie-cron
. Hence, do install it with:
yum install vixie-cron
And then start it with:
service crond start
To make it persistent, so that it starts on boot, use:
chkconfig crond on
On CentOS 7 you need to use cronie
:
yum install cronie
On CentOS 6 you can install vixie-cron
, but the real package is cronie
:
yum install vixie-cron
and
yum install cronie
In both cases you get the same output:
.../...
==================================================================
Package Arch Version Repository Size
==================================================================
Installing:
cronie x86_64 1.4.4-12.el6 base 73 k
Installing for dependencies:
cronie-anacron x86_64 1.4.4-12.el6 base 30 k
crontabs noarch 1.10-33.el6 base 10 k
exim x86_64 4.72-6.el6 epel 1.2 M
Transaction Summary
==================================================================
Install 4 Package(s)
You can use BeautifulSoup:
from bs4 import BeautifulSoup
x="""<foo>
<bar>
<type foobar="1"/>
<type foobar="2"/>
</bar>
</foo>"""
y=BeautifulSoup(x)
>>> y.foo.bar.type["foobar"]
u'1'
>>> y.foo.bar.findAll("type")
[<type foobar="1"></type>, <type foobar="2"></type>]
>>> y.foo.bar.findAll("type")[0]["foobar"]
u'1'
>>> y.foo.bar.findAll("type")[1]["foobar"]
u'2'
Only mozilla implements a simple property in css : http://caniuse.com/#search=scroll-behavior
you will have to use JS at least.
I personally use this because its easy to use (I use JQ but you can adapt it I guess):
/*Scroll transition to anchor*/
$("a.toscroll").on('click',function(e) {
var url = e.target.href;
var hash = url.substring(url.indexOf("#")+1);
$('html, body').animate({
scrollTop: $('#'+hash).offset().top
}, 500);
return false;
});
just add class toscroll to your a tag
String.Format("{0:#,###.##}", value)
A more complex example from String Formatting in C#:
String.Format("{0:$#,##0.00;($#,##0.00);Zero}", value);
This will output “$1,240.00" if passed 1243.50. It will output the same format but in parentheses if the number is negative, and will output the string “Zero” if the number is zero.
UIScreen class lets you find screen resolution in Points and Pixels.
Screen resolutions is measured in Points or Pixels. It should never be confused with screen size. A smaller screen size can have higher resolution.
UIScreen's 'bounds.width' return rectangular size in Points
UIScreen's 'nativeBounds.width' return rectangular size in Pixels.This value is detected as PPI ( Point per inch ). Shows the sharpness & clarity of the Image on a device.
You can use UIScreen class to detect all these values.
Swift3
// Normal Screen Bounds - Detect Screen size in Points.
let width = UIScreen.main.bounds.width
let height = UIScreen.main.bounds.height
print("\n width:\(width) \n height:\(height)")
// Native Bounds - Detect Screen size in Pixels.
let nWidth = UIScreen.main.nativeBounds.width
let nHeight = UIScreen.main.nativeBounds.height
print("\n Native Width:\(nWidth) \n Native Height:\(nHeight)")
Console
width:736.0
height:414.0
Native Width:1080.0
Native Height:1920.0
Swift 2.x
//Normal Bounds - Detect Screen size in Points.
let width = UIScreen.mainScreen.bounds.width
let height = UIScreen.mainScreen.bounds.height
// Native Bounds - Detect Screen size in Pixels.
let nWidth = UIScreen.mainScreen.nativeBounds.width
let nHeight = UIScreen.mainScreen.nativeBounds.height
ObjectiveC
// Normal Bounds - Detect Screen size in Points.
CGFloat *width = [UIScreen mainScreen].bounds.size.width;
CGFloat *height = [UIScreen mainScreen].bounds.size.height;
// Native Bounds - Detect Screen size in Pixels.
CGFloat *width = [UIScreen mainScreen].nativeBounds.size.width
CGFloat *height = [UIScreen mainScreen].nativeBounds.size.width
In Windows 7 I did this:
Done!
Modify Remember like this
public class MyModel
{
public string Name { get; set; }
public bool? Remember { get; set; }
}
Use nullable bool in controller and fallback to false on null like this
[HttpPost]
public ActionResult MyAction(MyModel model)
{
model.Remember = model.Remember ?? false;
Console.WriteLine(model.Remember.ToString());
}
I'm pretty sure you only have to register MappingJacksonHttpMessageConverter
(the easiest way to do that is through <mvc:annotation-driven />
in XML or @EnableWebMvc
in Java)
See:
Here's a working example:
Maven POM
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion><groupId>test</groupId><artifactId>json</artifactId><packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version><name>json test</name>
<dependencies>
<dependency><!-- spring mvc -->
<groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>3.0.5.RELEASE</version>
</dependency>
<dependency><!-- jackson -->
<groupId>org.codehaus.jackson</groupId><artifactId>jackson-mapper-asl</artifactId><version>1.4.2</version>
</dependency>
</dependencies>
<build><plugins>
<!-- javac --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version><configuration><source>1.6</source><target>1.6</target></configuration></plugin>
<!-- jetty --><plugin><groupId>org.mortbay.jetty</groupId><artifactId>jetty-maven-plugin</artifactId>
<version>7.4.0.v20110414</version></plugin>
</plugins></build>
</project>
in folder src/main/webapp/WEB-INF
web.xml
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<servlet><servlet-name>json</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>json</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
json-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="classpath:mvc-context.xml" />
</beans>
in folder src/main/resources:
mvc-context.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="test.json" />
</beans>
In folder src/main/java/test/json
TestController.java
@Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping(method = RequestMethod.POST, value = "math")
@ResponseBody
public Result math(@RequestBody final Request request) {
final Result result = new Result();
result.setAddition(request.getLeft() + request.getRight());
result.setSubtraction(request.getLeft() - request.getRight());
result.setMultiplication(request.getLeft() * request.getRight());
return result;
}
}
Request.java
public class Request implements Serializable {
private static final long serialVersionUID = 1513207428686438208L;
private int left;
private int right;
public int getLeft() {return left;}
public void setLeft(int left) {this.left = left;}
public int getRight() {return right;}
public void setRight(int right) {this.right = right;}
}
Result.java
public class Result implements Serializable {
private static final long serialVersionUID = -5054749880960511861L;
private int addition;
private int subtraction;
private int multiplication;
public int getAddition() { return addition; }
public void setAddition(int addition) { this.addition = addition; }
public int getSubtraction() { return subtraction; }
public void setSubtraction(int subtraction) { this.subtraction = subtraction; }
public int getMultiplication() { return multiplication; }
public void setMultiplication(int multiplication) { this.multiplication = multiplication; }
}
You can test this setup by executing mvn jetty:run
on the command line, and then sending a POST request:
URL: http://localhost:8080/test/math
mime type: application/json
post body: { "left": 13 , "right" : 7 }
I used the Poster Firefox plugin to do this.
Here's what the response looks like:
{"addition":20,"subtraction":6,"multiplication":91}
I haven't found a clear answer, without checks if it is negative or positive, that uses two's complement (negative numbers included). For that, I show my solution to one byte:
((0xFF + number +1) & 0x0FF).toString(16);
You can use this instruction to any number bytes, only you add FF
in respective places. For example, to two bytes:
((0xFFFF + number +1) & 0x0FFFF).toString(16);
If you want cast an array integer to string hexadecimal:
s = "";
for(var i = 0; i < arrayNumber.length; ++i) {
s += ((0xFF + arrayNumber[i] +1) & 0x0FF).toString(16);
}
You can do this to ignore all nulls in an object you're serializing, and any null properties won't then appear in the JSON
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.NullValueHandling = NullValueHandling.Ignore;
var myJson = JsonConvert.SerializeObject(myObject, settings);
List<String> items = Arrays.asList(commaSeparated.split(","));
That should work for you.
You do not specify why you think it is wrong but I can se two dangers:
BETWEEN can be implemented differently in different databases sometimes it is including the border values and sometimes excluding, resulting in that 1 and 31 of january would end up NOTHING. You should test how you database does this.
Also, if RATE_DATE contains hours also 2010-01-31 might be translated to 2010-01-31 00:00 which also would exclude any row with an hour other that 00:00.
To use withRouter
with a class-based component, try something like this below.
Don't forget to change the export statement to use withRouter
:
import { withRouter } from 'react-router-dom'
class YourClass extends React.Component {
yourFunction = () => {
doSomeAsyncAction(() =>
this.props.history.push('/other_location')
)
}
render() {
return (
<div>
<Form onSubmit={ this.yourFunction } />
</div>
)
}
}
export default withRouter(YourClass);
You can use this class:
using System.Collections.Specialized;
class Post_File
{
public static void HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc)
{
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
byte[] boundarybytesF = System.Text.Encoding.ASCII.GetBytes("--" + boundary + "\r\n"); // the first time it itereates, you need to make sure it doesn't put too many new paragraphs down or it completely messes up poor webbrick.
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
wr.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
var nvc2 = new NameValueCollection();
nvc2.Add("Accepts-Language", "en-us,en;q=0.5");
wr.Headers.Add(nvc2);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
Stream rs = wr.GetRequestStream();
bool firstLoop = true;
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
foreach (string key in nvc.Keys)
{
if (firstLoop)
{
rs.Write(boundarybytesF, 0, boundarybytesF.Length);
firstLoop = false;
}
else
{
rs.Write(boundarybytes, 0, boundarybytes.Length);
}
string formitem = string.Format(formdataTemplate, key, nvc[key]);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
rs.Write(formitembytes, 0, formitembytes.Length);
}
rs.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, paramName, new FileInfo(file).Name, contentType);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
rs.Write(buffer, 0, bytesRead);
}
fileStream.Close();
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
WebResponse wresp = null;
try
{
wresp = wr.GetResponse();
Stream stream2 = wresp.GetResponseStream();
StreamReader reader2 = new StreamReader(stream2);
}
catch (Exception ex)
{
if (wresp != null)
{
wresp.Close();
wresp = null;
}
}
finally
{
wr = null;
}
}
}
use it:
NameValueCollection nvc = new NameValueCollection();
//nvc.Add("id", "TTR");
nvc.Add("table_name", "uploadfile");
nvc.Add("commit", "uploadfile");
Post_File.HttpUploadFile("http://example/upload_file.php", @"C:\user\yourfile.docx", "uploadfile", "application/vnd.ms-excel", nvc);
example server upload_file.php
:
m('File upload '.(@copy($_FILES['uploadfile']['tmp_name'],getcwd().'\\'.'/'.$_FILES['uploadfile']['name']) ? 'success' : 'failed'));
function m($msg) {
echo '<div style="background:#f1f1f1;border:1px solid #ddd;padding:15px;font:14px;text-align:center;font-weight:bold;">';
echo $msg;
echo '</div>';
}
<?php
$url = 'your repository here';
$output = `svn info $url`;
echo "<pre>$output</pre>";
?>
You can get the output in XML like so:
$output = `svn info $url --xml`;
If there is an error then the output will be directed to stderr. To capture stderr in your output use thusly:
$output = `svn info $url 2>&1`;
The only standard mandated implementation dependent way is to use the system()
function from stdlib.h
.
Also if you know how to make user become the super-user that would be nice also.
Do you want the script to run as super-user or do you want to elevate the privileges of the C executable? The former can be done with sudo
but there are a few things you need to know before you can go off using sudo
.
In Python 2.6+, you could use io.open()
that is default (builtin open()
) on Python 3:
import io
with io.open(filename, 'w', encoding=character_encoding) as file:
file.write(unicode_text)
It might be more convenient if you need to write the text incrementally (you don't need to call unicode_text.encode(character_encoding)
multiple times). Unlike codecs
module, io
module has a proper universal newlines support.
php.js ( http://www.phpjs.org/ ) has a isset()
function: http://phpjs.org/functions/isset:454
your link is generated when the page loads therefore it will always have the original value in it. You will need to set the link via javascript
You could also just wrap that in a form and have hidden fields for id
, productid
, and unitrate
Here's a sample for ya.
HTML
<input type="text" id="ss" value="1"/>
<br/>
<input type="submit" id="go" onClick="changeUrl()"/>
<br/>
<a id="imgUpdate" href="/someurl?quantity=1">click me</a>
JS
function changeUrl(){
var url = document.getElementById("imgUpdate").getAttribute('href');
var inputValue = document.getElementById('ss').value;
var currentQ = GiveMeTheQueryStringParameterValue("quantity",url);
url = url.replace("quantity=" + currentQ, "quantity=" + inputValue);
document.getElementById("imgUpdate").setAttribute('href',url)
}
function GiveMeTheQueryStringParameterValue(parameterName, input) {
parameterName = parameterName.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + parameterName + "=([^&#]*)");
var results = regex.exec(input);
if (results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
this could be cleaned up and expanded as you need it but the example works
I required only one instance of the vertical padding, so I inserted this line in the appropriate place to avoid adding more to the css. <div style="margin-top:5px"></div>
Try to use it via [ngClass]
property:
<div class="button" [ngClass]="{active: isOn, disabled: isDisabled}"
(click)="toggle(!isOn)">
Click me!
</div>`,
Above answers are correct. But simply this worked for me
target={"_blank"}
Microsoft SQL Server's INTERSECT
"returns any distinct values that are returned by both the query on the left and right sides of the INTERSECT operand" This is different from a standard INNER JOIN
or WHERE EXISTS
query.
SQL Server
CREATE TABLE table_a (
id INT PRIMARY KEY,
value VARCHAR(255)
);
CREATE TABLE table_b (
id INT PRIMARY KEY,
value VARCHAR(255)
);
INSERT INTO table_a VALUES (1, 'A'), (2, 'B'), (3, 'B');
INSERT INTO table_b VALUES (1, 'B');
SELECT value FROM table_a
INTERSECT
SELECT value FROM table_b
value
-----
B
(1 rows affected)
MySQL
CREATE TABLE `table_a` (
`id` INT NOT NULL AUTO_INCREMENT,
`value` varchar(255),
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
CREATE TABLE `table_b` LIKE `table_a`;
INSERT INTO table_a VALUES (1, 'A'), (2, 'B'), (3, 'B');
INSERT INTO table_b VALUES (1, 'B');
SELECT value FROM table_a
INNER JOIN table_b
USING (value);
+-------+
| value |
+-------+
| B |
| B |
+-------+
2 rows in set (0.00 sec)
SELECT value FROM table_a
WHERE (value) IN
(SELECT value FROM table_b);
+-------+
| value |
+-------+
| B |
| B |
+-------+
With this particular question, the id column is involved, so duplicate values will not be returned, but for the sake of completeness, here's a MySQL alternative using INNER JOIN
and DISTINCT
:
SELECT DISTINCT value FROM table_a
INNER JOIN table_b
USING (value);
+-------+
| value |
+-------+
| B |
+-------+
And another example using WHERE ... IN
and DISTINCT
:
SELECT DISTINCT value FROM table_a
WHERE (value) IN
(SELECT value FROM table_b);
+-------+
| value |
+-------+
| B |
+-------+
You want to use postgresql's replace function:
replace(string text, from text, to text)
for instance :
UPDATE <table> SET <field> = replace(<field>, 'cat', 'dog')
Be aware, though, that this will be a string-to-string replacement, so 'category' will become 'dogegory'. the regexp_replace function may help you define a stricter match pattern for what you want to replace.
Try this Bash syntax instead of trying to use an external program expr
:
count=$((FIRSTV-SECONDV))
BTW, the correct syntax of using expr
is:
count=$(expr $FIRSTV - $SECONDV)
But keep in mind using expr
is going to be slower than the internal Bash syntax I provided above.
I've actually always thought it was popular convention to use plural table names. Up until this point I've always used plural.
I can understand the argument for singular table names, but to me plural makes more sense. A table name usually describes what the table contains. In a normalized database, each table contains specific sets of data. Each row is an entity and the table contains many entities. Thus the plural form for the table name.
A table of cars would have the name cars and each row is a car. I'll admit that specifying the table along with the field in a table.field
manner is the best practice and that having singular table names is more readable. However in the following two examples, the former makes more sense:
SELECT * FROM cars WHERE color='blue'
SELECT * FROM car WHERE color='blue'
Honestly, I will be rethinking my position on the matter, and I would rely on the actual conventions used by the organization I'm developing for. However, I think for my personal conventions, I'll stick with plural table names. To me it makes more sense.
To drop a table if there is a foreign key constraint in MySQL Server?
Run the sql query:
SET FOREIGN_KEY_CHECKS = 0; DROP TABLE table_name
Hope it helps!
Turns out that YUI's reset CSS strips the list style from 'ul li' instead of just 'ul', which is why setting it just in 'ul' never worked.
Are you sure that your configuration file (web.config) is at the right place and the connection string is really in the (generated) file? If you publish your file, the content of web.release.config might be copied.
The configuration and the access to the Connection string looks all right to me. I would always add a providername
<connectionStrings>
<add name="Dbconnection"
connectionString="Server=localhost; Database=OnlineShopping;
Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
I'm not sure how far it will get you, but you can execute JavaScript one line at a time from the Developer Tool Console.
In Go, there is a general rule that syntax should not hide complex/costly operations. Converting a string
to an interface{}
is done in O(1) time. Converting a []string
to an interface{}
is also done in O(1) time since a slice is still one value. However, converting a []string
to an []interface{}
is O(n) time because each element of the slice must be converted to an interface{}
.
The one exception to this rule is converting strings. When converting a string
to and from a []byte
or a []rune
, Go does O(n) work even though conversions are "syntax".
There is no standard library function that will do this conversion for you. You could make one with reflect, but it would be slower than the three line option.
Example with reflection:
func InterfaceSlice(slice interface{}) []interface{} {
s := reflect.ValueOf(slice)
if s.Kind() != reflect.Slice {
panic("InterfaceSlice() given a non-slice type")
}
// Keep the distinction between nil and empty slice input
if s.IsNil() {
return nil
}
ret := make([]interface{}, s.Len())
for i:=0; i<s.Len(); i++ {
ret[i] = s.Index(i).Interface()
}
return ret
}
Your best option though is just to use the lines of code you gave in your question:
b := make([]interface{}, len(a))
for i := range a {
b[i] = a[i]
}
Since C++ 11, you could do the following:
for(const auto& student : data)
{
std::cout << student.name << std::endl;
}
My fix for this was my child table needed to be populated before the parent table.
I had two tables: UserDetails and Login linked by an email address. I therefore had to insert into the UserDetails first before inserting into the Login table:
insert into UserDetails (Email, Name, Telephone, Department) values ('Email', 'Name', 'number', 'IT');
Then:
insert into Login (UserID, UserType, Email, Username, Password) VALUES (001, 'SYS-USR-ADMIN', 'Email', 'Name', 'Password')
After hours of searching and looking for answer, finally I made it!!!!! Code is below :))))
HTML:
<form id="fileinfo" enctype="multipart/form-data" method="post" name="fileinfo">
<label>File to stash:</label>
<input type="file" name="file" required />
</form>
<input type="button" value="Stash the file!"></input>
<div id="output"></div>
jQuery:
$(function(){
$('#uploadBTN').on('click', function(){
var fd = new FormData($("#fileinfo"));
//fd.append("CustomField", "This is some extra data");
$.ajax({
url: 'upload.php',
type: 'POST',
data: fd,
success:function(data){
$('#output').html(data);
},
cache: false,
contentType: false,
processData: false
});
});
});
In the upload.php
file you can access the data passed with $_FILES['file']
.
Thanks everyone for trying to help:)
I took the answer from here (with some changes) MDN
<?php
if (isset($_POST['birthdate'])) {
$timestamp = strtotime($_POST['birthdate']);
$date=date('d',$timestamp);
$month=date('m',$timestamp);
$year=date('Y',$timestamp);
}
?>
My personal preference is to delete the branch name after I’m done with a topic branch.
Instead of trying to use the branch name to explain the meaning of the branch, I start the subject line of the commit message in the first commit on that branch with “Branch:” and include further explanations in the body of the message if the subject does not give me enough space.
The branch name in my use is purely a handle for referring to a topic branch while working on it. Once work on the topic branch has concluded, I get rid of the branch name, sometimes tagging the commit for later reference.
That makes the output of git branch
more useful as well: it only lists long-lived branches and active topic branches, not all branches ever.
This appears to be a problem with the way mac is handling reading the /etc/hosts file. See for example http://youtrack.jetbrains.com/issue/IDEA-96865
Adding the hostname to the hosts file as bond described should not be required, but it does solve the problem.
Just write what you really wanted to know:
fac.GetCachedValue("Auto Print Clinical Warnings").ToLower().StartsWith("y")
It's much simpler than anything with substring.
Why all people want to use '==' instead of simple '=' ? It is bad habit! It used only in [[ ]] expression. And in (( )) too. But you may use just = too! It work well in any case. If you use numbers, not strings use not parcing to strings and then compare like strings but compare numbers. like that
let -i i=5 # garantee that i is nubmber
test $i -eq 5 && echo "$i is equal 5" || echo "$i not equal 5"
It's match better and quicker. I'm expert in C/C++, Java, JavaScript. But if I use bash i never use '==' instead '='. Why you do so?
I'm writing this as a separate answer rather than just a comment because I disagree with Luc Touraille's answer, not on the grounds of legality but for robust software and the danger of misinterpretation.
Specifically, I have an issue with the implied contract of what you expect users of your interface to have to know.
If you are returning or accepting reference types, then you are just saying they can pass through a pointer or reference which they may in turn have known only through a forward declaration.
When you are returning an incomplete type X f2();
then you are saying your caller must have the full type specification of X. They need it in order to create the LHS or temporary object at the call site.
Similarly, if you accept an incomplete type, the caller has to have constructed the object which is the parameter. Even if that object was returned as another incomplete type from a function, the call site needs the full declaration. i.e.:
class X; // forward for two legal declarations
X returnsX();
void XAcceptor(X);
XAcepptor( returnsX() ); // X declaration needs to be known here
I think there's an important principle that a header should supply enough information to use it without a dependency requiring other headers. That means header should be able to be included in a compilation unit without causing a compiler error when you use any functions it declares.
Except
If this external dependency is desired behaviour. Instead of using conditional compilation you could have a well-documented requirement for them to supply their own header declaring X. This is an alternative to using #ifdefs and can be a useful way to introduce mocks or other variants.
The important distinction being some template techniques where you are explicitly NOT expected to instantiate them, mentioned just so someone doesn't get snarky with me.
Goto the Src folder of your Android project, and open the Java file.
Change the package OldName.android.widget
to newName.android.widget
.
It gives you an error like this
The declared package "newName.android.widget" does not match the expected package "OLDName.android.widget.
To fix this problem, select Move filename.Java to Newname.android.widget and delete the old package folder.
Next step: Go to AndroidManifest.xml
and change
package="OldName.android.widget"
to package="newName.android.widget"
.
no , there is nothing similar IndexOf for Dictionary although you can make use of ContainsKey method to get whether a key belongs to dictionary or not
Since you're using express, just add bodyParser:
app.use(express.bodyParser());
then your route automatically has access to the uploaded file(s) in req.files:
app.post('/todo/create', function (req, res) {
// TODO: move and rename the file using req.files.path & .name)
res.send(console.dir(req.files)); // DEBUG: display available fields
});
If you name the input control "todo" like this (in Jade):
form(action="/todo/create", method="POST", enctype="multipart/form-data")
input(type='file', name='todo')
button(type='submit') New
Then the uploaded file is ready by the time you get the path and original filename in 'files.todo':
other useful req.files properties:
Do the following, download SQLLite Database Browser from here:
Locate your db. file in your phone.
Then, as soon you install the program go to: "Browse Data", you will see all the SMS there!!
You can actually export the data to an excel file or SQL.
String cleanString = dirtyString.strip() ; // Call new `String::string` method.
String::strip…
The old String::trim
method has a strange definition of whitespace.
As discussed here, Java 11 adds new strip…
methods to the String
class. These use a more Unicode-savvy definition of whitespace. See the rules of this definition in the class JavaDoc for Character::isWhitespace
.
Example code.
String input = " some Thing ";
System.out.println("before->>"+input+"<<-");
input = input.strip();
System.out.println("after->>"+input+"<<-");
Or you can strip just the leading or just the trailing whitespace.
You do not mention exactly what code point(s) make up your newlines. I imagine your newline is likely included in this list of code points targeted by strip
:
The first thing to do is to check the details of the error message. For this you could use the LogCat App.
For me the problem was an error like
Cannot rename native library directory /data/app-lib/vmdl-... to /data/app-lib/com.xyz
The solution was to activate the common sense function in my brain and look for the com.xyz folder in the app-lib folder with ES-Explorer. I recognized that this folder was already there. So removing it solved the renaming problem and the apps can now install properly.
The idea consists to use the keys, when a value is already present in the array keys, the array size stays the same:
function getDistinctRandomNumbers ($nb, $min, $max) {
if ($max - $min + 1 < $nb)
return false; // or throw an exception
$res = array();
do {
$res[mt_rand($min, $max)] = 1;
} while (count($res) !== $nb);
return array_keys($res);
}
Pro: This way avoids the use of in_array
and doesn't generate a huge array. So, it is fast and preserves a lot of memory.
Cons: when the rate (range/quantity) decreases, the speed decreases too (but stays correct). For a same rate, relative speed increases with the range size.(*)
(*) I understand that fact since there are more free integers to select (in particular for the first steps), but if somebody has the mathematical formula that describes this behaviour, I am interested by, don't hesitate.
Conclusion: The best "general" function seems to be a mix between this function and @Anne function that is more efficient with a little rate. This function should switch between the two ways when a certain quantity is needed and a rate (range/quantity) is reached. So the complexity/time of the test to know that, must be taken in account.
Thanks for your replies. I have already solved my problem. Suppose I have my pages under http://www.yoursite.com/html, the following .htaccess rules apply.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /html/(.*).html\ HTTP/
RewriteRule .* http://localhost/html/%1 [R=301,L]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /html/(.*)\ HTTP/
RewriteRule .* %1.html [L]
</IfModule>
See this answer for a a clean & simple 'class' solution with a private and public interface and support for composition
If you want to pass the variable to your proxy backend, you have to set it with the proxy module.
location / {
proxy_pass http://example.com;
proxy_set_header Host example.com;
proxy_set_header HTTP_Country-Code $geoip_country_code;
proxy_pass_request_headers on;
}
And now it's passed to the proxy backend.
find . -type d > list.txt
Will list all directories and subdirectories under the current path. If you want to list all of the directories under a path other than the current one, change the .
to that other path.
If you want to exclude certain directories, you can filter them out with a negative condition:
find . -type d ! -name "~snapshot" > list.txt
Since the introduction of go.mod , I think both local and external package management becomes easier. Using go.mod, it is possible to have go project outside the GOPATH as well.
Create a folder demoproject and run following command to generate go.mod file
go mod init demoproject
I have a project structure like below inside the demoproject directory.
+-- go.mod
+-- src
+-- main.go
+-- model
+-- model.go
For the demo purpose, insert the following code in the model.go file.
package model
type Employee struct {
Id int32
FirstName string
LastName string
BadgeNumber int32
}
In main.go, I imported Employee model by referencing to "demoproject/src/model"
package main
import (
"demoproject/src/model"
"fmt"
)
func main() {
fmt.Printf("Main Function")
var employee = model.Employee{
Id: 1,
FirstName: "First name",
LastName: "Last Name",
BadgeNumber: 1000,
}
fmt.Printf(employee.FirstName)
}
Just run go get
command inside the project directory.
For example:
go get -u google.golang.org/grpc
It should include module dependency in the go.mod file
module demoproject
go 1.13
require (
golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa // indirect
golang.org/x/sys v0.0.0-20200124204421-9fbb57f87de9 // indirect
golang.org/x/text v0.3.2 // indirect
google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150 // indirect
google.golang.org/grpc v1.26.0 // indirect
)
Adding a new row in a DGV with no rows with Add() raises SelectionChanged event before you can insert any data (or bind an object in Tag property).
Create a clone row from RowTemplate is safer imho:
//assuming that you created columns (via code or designer) in myDGV
DataGridViewRow row = (DataGridViewRow) myDGV.RowTemplate.Clone();
row.CreateCells(myDGV, "cell1", "cell2", "cell3");
myDGV.Rows.Add(row);
You can use the following code snippet to achieve your goal:
Intent smsIntent = new Intent(Intent.ACTION_SENDTO);
smsIntent.setData(Uri.parse("smsto:"+model.getPhoneNo().trim()));
smsIntent.addCategory(Intent.CATEGORY_DEFAULT);
smsIntent.putExtra("sms_body","Hello this is dummy text");
startActivity(smsIntent);
If you don't want any text then remove the sms_body key.
Intent smsIntent = new Intent(Intent.ACTION_SENDTO);
smsIntent.setData(Uri.parse("smsto:"+shopkepperDataModel.getPhoneNo().trim()));
smsIntent.addCategory(Intent.CATEGORY_DEFAULT);
startActivity(smsIntent);
In my opinion, I think it's important to explain the why behind the need for a GROUP BY in your SQL when summing with OVER() clause and why you are getting repeated lines of data when you are expecting one row per BrandID.
Take this example: You need to aggregate the total sale price of each order line, per specific order category, between two dates, but you also need to retain individual order data in your final results. A SUM() on the SalesPrice column would not allow you to get the correct totals because it would require a GROUP BY, therefore squashing the details because you wouldn't be able to keep the individual order lines in the select statement.
Many times we see a #temp table, @table variable, or CTE filled with the sum of our data and grouped up so we can join to it again later to get a column of the sums we need. This can add processing time and extra lines of code. Instead, use OVER(PARTITION BY ()) like this:
SELECT
OrderLine,
OrderDateTime,
SalePrice,
OrderCategory,
SUM(SalePrice) OVER(PARTITION BY OrderCategory) AS SaleTotalPerCategory
FROM tblSales
WHERE OrderDateTime BETWEEN @StartDate AND @EndDate
Notice we are not grouping and we have individual order lines column selected. The PARTITION BY in the last column will return us a sales price total for each row of data in each category. What the last column essentially says is, we want the sum of the sale price (SUM(SalePrice)) over a partition of my results and by a specified category (OVER(PARTITION BY CategoryHere)).
If we remove the other columns from our select statement, and leave our final SUM() column, like this:
SELECT
SUM(SalePrice) OVER(PARTITION BY OrderCategory) AS SaleTotalPerCategory
FROM tblSales
WHERE OrderDateTime BETWEEN @StartDate AND @EndDate
The results will still repeat this sum for each row in our original result set. The reason is this method does not require a GROUP BY. If you don't need to retain individual line data, then simply SUM() without the use of OVER() and group up your data appropriately. Again, if you need an additional column with specific totals, you can use the OVER(PARTITION BY ()) method described above without additional selects to join back to.
The above is purely for explaining WHY he is getting repeated lines of the same number and to help understand what this clause provides. This method can be used in many ways and I highly encourage further reading from the documentation here:
2019 Update: I realize that this is somewhat bad advice. As the first comment states, this heavily depends on the situation, and it is not a bad practice to use the [hidden] attribute: see the comments for some of the cases where you need to use it and not *ngIf
Original answer:
You should always try to use *ngIf
instead of [hidden]
.
<input *ngIf="!isHidden" class="txt" type="password" [(ngModel)]="input_pw" >
There are several blog posts about that topics, but the bottom line is, that Hidden usually means you do not want the browser to render the object - using angular you still waste resource on rendering it, and it will end up in the DOM anyway (and tricky users can see it with basic browser manipulation).
You are trying to read the value of your checkbox before it is loaded. The script runs before the checkbox exists. You need to call your script when the page loads:
<body onload="dosomething()">
Example:
http://jsfiddle.net/jtbowden/6dx6A/
You are also missing a semi-colon after your first assignment.
In storyboard and image Assets. you can change this two also:
Update the Render Mode to Template Image
Update the tint Color in Views.
When you create a folder with N entries, you create a list of N items at file-system level. This list is a system-wide shared data structure. If you then start modifying this list continuously by adding/removing entries, I expect at least some lock contention over shared data. This contention - theoretically - can negatively affect performance.
For read-only scenarios I can't imagine any reason for performance degradation of directories with large number of entries.
use this code below as progress.xml:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background">
<shape>
<corners android:radius="5dip" />
<gradient
android:startColor="#ff9d9e9d"
android:centerColor="#ff5a5d5a"
android:centerY="0.75"
android:endColor="#ff747674"
android:angle="270"
/>
</shape>
</item>
<item android:id="@android:id/secondaryProgress">
<clip>
<shape>
<solid android:color="#00000000" />
</shape>
</clip>
</item>
<item android:id="@android:id/progress">
<clip>
<shape>
<solid android:color="#00000000" />
</shape>
</clip>
</item>
</layer-list>
where:
after that use it in the layout containing the xml:
<SeekBar
android:id="@+id/myseekbar"
...
android:progressDrawable="@drawable/progress"
/>
you can also customize the thumb by using a custom icon seek_thumb.png:
android:thumb="@drawable/seek_thumb"
public ActionResult Questionnaire()
{
return Redirect("~/MedicalHistory.html");
}
When searching for an answer to the very same question I came across gem_unused.
You also might wanna read this article: http://chill.manilla.com/2012/12/31/clean-up-your-dirty-gemsets/
The source code is available on GitHub: https://github.com/apolzon/gem_unused
Update:
Improved and simplified version of previous directive (one instead of two) with same functionality:
.directive('myTestExpression', ['$parse', function ($parse) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
var expr = attrs.myTestExpression;
var watches = attrs.myTestExpressionWatch;
ctrl.$validators.mytestexpression = function (modelValue, viewValue) {
return expr == undefined || (angular.isString(expr) && expr.length < 1) || $parse(expr)(scope, { $model: modelValue, $view: viewValue }) === true;
};
if (angular.isString(watches)) {
angular.forEach(watches.split(",").filter(function (n) { return !!n; }), function (n) {
scope.$watch(n, function () {
ctrl.$validate();
});
});
}
}
};
}])
Example usage:
<input ng-model="price1"
my-test-expression="$model > 0"
my-test-expression-watch="price2,someOtherWatchedPrice" />
<input ng-model="price2"
my-test-expression="$model > 10"
my-test-expression-watch="price1"
required />
Result: Mutually dependent test expressions where validators are executed on change of other's directive model and current model.
Test expression has local $model
variable which you should use to compare it to other variables.
Previously:
I've made an attempt to improve @Plantface code by adding extra directive. This extra directive very useful if our expression needs to be executed when changes are made in more than one ngModel variables.
.directive('ensureExpression', ['$parse', function($parse) {
return {
restrict: 'A',
require: 'ngModel',
controller: function () { },
scope: true,
link: function (scope, element, attrs, ngModelCtrl) {
scope.validate = function () {
var booleanResult = $parse(attrs.ensureExpression)(scope);
ngModelCtrl.$setValidity('expression', booleanResult);
};
scope.$watch(attrs.ngModel, function(value) {
scope.validate();
});
}
};
}])
.directive('ensureWatch', ['$parse', function ($parse) {
return {
restrict: 'A',
require: 'ensureExpression',
link: function (scope, element, attrs, ctrl) {
angular.forEach(attrs.ensureWatch.split(",").filter(function (n) { return !!n; }), function (n) {
scope.$watch(n, function () {
scope.validate();
});
});
}
};
}])
Example how to use it to make cross validated fields:
<input name="price1"
ng-model="price1"
ensure-expression="price1 > price2"
ensure-watch="price2" />
<input name="price2"
ng-model="price2"
ensure-expression="price2 > price3"
ensure-watch="price3" />
<input name="price3"
ng-model="price3"
ensure-expression="price3 > price1 && price3 > price2"
ensure-watch="price1,price2" />
ensure-expression
is executed to validate model when ng-model
or any of ensure-watch
variables is changed.
I have exactly the same issue as above, and took me the whole day to discover that it doesn't like my newline approach. Instead I reused the same code with semi-colon approach instead. For example my initial code using the newline (which threw the same error as yours):
Y=1
while test "$Y" -le "20"
do
echo "Number $Y"
Y=$[Y+1]
done
And using code with semicolon approach with worked wonder:
Y=1 ; while test "$Y" -le "20"; do echo "Number $Y"; Y=$[Y+1] ; done
I notice the same problem occurs for other commands as well using the newline approach, so I think I am gonna stick to using semicolon for my future code.
Undoubtly this can be simplified but the results match your expectations.
The gist of this is to
CTE
for each t2ID
CTE
for each t2ID
CTE
's SQL Statement
;WITH MaxPrice AS (
SELECT t2ID
, t1ID
FROM (
SELECT t2.ID AS t2ID
, t1.ID AS t1ID
, rn = ROW_NUMBER() OVER (PARTITION BY t2.ID ORDER BY t1.Price DESC)
FROM @t1 t1
INNER JOIN @relation r ON r.t1ID = t1.ID
INNER JOIN @t2 t2 ON t2.ID = r.t2ID
) maxt1
WHERE maxt1.rn = 1
)
, SumPrice AS (
SELECT t2ID = t2.ID
, Price = SUM(Price)
FROM @t1 t1
INNER JOIN @relation r ON r.t1ID = t1.ID
INNER JOIN @t2 t2 ON t2.ID = r.t2ID
GROUP BY
t2.ID
)
SELECT t2.ID
, t2.Name
, t2.Orders
, mp.t1ID
, t1.ID
, t1.Name
, sp.Price
FROM @t2 t2
INNER JOIN MaxPrice mp ON mp.t2ID = t2.ID
INNER JOIN SumPrice sp ON sp.t2ID = t2.ID
INNER JOIN @t1 t1 ON t1.ID = mp.t1ID
I had the same problem and this saved me from the problem in second:
write in console this:
npm i --save bluebird
npm i --save-dev @types/bluebird @types/[email protected]
in the file where the problem is copy paste this:
import * as Promise from 'bluebird';
strip
doesn't mean "remove this substring". x.strip(y)
treats y
as a set of characters and strips any characters in that set from both ends of x
.
On Python 3.9 and newer you can use the removeprefix
and removesuffix
methods to remove an entire substring from either side of the string:
url = 'abcdc.com'
url.removesuffix('.com') # Returns 'abcdc'
url.removeprefix('abcdc.') # Returns 'com'
The relevant Python Enhancement Proposal is PEP-616.
On Python 3.8 and older you can use endswith
and slicing:
url = 'abcdc.com'
if url.endswith('.com'):
url = url[:-4]
Or a regular expression:
import re
url = 'abcdc.com'
url = re.sub('\.com$', '', url)
If you want to open a windows file explorer, you should call explorer.exe
Call Shell("explorer.exe" & " " & "P:\Engineering", vbNormalFocus)
Equivalent syxntax
Shell "explorer.exe" & " " & "P:\Engineering", vbNormalFocus
var coordinates = [jsonObject[3][0],
jsonObject[3][0],
jsonObject[4][1],
jsonObject[4][1]];