I'm going to go right ahead and offer a solution using jQuery, which means you will need to import the library if you haven't already...
Import the jQuery library in your page mark-up:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
Then create another *.js script file (I call mine ExecutePageMethod
, since that is the only method it is going to expose) and import it:
<script type="text/javascript" src="/ExecutePageMethod.js" ></script>
Within the newly added file, add the following code (I remember pulling this from elsewhere, so someone else deserves credit for it really):
function ExecutePageMethod(page, fn, paramArray, successFn, errorFn) {
var paramList = '';
if (paramArray.length > 0) {
for (var i = 0; i < paramArray.length; i += 2) {
if (paramList.length > 0) paramList += ',';
paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
}
}
paramList = '{' + paramList + '}';
$.ajax({
type: "POST",
url: page + "/" + fn,
contentType: "application/json; charset=utf-8",
data: paramList,
dataType: "json",
success: successFn,
error: errorFn
});
}
You will then need to augment your .NET page method with the appropriate attributes, as such:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string MyMethod()
{
return "Yay!";
}
Now, within your page mark-up, within a script
block or from another script file, you can call the method, like so:
ExecutePageMethod("PageName.aspx", "MyMethod", [], OnSuccess, OnFailure);
Obviously you will need to implement the OnSuccess
and OnFailure
methods.
To consume the results, say in the OnSuccess
method, you can use the parseJSON method, which, if the results become more complex (in the case or returning an array of types, for instance) this method will parse it into objects:
function OnSuccess(result) {
var parsedResult = jQuery.parseJSON(result.d);
}
This ExecutePageMethod
code is particularly useful since it it reusable, so rather than having to manage an $.ajax
call for each page method you might want to execute, you just need to pass the page, method name and arguments to this method.
htop
gives a nice overview of individual core usage
When using floating point numbers you cannot trust that your local tests will be exactly the same as the tests that are done on the server side. The environment and the compiler are probably different on you local system and where the final tests are run. I have seen this problem many times before in some TopCoder competitions especially if you try to compare two floating point numbers.
Try DataGridView.CurrentCellAddress.
Returns: A Point that represents the row and column indexes of the currently active cell.
E.G. Select the first column and the fifth row, and you'll get back: Point( X=1, Y=5 )
This problem has very simple solution. Just open your SmartGit, then go to Repository option(On top left), then go to settings. It will open a dialog box of Repository Settings. Now, click on Commit TAB and write your UserName and EmailId which you give on BitBucke website. Now click ok and again try to Commit and it works fine now.
i have experienced same issue in my spring boot application. after removing manually javax.persistance.jar file from lib folder. issue was fixed. in pom.xml file i have remained following dependency only
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
You can use JQuery for this
<asp:Button runat="server" ID="btnID" />
than in JQuery
$("#btnID").click(function(e){e.preventDefault();})
No, but you can write your own:
public static bool Between(this int num, int lower, int upper, bool inclusive = false)
{
return inclusive
? lower <= num && num <= upper
: lower < num && num < upper;
}
You can set new indices by using set_index
:
df2.set_index(np.arange(len(df2.index)))
Output:
x y
0 0 0
1 0 1
2 0 2
3 1 0
4 1 1
5 1 2
6 2 0
7 2 1
8 2 2
Try to use single quotes (') to avoid shell escaping of your string. Remember that the expression needs to match the whole path, i.e. needs to look like:
find . -regex '\./[a-f0-9-]*.jpg'
Apart from that, it seems that my find (GNU 4.4.2) only knows basic regular expressions, especially not the {36} syntax. I think you'll have to make do without it.
Try:
$(document).ready(function(){
$('a .sign_new').click(function(){
alert('Sign new href executed.');
});
});
You've mixed up the class
and href
names / selector type.
Ok, I know I'm late to the party, but here is the syntax I think is best. Add a schema name if needed to the OBJECT_ID clause.
IF OBJECTPROPERTY(OBJECT_ID(N'My_FK_name'),'IsConstraint') =1
ALTER TABLE dbo.TableName DROP CONSTRAINT My_FK_name
Solution 0
This can be accompished using pivot tables.
Solution 1
Use the unique
formula to get all the distinct values. Then use countif
to get the count of each value. See the working example link at the top to see exactly how this is implemented.
Unique Values Count
=UNIQUE(A3:A8) =COUNTIF(A3:A8;B3)
=COUNTIF(A3:A8;B4)
...
Solution 2
If you setup your data as such:
City
----
London 1
Paris 1
London 1
Berlin 1
Rome 1
Paris 1
Then the following will produce the desired result.
=sort(transpose(query(A3:B8,"Select sum(B) pivot (A)")),2,FALSE)
I'm sure there is a way to get rid of the second column since all values will be 1. Not an ideal solution in my opinion.
via http://googledocsforlife.blogspot.com/2011/12/counting-unique-values-of-data-set.html
Other Possibly Helpful Links
Few things:
Why are your use-permissions and use-features tags in your activity tag. Generally, permissions are included as direct children of your <manifest>
tag. This could be part of the problem.
According to the android camera open documentation, a runtime exception is thrown:
if connection to the camera service fails (for example, if the camera is in use by another process or device policy manager has disabled the camera)
Have you tried checking if the camera is being used by something else or if your policy manager has some setting where the camera is turned off?
Don't forget the <uses-feature android:name="android.hardware.camera.autofocus" />
for autofocus.
While I'm not sure if any of these will directly help you, I think they're worth investigating if for no other reason than to simply rule out. Due diligence if you will.
EDIT
As mentioned in the comments below, the solution was to move the uses-permissions
up to above the application tag.
I've done it with two annotations for test class: @RunWith(SpringRunner.class)
and @SpringBootTest
.
Example:
@RunWith(SpringRunner.class )
@SpringBootTest
public class ProtocolTransactionServiceTest {
@Autowired
private ProtocolTransactionService protocolTransactionService;
}
@SpringBootTest
loads the whole context, which was OK in my case.
For UNIX-Like systems you might want to execute "echo ~username
" using the shell (so use Runtime.exec()
to run {"/bin/sh", "-c", "echo ~username"}
).
Hiya demo http://jsfiddle.net/LYTbc/
this is a reference to the DOM element, so you can wrap it directly.
attr
api: http://api.jquery.com/attr/
The .attr() method gets the attribute value for only the first element in the matched set.
have a nice one, cheers!
code
$(document).ready(function () {
$(".inputs").click(function () {
alert(this.id);
alert(" or " + $(this).attr("id"));
});
});?
Database and table names are not case sensitive in Windows, and case sensitive in most varieties of Unix or Linux.
To resolve the issue, set the lower_case_table_names to 1
lower_case_table_names=1
This will make all your tables lowercase, no matter how you write them.
"Obliberating" contents from a svn repository, i.e. wiping this contents from the disc, can be done as described in this article http://www.limilabs.com/blog/how-to-permanently-remove-svn-folder
It requires access to the server side svn repository, thus you must have some admin privileges.
It works by (a) dumping the repository content into a file, (b) excluding some contents and (c) wiping and re-creating the plain repository again and eventually by (d) loading the filtered repository contents:
svnadmin dump "path/to/svnrepo" > svnrepo.txt // (a)
svndumpfilter exclude "my/folder" < svnrepo.txt > filtered.txt // (b)
rm -rf "path/to/svnrepo" && svnadmin create "path/to/svnrepo" // (c)
svnadmin load "path/to/svnrepo" < filtered.txt // (d)
The repository counter is unchanged by this operations. However, your repository is now "missing" all those revision numbers used to create that contents you removed in step (b).
Subversion 1.7.5 appears to handle this "missing" revisions pretty well. Using "svn ls -r $missing" for example, reports the very same as "svn ls -r $(( missing - 1))".
Contrary to this, my (pretty old) VIEWVC reports "no contents" when querying a "missing" revision.
SELECT * FROM TABLE
WHERE DATE BETWEEN '09/16/2010 05:00:00' and '09/21/2010 09:00:00'
The node.js docs for fs.mkdir
basically defer to the Linux man page for mkdir(2)
. That indicates that EEXIST
will also be indicated if the path exists but isn't a directory which creates an awkward corner case if you go this route.
You may be better off calling fs.stat
which will tell you whether the path exists and if it's a directory in a single call. For (what I'm assuming is) the normal case where the directory already exists, it's only a single filesystem hit.
These fs
module methods are thin wrappers around the native C APIs so you've got to check the man pages referenced in the node.js docs for the details.
Take a look at this question.
TL;DR: clean, then build.
./gradlew clean packageDebug
Let,
#include <vector>
vector<int> v {1, 2, 3, -1, -2, -3};
If the vector is sorted in ascending or descending order then you can find it with complexity O(1).
For a vector of ascending order the first element is the smallest element, you can get it by v[0] (0 based indexing) and last element is the largest element, you can get it by v[sizeOfVector-1].
If the vector is sorted in descending order then the last element is the smallest element,you can get it by v[sizeOfVector-1] and first element is the largest element, you can get it by v[0].
If the vector is not sorted then you have to iterate over the vector to get the smallest/largest element.In this case time complexity is O(n), here n is the size of vector.
int smallest_element = v[0]; //let, first element is the smallest one
int largest_element = v[0]; //also let, first element is the biggest one
for(int i = 1; i < v.size(); i++) //start iterating from the second element
{
if(v[i] < smallest_element)
{
smallest_element = v[i];
}
if(v[i] > largest_element)
{
largest_element = v[i];
}
}
You can use iterator,
for (vector<int>:: iterator it = v.begin(); it != v.end(); it++)
{
if(*it < smallest_element) //used *it (with asterisk), because it's an iterator
{
smallest_element = *it;
}
if(*it > largest_element)
{
largest_element = *it;
}
}
You can calculate it in input section (when you have to find smallest or largest element from a given vector)
int smallest_element, largest_element, value;
vector <int> v;
int n;//n is the number of elements to enter
cin >> n;
for(int i = 0;i<n;i++)
{
cin>>value;
if(i==0)
{
smallest_element= value; //smallest_element=v[0];
largest_element= value; //also, largest_element = v[0]
}
if(value<smallest_element and i>0)
{
smallest_element = value;
}
if(value>largest_element and i>0)
{
largest_element = value;
}
v.push_back(value);
}
Also you can get smallest/largest element by built in functions
#include<algorithm>
int smallest_element = *min_element(v.begin(),v.end());
int largest_element = *max_element(v.begin(),v.end());
You can get smallest/largest element of any range by using this functions. such as,
vector<int> v {1,2,3,-1,-2,-3};
cout << *min_element(v.begin(), v.begin() + 3); //this will print 1,smallest element of first three elements
cout << *max_element(v.begin(), v.begin() + 3); //largest element of first three elements
cout << *min_element(v.begin() + 2, v.begin() + 5); // -2, smallest element between third and fifth element (inclusive)
cout << *max_element(v.begin() + 2, v.begin()+5); //largest element between third and first element (inclusive)
I have used asterisk (*), before min_element()/max_element() functions. Because both of them return iterator. All codes are in c++.
Check out fontsquirrel. They have a web font generator, which will also spit out a suitable stylesheet for your font (look for "@font-face kit"). This stylesheet can be included in your own, or you can use it as a template.
CardView
extends FrameLayout, so it support foreground
attribute. Using foreground
attribute can also add border easily.
layout as follows:
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/link_card"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:foreground="@drawable/bg_roundrect_ripple_light_border"
app:cardCornerRadius="23dp"
app:cardElevation="0dp">
</androidx.cardview.widget.CardView>
bg_roundrect_ripple_light_border.xml
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@color/ripple_color_light">
<item>
<shape android:shape="rectangle">
<stroke
android:width="0.5dp"
android:color="#DDDDDD" />
<corners android:radius="23dp" />
</shape>
</item>
<item android:id="@android:id/mask">
<shape android:shape="rectangle">
<corners android:radius="23dp" />
<solid android:color="@color/background" />
</shape>
</item>
</ripple>
To quickly find a meaningful error message by inspecting the error during debugging:
Add a quick watch for:
((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors
Drill down into EntityValidationErrors like this:
(collection item e.g. [0]) > ValidationErrors > (collection item e.g. [0]) > ErrorMessage
if you're using php jquery, this might help:
$.ajax({
url:'phpmd5file.php',
data:{'mypassword',mypassword},
dataType:"json",
method:"POST",
success:function(mymd5password){
alert(mymd5password);
}
});
on your phpmd5.php file:
echo json_encode($_POST["mypassword"]);
no jsplugins needed. just use ajax and let php md5() do the job.
You would need an IoC container if you needed to centralize the configuration of your dependencies so that they may be easily swapped out en mass. This makes the most sense in TDD, where many dependencies are swapped out, but where there is little interdependence between the dependencies. This is done at the cost of obfuscating the flow of control of object construction to some degree, so having a well organized and reasonably documented configuration is important. It is also good to have a reason to do this, otherwise, it is mere abstraction gold-plating. I have seen it done so poorly that it was dragged down to being the equivalent to a goto statement for constructors.
Today I got this error, and after debugging I figured out that the actual tables were misssing, which I was referring using synonyms. So I suggest - first check that whether the tables exists!! :-))
Something that has helped me: if you have ranges of variables to convert (or just more then one), you can use sapply
.
A bit nonsensical but just for example:
data(cars)
cars[, 1:2] <- sapply(cars[, 1:2], as.factor)
Say columns 3, 6-15 and 37 of you dataframe need to be converted to numeric one could:
dat[, c(3,6:15,37)] <- sapply(dat[, c(3,6:15,37)], as.numeric)
Below are the way to Generate 4 Or 8 Characters Long Random Alphanumeric String in SQL
select LEFT(CONVERT(VARCHAR(36),NEWID()),4)+RIGHT(CONVERT(VARCHAR(36),NEWID()),4)
SELECT RIGHT(REPLACE(CONVERT(VARCHAR(36),NEWID()),'-',''),8)
I have also received this error when developing automatic tests for components. In this context the following import should be done:
import { RouterTestingModule } from "@angular/router/testing";
const testBedConfiguration = {
imports: [SharedModule,
BrowserAnimationsModule,
RouterTestingModule.withRoutes([]),
],
Do this:
long l = Long.parseLong(str);
However, always check that str contains digits to prevent throwing exceptions. For instance:
String str="ABCDE";
long l = Long.parseLong(str);
would throw an exception but this
String str="1234567";
long l = Long.parseLong(str);
won't.
lsof and fuser didn't give me anything either.
After a process of renaming all possible directories to .old and rebooting the system every time after I made changes I found one particular directory (relating to postfix) that was responsible.
It turned out that I had once made a symlink from /var/spool/postfix to /disk2/pers/mail/postfix/varspool in order to minimise disk writes on an SDCARD-based root filesystem (Sheeva Plug).
With this symlink, even after stopping the postfix and dovecot services (both ps aux as well as netstat -tuanp didn't show anything related) I was not able to unmount /disk2/pers.
When I removed the symlink and updated the postfix and dovecot config files to point directly to the new dirs on /disk2/pers/ I was able to successfully stop the services and unmount the directory.
Next time I will look more closely at the output of:
ls -lR /var | grep ^l | grep disk2
The above command will recursively list all symbolic links in a directory tree (here starting at /var) and filter out those names that point to a specific target mount point (here disk2).
For anyone experiencing this in angular 9+
This issue can also be experienced if you do not declare or import the component that declares your component.
Lets consider a situation where you intend to use ng-select
but you forget to import it Angular will throw the error 'No value accessor...'
I have reproduced this error in the Below stackblitz demo.
In case that you have Ubuntu in your machine, the following steps will help you:
Open your terminal and paste: sudo apt-get install php-soap.
Restart your apache2 server in terminal : service apache2 restart.
To check use your php test file again to be seems like mine in step 1.
run composer update
. That's it
Why don't You just use:
label {
display: block;
width: 50px;
height: 24px;
float: left;
}
As in Internet Explorer, the javascript method "includes" doesn't support which is leading to the error as below
dijit.form.FilteringSelect TypeError: Object doesn't support property or method 'includes'
So I have changed the JavaScript string method from "includes" to "indexOf" as below
//str1 doesn't match str2 w.r.t index, so it will try to add object
var str1="acd", str2="b";
if(str1.indexOf(str2) == -1)
{
alert("add object");
}
else
{
alert("object not added");
}
You can use:
<asp:textbox id="textBox1" style="text-align:center"></asp:textbox>
Or this:
textbox.Style["text-align"] = "center"; //right, left
If you use Python3, you can use ipaddress
module http://docs.python.org/py3k/library/ipaddress.html. Example:
>>> import ipaddress
>>> ipv6 = "2001:0db8:0a0b:12f0:0000:0000:0000:0001"
>>> ipv4 = "192.168.2.10"
>>> ipv4invalid = "266.255.9.10"
>>> str = "Tay Tay"
>>> ipaddress.ip_address(ipv6)
IPv6Address('2001:db8:a0b:12f0::1')
>>> ipaddress.ip_address(ipv4)
IPv4Address('192.168.2.10')
>>> ipaddress.ip_address(ipv4invalid)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/lib/python3.4/ipaddress.py", line 54, in ip_address
address)
ValueError: '266.255.9.10' does not appear to be an IPv4 or IPv6 address
>>> ipaddress.ip_address(str)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/lib/python3.4/ipaddress.py", line 54, in ip_address
address)
ValueError: 'Tay Tay' does not appear to be an IPv4 or IPv6 address
You can actually install both packages at the same time. For me:
conda install -c anaconda graphviz python-graphviz
did the trick.
Based on Yamikep's answer, I found a better and very simple solution which also handles ModelMultipleChoiceField
fields.
Removing field from form.cleaned_data
prevents fields from being saved:
class ReadOnlyFieldsMixin(object):
readonly_fields = ()
def __init__(self, *args, **kwargs):
super(ReadOnlyFieldsMixin, self).__init__(*args, **kwargs)
for field in (field for name, field in self.fields.iteritems() if
name in self.readonly_fields):
field.widget.attrs['disabled'] = 'true'
field.required = False
def clean(self):
for f in self.readonly_fields:
self.cleaned_data.pop(f, None)
return super(ReadOnlyFieldsMixin, self).clean()
Usage:
class MyFormWithReadOnlyFields(ReadOnlyFieldsMixin, MyForm):
readonly_fields = ('field1', 'field2', 'fieldx')
Some notes to complement the ALTER DATABASE process:
1) You can obtain a full list of databases with logical names and full paths of MDF and LDF files:
USE master SELECT name, physical_name FROM sys.master_files
2) You can move manually the files with CMD move command:
Move "Source" "Destination"
Example:
md "D:\MSSQLData"
Move "C:\test\SYSADMIT-DB.mdf" "D:\MSSQLData\SYSADMIT-DB_Data.mdf"
Move "C:\test\SYSADMIT-DB_log.ldf" "D:\MSSQLData\SYSADMIT-DB_log.ldf"
3) You should change the default database path for new databases creation. The default path is obtained from the Windows registry.
You can also change with T-SQL, for example, to set default destination to: D:\MSSQLData
USE [master]
GO
EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'DefaultData', REG_SZ, N'D:\MSSQLData'
GO
EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'DefaultLog', REG_SZ, N'D:\MSSQLData'
GO
Extracted from: http://www.sysadmit.com/2016/08/mover-base-de-datos-sql-server-a-otro-disco.html
Use:
sed -n '1,100p' filename > output.txt
Here, 1 and 100 are the line numbers which you will capture in output.txt
.
There is an assertNotEquals
in JUnit 4.11: https://github.com/junit-team/junit/blob/master/doc/ReleaseNotes4.11.md#improvements-to-assert-and-assume
import static org.junit.Assert.assertNotEquals;
Check if you imported the header files of classes that are throwing this error.
To avoid to add sources files .java
to your package you should do
cd src/
jar cvf mylib.jar com/**/*.class
Supposed that your project structure was like
myproject/
src/
com/
mycompany/
mainClass.java
mainClass.class
Download HAXM from SDK Manager
Open your SDK Manager from Android Studio, click the icon shown in the screen shot.
Click on "Launch Standalone SDK Manager" on the "Default Settings" Dialog.
Check node "Extras > Intel x86 Emulator Accelerator (HAXM installer)" and proceed with HAXM download.
Installing or Modifying HAXM
You can now access with installation (or modifying existing installtino) of HAXM by accessing the download location. Enter this path in "run"
%localappdata%\Android\sdk\extras\intel\Hardware_Accelerated_Execution_Manager
and double click the file "intelhaxm-android.exe"
You can increase the size of memory allocated to HAXM while modifying existing HAXM install. I have a machine with 32 GB of RAM and would like to launch multiple AVDs at same time (for automated testing etc.) so I have allocated 8 GB to HAXM.
Caveat
If you are running one AVD of one 1 GB and allocated 2 GB to HAXM, you cannot run another AVD with RAM more than 1 GB. Please make sure that Android Device Monitor is not running when you are modifying or installing HAXM (just to avoid any suprises).
These steps are tested on Windows platform, but generally could be applied to other platforms too with slight modification.
If you are here for a filepath just use "\\"
import os
path = r"c:\file"+"\\"+"path"
os.path.normpath(path)
which will outputc:\file\path
Here's a bash script I use, works on OSX 10.11.3.
#!/bin/bash
PLUGINS=$(cordova plugin list | awk '{print $1}')
for PLUGIN in $PLUGINS; do
cordova plugin rm $PLUGIN --save && cordova plugin add $PLUGIN --save
done
This may help if there are conflicts, per shan's comment. The difference is the addition of the --force
flag when removing.
#!/bin/bash
PLUGINS=$(cordova plugin list | awk '{print $1}')
for PLUGIN in $PLUGINS; do
cordova plugin rm $PLUGIN --force --save && cordova plugin add $PLUGIN --save
done
You can use comments like in regular JavaScript:
[...] TypeScript syntax is a superset of ECMAScript 2015 (ES2015) syntax.
[...] This document describes the syntactic grammar added by TypeScript [...]
Source: TypeScript Language Specification
The only two mentions of the word "comments" in the spec are:
[...] TypeScript also provides to JavaScript programmers a system of optional type annotations. These type annotations are like the JSDoc comments found in the Closure system, but in TypeScript they are integrated directly into the language syntax. This integration makes the code more readable and reduces the maintenance cost of synchronizing type annotations with their corresponding variables.
11.1.1 Source Files Dependencies
[...] A comment of the form
/// <reference path="..."/>
adds a dependency on the source file specified in the path argument. The path is resolved relative to the directory of the containing source file.
C++17 (N4659
) includes a proposal Refining Expression Evaluation Order for Idiomatic C++
which defines a stricter order of expression evaluation.
In particular, the following sentence
8.18 Assignment and compound assignment operators:
....In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression. The right operand is sequenced before the left operand.
together with the following clarification
An expression X is said to be sequenced before an expression Y if every value computation and every side effect associated with the expression X is sequenced before every value computation and every side effect associated with the expression Y.
make several cases of previously undefined behavior valid, including the one in question:
a[++i] = i;
However several other similar cases still lead to undefined behavior.
In N4140
:
i = i++ + 1; // the behavior is undefined
But in N4659
i = i++ + 1; // the value of i is incremented
i = i++ + i; // the behavior is undefined
Of course, using a C++17 compliant compiler does not necessarily mean that one should start writing such expressions.
Spinner
<Spinner
android:id="@+id/To_Units"
style="@style/spinner_style" />
style.xml
<style name="spinner_style">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:background">@drawable/gradient_spinner</item>
<item name="android:layout_margin">10dp</item>
<item name="android:paddingLeft">8dp</item>
<item name="android:paddingRight">20dp</item>
<item name="android:paddingTop">5dp</item>
<item name="android:paddingBottom">5dp</item>
<item name="android:popupBackground">#DFFFFFFF</item>
</style>
gradient_spinner.xml (in drawable folder)
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item><layer-list>
<item><shape>
<gradient android:angle="90" android:endColor="#B3BBCC" android:startColor="#E8EBEF" android:type="linear" />
<stroke android:width="1dp" android:color="#000000" />
<corners android:radius="4dp" />
<padding android:bottom="3dp" android:left="3dp" android:right="3dp" android:top="3dp" />
</shape></item>
<item ><bitmap android:gravity="bottom|right" android:src="@drawable/spinner_arrow" />
</item>
</layer-list></item>
</selector>
@drawable/spinner_arrow
is your bottom right corner image
Authentication is managed at a database level. When you try to connect to the system using a database, mongo actually checks for the credentials you provide in the collection <database>.system.users
. So, basically when you are trying to connect to "test", it looks for the credentials in test.system.users
and returns an error because it cannot find them (as they are stored in admin.system.users
). Having the right to read and write from all db doesn't mean you can directly connect to them.
You have to connect to the database holding the credentials first. Try:
mongo admin -u admin -p SECRETPASSWORD
For more info, check this http://docs.mongodb.org/manual/reference/privilege-documents/
mysqldump --no-create-info ...
Also you may use:
--skip-triggers
: if you are using triggers--no-create-db
: if you are using --databases ...
option--compact
: if you want to get rid of extra commentsJust did this and UrlSearchParams did the trick Here is my code if it helps someone
import 'url-search-params-polyfill';
const userLogsInOptions = (username, password) => {
// const formData = new FormData();
const formData = new URLSearchParams();
formData.append('grant_type', 'password');
formData.append('client_id', 'entrance-app');
formData.append('username', username);
formData.append('password', password);
return (
{
method: 'POST',
headers: {
// "Content-Type": "application/json; charset=utf-8",
"Content-Type": "application/x-www-form-urlencoded",
},
body: formData.toString(),
json: true,
}
);
};
const getUserUnlockToken = async (username, password) => {
const userLoginUri = `${scheme}://${host}/auth/realms/${realm}/protocol/openid-connect/token`;
const response = await fetch(
userLoginUri,
userLogsInOptions(username, password),
);
const responseJson = await response.json();
console.log('acces_token ', responseJson.access_token);
if (responseJson.error) {
console.error('error ', responseJson.error);
}
console.log('json ', responseJson);
return responseJson.access_token;
};
My most preferred way is,
var objectKeysArray = Object.keys(yourJsonObj)
objectKeysArray.forEach(function(objKey) {
var objValue = yourJsonObj[objKey]
})
You need to set your local branch to track the remote branch, which it won't do automatically if they have different capitalizations.
Try:
git branch --set-upstream downloadmanager origin/DownloadManager
git pull
UPDATE:
'--set-upstream' option is no longer supported.
git branch --set-upstream-to downloadmanager origin/DownloadManager
git pull
Are you working with a @Service
too? Because if you are, then you can @Autowired
your PersonRepository
to the @Service
and then in the service just invoke the Name
class and use the form that @CuriosMind... proposed:
@Query(select p from Person p where p.forename = :forename and p.surname = :surname)
User findByForenameAndSurname(@Param("surname") String lastname,
@Param("forename") String firstname);
}
and when invoking the method from the repository in the service, you can then pass those parameters.
urllib2.urlopen does an HTTP GET (or POST if you supply a data argument), not an HTTP HEAD (if it did the latter, you couldn't do readlines or other accesses to the page body, of course).
MongoDB 3.6 include $expr https://docs.mongodb.com/manual/reference/operator/query/expr/
You can use $expr in order to evaluate an expression inside a $match, or find.
{ $match: {
$expr: {$gt: [{$size: "$yourArrayField"}, 0]}
}
}
or find
collection.find({$expr: {$gte: [{$size: "$yourArrayField"}, 0]}});
//This will sort your array
function SortByName(a, b){
var aName = a.name.toLowerCase();
var bName = b.name.toLowerCase();
return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
}
array.sort(SortByName);
Some ideas in the following answer:
Steps in creating a web service using Axis2 - The client code
Gives an example of a Groovy client invoking the ADB classes generated from the WSDL.
There are lots of web service frameworks out there...
You can change this in the page load
.
My intention is that when the page comes to the load
function, switch the links (the current link in the required one)
You can make the copy constructor private and provide no implementation:
private:
SymbolIndexer(const SymbolIndexer&);
Or in C++11, explicitly forbid it:
SymbolIndexer(const SymbolIndexer&) = delete;
I know i am answering late. But this code may useful for some one. So i am attaching it here.
Use the following java code to download the videos from YouTube.
package com.mycompany.ytd;
import java.io.File;
import java.net.URL;
import com.github.axet.vget.VGet;
/**
*
* @author Manindar
*/
public class YTD {
public static void main(String[] args) {
try {
String url = "https://www.youtube.com/watch?v=s10ARdfQUOY";
String path = "D:\\Manindar\\YTD\\";
VGet v = new VGet(new URL(url), new File(path));
v.download();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Add the below Dependency in your POM.XML file
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>vget</artifactId>
<version>1.1.33</version>
</dependency>
Hope this will be useful.
JPA is the dance, Hibernate is the dancer.
One observation: (though this can be thought of side effect)
boolean being a primitive can either say yes or no.
Boolean is an object (it can refer to either yes or no or 'don't know' i.e. null)
One more cause for this:
If the routes are overridden with the same URI (Unknowingly), it causes this error:
Eg:
Route::get('dashboard', ['uses' => 'SomeController@index', 'as' => 'my.dashboard']);
Route::get('dashboard/', ['uses' => 'SomeController@dashboard', 'as' => 'my.home_dashboard']);
In this case route 'my.dashboard' is invalidate as the both routes has same URI ('dashboard', 'dashboard/')
Solution: You should change the URI for either one
Eg:
Route::get('dashboard', ['uses' => 'SomeController@index', 'as' => 'my.dashboard']);
Route::get('home-dashboard', ['uses' => 'SomeController@dashboard', 'as' => 'my.home_dashboard']);
// See the URI changed for this 'home-dashboard'
Hope it helps some once.
I'm going to agree with shodanex, it looks like you're prematurely trying to optimize something that isn't yet problematic. Unless you know sockets are going to be a bottleneck, I'd just use them.
A lot of people who swear by named pipes find a little savings (depending on how well everything else is written), but end up with code that spends more time blocking for an IPC reply than it does doing useful work. Sure, non-blocking schemes help this, but those can be tricky. Spending years bringing old code into the modern age, I can say, the speedup is almost nil in the majority of cases I've seen.
If you really think that sockets are going to slow you down, then go out of the gate using shared memory with careful attention to how you use locks. Again, in all actuality, you might find a small speedup, but notice that you're wasting a portion of it waiting on mutual exclusion locks. I'm not going to advocate a trip to futex hell (well, not quite hell anymore in 2015, depending upon your experience).
Pound for pound, sockets are (almost) always the best way to go for user space IPC under a monolithic kernel .. and (usually) the easiest to debug and maintain.
you're using a function
error(error)
but jquery is actually looking for a function with three parameters:
error(jqXHR, textStatus, errorThrown)
you'll need to add two more parameters.
ALSO: please have a look at all the comments above that mention 'deprecated' :)
$.ajax("www.stackoverflow.com/api/whatever", {
dataType:"JSON"
data: { id=1, name='example' }
}).succes(function (result) {
// use result
}).error(function (jqXHR, textStatus, errorThrown) {
// handle error
});
There are a couple different ways I would do this:
1) Mimic Excel Tables Using with a Named Range
In your example, you named the range A10:A20
"Age". Depending on how you wanted to reference a cell in that range you could either (as @Alex P wrote) use =INDEX(Age, 5)
or if you want to reference a cell in range "Age" that is on the same row as your formula, just use:
=INDEX(Age, ROW()-ROW(Age)+1)
This mimics the relative reference features built into Excel tables but is an alternative if you don't want to use a table.
If the named range is an entire column, the formula simplifies as:
=INDEX(Age, ROW())
2) Use an Excel Table
Alternatively if you set this up as an Excel table and type "Age" as the header title of the Age column, then your formula in columns to the right of the Age column can use a formula like this:
=[@[Age]]
This would work very well -- You can use HTML5 to allow only image files to be uploaded. This is the code for uploader.htm --
<html>
<head>
<script>
function validateForm(){
var image = document.getElementById("image").value;
var name = document.getElementById("name").value;
if (image =='')
{
return false;
}
if(name =='')
{
return false;
}
else
{
return true;
}
return false;
}
</script>
</head>
<body>
<form method="post" action="upload.php" enctype="multipart/form-data">
<input type="text" name="ext" size="30"/>
<input type="text" name="name" id="name" size="30"/>
<input type="file" accept="image/*" name="image" id="image" />
<input type="submit" value='Save' onclick="return validateForm()"/>
</form>
</body>
</html>
Now the code for upload.php --
<?php
$name = $_POST['name'];
$ext = $_POST['ext'];
if (isset($_FILES['image']['name']))
{
$saveto = "$name.$ext";
move_uploaded_file($_FILES['image']['tmp_name'], $saveto);
$typeok = TRUE;
switch($_FILES['image']['type'])
{
case "image/gif": $src = imagecreatefromgif($saveto); break;
case "image/jpeg": // Both regular and progressive jpegs
case "image/pjpeg": $src = imagecreatefromjpeg($saveto); break;
case "image/png": $src = imagecreatefrompng($saveto); break;
default: $typeok = FALSE; break;
}
if ($typeok)
{
list($w, $h) = getimagesize($saveto);
$max = 100;
$tw = $w;
$th = $h;
if ($w > $h && $max < $w)
{
$th = $max / $w * $h;
$tw = $max;
}
elseif ($h > $w && $max < $h)
{
$tw = $max / $h * $w;
$th = $max;
}
elseif ($max < $w)
{
$tw = $th = $max;
}
$tmp = imagecreatetruecolor($tw, $th);
imagecopyresampled($tmp, $src, 0, 0, 0, 0, $tw, $th, $w, $h);
imageconvolution($tmp, array( // Sharpen image
array(-1, -1, -1),
array(-1, 16, -1),
array(-1, -1, -1)
), 8, 0);
imagejpeg($tmp, $saveto);
imagedestroy($tmp);
imagedestroy($src);
}
}
?>
Another problem solved by the rubber duck:
The css is right but you still have to remember that the HTML elements order matters: the div has to come before the header. http://jsfiddle.net/Fq2Na/1/
Change your HTML code to have the div before the header:
<section>
<div><button>button</button></div>
<h1>some long long long long header, a whole line, 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6</h1>
</section>
And keep your CSS to the simple div { float: right; }
.
Copy servlet-api.jar from your tomcat server lib folder.
Paste it to WEB-INF > lib
folder
Error was solved!!!
I tried with Android Studio to commit Changes and push it to master But Window Showed a popup that I have to enter Github Credentials (https://github.com). I did Signup with my Gmail account So I tried to enter my Gmail id along with its password, Obviously Git do not have my Gmail password and can't match it with what I'm providing, So I ended up canceling the push.
When I tried to sync my changes through GitHub GUI Window I encounter this error. On git status
command Git Shell suggested to push changes as
Your branch is ahead of 'origin/master' by 1 commit.
(use "git push" to publish your local commits)
I did the same as Git Shell suggested (git push
) and everything is ok now.
Note: for someone who is new to git you have to change your path to the folder where your .git file is otherwise on Every Command you enter Git Shell will show error that its not a git repository.
fatal: Not a git repository (or any of the parent directories):
For example if your Project is in D
drive in some folder you have to do something like below as you do in cmd
to change directory.
cd D:\someFolder // if your project is not deep in `D`
And if its within nested folder in D
cd D:\somefolder\someNestedFolder\nestedInNested // if your project is not deep in `D`
If someone know how to login into Github popup from windows as I did signup with google account and here are 2 fields only Github username, password Please let me know. I have resolved the issue but with waste of some time so I want to know about login too.
Today, I have used this feature, so here's my very fresh real-life example. (I have changed class and method names to generic ones so they won't distract from the actual point.)
I have a method that's meant to accept a Set
of A
objects that I originally wrote with this signature:
void myMethod(Set<A> set)
But it want to actually call it with Set
s of subclasses of A
. But this is not allowed! (The reason for that is, myMethod
could add objects to set
that are of type A
, but not of the subtype that set
's objects are declared to be at the caller's site. So this could break the type system if it were possible.)
Now here come generics to the rescue, because it works as intended if I use this method signature instead:
<T extends A> void myMethod(Set<T> set)
or shorter, if you don't need to use the actual type in the method body:
void myMethod(Set<? extends A> set)
This way, set
's type becomes a collection of objects of the actual subtype of A
, so it becomes possible to use this with subclasses without endangering the type system.
Another syntax of doing the same thing is:
rails g migration AddUserToUpload user:belongs_to
Simple variation on @erikkallen answer that shows which table the row is present in:
( SELECT 'table1' as source, * FROM table1
EXCEPT
SELECT * FROM table2)
UNION ALL
( SELECT 'table2' as source, * FROM table2
EXCEPT
SELECT * FROM table1)
If you get an error
All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists.
then it may help to add
( SELECT 'table1' as source, * FROM table1
EXCEPT
SELECT 'table1' as source, * FROM table2)
UNION ALL
( SELECT 'table2' as source, * FROM table2
EXCEPT
SELECT 'table2' as source, * FROM table1)
One more reason I found (vague as it may sound). The below did not work.
LinearLayout vertical
LinearLayout height fillparent + weight
LinearLayout height fillparent + weight
LinearLayout height fillparent + weight
EndLinearLayout
What did work was
RelativeLayout
LinearLayout vertical
LinearLayout height fillparent + weight
LinearLayout height fillparent + weight
LinearLayout height fillparent + weight
EndLinearLayout
EndRelativeLayout
It sounds vague by a root layout with Linear and weights under it did not work. And when I say "did not work", I mean, that after I viewed the graphical layout between various resolutions the screen consistency broke big time.
I think you are looking for instance_of?
. is_a?
and kind_of?
will return true for instances from derived classes.
class X < String
end
foo = X.new
foo.is_a? String # true
foo.kind_of? String # true
foo.instance_of? String # false
foo.instance_of? X # true
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 guess this is what you need. Try this .
<form action="" method="get">
<input name="search" type="text">
<input type="button" value="Search" onclick="return updateTable();">
</form>
and your javascript code is the same
function updateTable()
{
var photoViewer = document.getElementById('photoViewer');
var photo = document.getElementById('photo1').href;
var numOfPics = 5;
var columns = 3;
var rows = Math.ceil(numOfPics/columns);
var content="";
var count=0;
content = "<table class='photoViewer' id='photoViewer'>";
for (r = 0; r < rows; r++) {
content +="<tr>";
for (c = 0; c < columns; c++) {
count++;
if(count == numOfPics)break; // here is check if number of cells equal Number of Pictures to stop
content +="<td><a href='"+photo+"' id='photo1'><img class='photo' src='"+photo+"' alt='Photo'></a><p>City View</p></td>";
}
content +="</tr>";
}
content += "</table>";
photoViewer.innerHTML = content;
}
ALTER TABLE TableName
ADD NewColumnName INTEGER,
FOREIGN KEY(NewColumnName) REFERENCES [ForeignKey_TableName](Foreign_Key_Column)
An easier solution has been outlined here: Validate select box
Make the value be empty and add the required attribute
<select id="select" class="required">
<option value="">Choose an option</option>
<option value="option1">Option1</option>
<option value="option2">Option2</option>
<option value="option3">Option3</option>
</select>
You can use the following workaround for it to work with the first parameter too:
var param1 =
HttpUtility.ParseQueryString(url.Substring(
new []{0, url.IndexOf('?')}.Max()
)).Get("param1");
The shortest:
let arr = [...Array(10)];
console.log(arr);
_x000D_
Quoting Jacob Hallen:
The proper use of
__slots__
is to save space in objects. Instead of having a dynamic dict that allows adding attributes to objects at anytime, there is a static structure which does not allow additions after creation. [This use of__slots__
eliminates the overhead of one dict for every object.] While this is sometimes a useful optimization, it would be completely unnecessary if the Python interpreter was dynamic enough so that it would only require the dict when there actually were additions to the object.Unfortunately there is a side effect to slots. They change the behavior of the objects that have slots in a way that can be abused by control freaks and static typing weenies. This is bad, because the control freaks should be abusing the metaclasses and the static typing weenies should be abusing decorators, since in Python, there should be only one obvious way of doing something.
Making CPython smart enough to handle saving space without
__slots__
is a major undertaking, which is probably why it is not on the list of changes for P3k (yet).
You can do it using only the shell, no need for tr
or sed
$ str="This is just a test"
$ echo ${str// /_}
This_is_just_a_test
I have a textarea with id is #infoartist follow:
<textarea id="infoartist" ng-show="dForm" style="width: 100%;" placeholder="Tell your contacts and collectors about yourself."></textarea>
In javascript code, i'll get value of textarea and replace escaping new line (\n\r) by <br />
tag, such as:
var text = document.getElementById("infoartist").value;
text = text.replace(/\r?\n/g, '<br />');
So if you are using jquery (like me):
var text = $("#infoartist").val();
text = text.replace(/\r?\n/g, '<br />');
Hope it helped you. :-)
Do you want to get a substring of a string from start index to the last index of one of its characters? If so, you may choose one of the following Swift 2.0+ methods.
Foundation
Get a substring that includes the last index of a character:
import Foundation
let string = "www.stackoverflow.com"
if let rangeOfIndex = string.rangeOfCharacterFromSet(NSCharacterSet(charactersInString: "."), options: .BackwardsSearch) {
print(string.substringToIndex(rangeOfIndex.endIndex))
}
// prints "www.stackoverflow."
Get a substring that DOES NOT include the last index of a character:
import Foundation
let string = "www.stackoverflow.com"
if let rangeOfIndex = string.rangeOfCharacterFromSet(NSCharacterSet(charactersInString: "."), options: .BackwardsSearch) {
print(string.substringToIndex(rangeOfIndex.startIndex))
}
// prints "www.stackoverflow"
If you need to repeat those operations, extending String
can be a good solution:
import Foundation
extension String {
func substringWithLastInstanceOf(character: Character) -> String? {
if let rangeOfIndex = rangeOfCharacterFromSet(NSCharacterSet(charactersInString: String(character)), options: .BackwardsSearch) {
return self.substringToIndex(rangeOfIndex.endIndex)
}
return nil
}
func substringWithoutLastInstanceOf(character: Character) -> String? {
if let rangeOfIndex = rangeOfCharacterFromSet(NSCharacterSet(charactersInString: String(character)), options: .BackwardsSearch) {
return self.substringToIndex(rangeOfIndex.startIndex)
}
return nil
}
}
print("www.stackoverflow.com".substringWithLastInstanceOf("."))
print("www.stackoverflow.com".substringWithoutLastInstanceOf("."))
/*
prints:
Optional("www.stackoverflow.")
Optional("www.stackoverflow")
*/
Foundation
Get a substring that includes the last index of a character:
let string = "www.stackoverflow.com"
if let reverseIndex = string.characters.reverse().indexOf(".") {
print(string[string.startIndex ..< reverseIndex.base])
}
// prints "www.stackoverflow."
Get a substring that DOES NOT include the last index of a character:
let string = "www.stackoverflow.com"
if let reverseIndex = string.characters.reverse().indexOf(".") {
print(string[string.startIndex ..< reverseIndex.base.advancedBy(-1)])
}
// prints "www.stackoverflow"
If you need to repeat those operations, extending String
can be a good solution:
extension String {
func substringWithLastInstanceOf(character: Character) -> String? {
if let reverseIndex = characters.reverse().indexOf(".") {
return self[self.startIndex ..< reverseIndex.base]
}
return nil
}
func substringWithoutLastInstanceOf(character: Character) -> String? {
if let reverseIndex = characters.reverse().indexOf(".") {
return self[self.startIndex ..< reverseIndex.base.advancedBy(-1)]
}
return nil
}
}
print("www.stackoverflow.com".substringWithLastInstanceOf("."))
print("www.stackoverflow.com".substringWithoutLastInstanceOf("."))
/*
prints:
Optional("www.stackoverflow.")
Optional("www.stackoverflow")
*/
<input attr1='a' attr2='b' attr3='c'>foo</input>
getAttribute(attr1)
you get 'a'
getAttribute(attr2)
you get 'b'
getAttribute(attr3)
you get 'c'
getText()
with no parameter you can only get 'foo'
You are using Python 2 for which the input()
function tries to evaluate the expression entered. Because you enter a string, Python treats it as a name and tries to evaluate it. If there is no variable defined with that name you will get a NameError
exception.
To fix the problem, in Python 2, you can use raw_input()
. This returns the string entered by the user and does not attempt to evaluate it.
Note that if you were using Python 3, input()
behaves the same as raw_input()
does in Python 2.
In older versions you could use attr
. As of jQuery 1.6 you should use prop
instead:
$("#target :input").prop("disabled", true);
To disable all form elements inside 'target'. See :input
:
Matches all input, textarea, select and button elements.
If you only want the <input>
elements:
$("#target input").prop("disabled", true);
The error:
'int' object has no attribute '__getitem__'
means that you're attempting to apply the index operator []
on an int, not a list. So is col
not a list, even when it should be? Let's start from that.
Look here:
col = [[0 for col in range(5)] for row in range(6)]
Use a different variable name inside, looks like the list comprehension overwrites the col
variable during iteration. (Not during the iteration when you set col
, but during the following ones.)
I have overcome this problem by renaming the locked file (using Windows Explorer). I was not allowed to delete the file, but renaming the locked file works!
The terms "background page", "popup", "content script" are still confusing you; I strongly suggest a more in-depth look at the Google Chrome Extensions Documentation.
Regarding your question if content scripts or background pages are the way to go:
Content scripts: Definitely
Content scripts are the only component of an extension that has access to the web-page's DOM.
Background page / Popup: Maybe (probably max. 1 of the two)
You may need to have the content script pass the DOM content to either a background page or the popup for further processing.
Let me repeat that I strongly recommend a more careful study of the available documentation!
That said, here is a sample extension that retrieves the DOM content on StackOverflow pages and sends it to the background page, which in turn prints it in the console:
background.js:
// Regex-pattern to check URLs against.
// It matches URLs like: http[s]://[...]stackoverflow.com[...]
var urlRegex = /^https?:\/\/(?:[^./?#]+\.)?stackoverflow\.com/;
// A function to use as callback
function doStuffWithDom(domContent) {
console.log('I received the following DOM content:\n' + domContent);
}
// When the browser-action button is clicked...
chrome.browserAction.onClicked.addListener(function (tab) {
// ...check the URL of the active tab against our pattern and...
if (urlRegex.test(tab.url)) {
// ...if it matches, send a message specifying a callback too
chrome.tabs.sendMessage(tab.id, {text: 'report_back'}, doStuffWithDom);
}
});
content.js:
// Listen for messages
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
// If the received message has the expected format...
if (msg.text === 'report_back') {
// Call the specified callback, passing
// the web-page's DOM content as argument
sendResponse(document.all[0].outerHTML);
}
});
manifest.json:
{
"manifest_version": 2,
"name": "Test Extension",
"version": "0.0",
...
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"content_scripts": [{
"matches": ["*://*.stackoverflow.com/*"],
"js": ["content.js"]
}],
"browser_action": {
"default_title": "Test Extension"
},
"permissions": ["activeTab"]
}
Use regex:
result = result.replaceAll("\n.*", "");
replaceAll()
uses regex to find its target, which I have replaced with "nothing" - effectively deleting the target.
The target I've specified by the regex \n.*
means "the newline char and everything after"
Just like you do for getting something from the CNode
you also need to do for the ANode
XmlNodeList xnList = xml.SelectNodes("/Element[@*]");
foreach (XmlNode xn in xnList)
{
XmlNode anode = xn.SelectSingleNode("ANode");
if (anode!= null)
{
string id = anode["ID"].InnerText;
string date = anode["Date"].InnerText;
XmlNodeList CNodes = xn.SelectNodes("ANode/BNode/CNode");
foreach (XmlNode node in CNodes)
{
XmlNode example = node.SelectSingleNode("Example");
if (example != null)
{
string na = example["Name"].InnerText;
string no = example["NO"].InnerText;
}
}
}
}
You can use AudioStream this way as well:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;
public class AudioWizz extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L; //you like your cereal and the program likes their "serial"
static AudioWizz a;
static JButton playBuddon;
static JFrame frame;
public static void main(String arguments[]){
frame= new JFrame("AudioWizz");
frame.setSize(300,300);
frame.setVisible(true);
a= new AudioWizz();
playBuddon= new JButton("PUSH ME");
playBuddon.setBounds(10,10,80,30);
playBuddon.addActionListener(a);
frame.add(playBuddon);
frame.add(a);
}
public void actionPerformed(ActionEvent e){ //an eventListener
if (e.getSource() == playBuddon) {
try {
InputStream in = new FileInputStream("*.wav");
AudioStream sound = new AudioStream(in);
AudioPlayer.player.start(sound);
} catch(FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
If you are looking for UML sequence diagrams, try searching for UML Sequence in the search box and add them.
You can either browse through My shapes to access them. They will be available in the in the sidebar nevertheless once you search.
No, because RAND_MAX is typically expanded to MAX_INT. So adding one (apparently) puts it at MIN_INT (although it should be undefined behavior as I'm told), hence the reversal of sign.
To get what you want you will need to move the +1 outside the computation:
r = ((double) rand() / (RAND_MAX)) + 1;
My Theme plugin provide full featured customization for Eclipse 4. Try it. Visit Plugin Page
normaly is better image store in public folder (because it has write permission already that you can use when I upload images to it)
public
upload_media
photos
image.png
$image = public_path() . '/upload_media/photos/image.png'; // destination path
view PHP
<img src="<?= $image ?>">
View blade
<img src="{{ $image }}">
HTML Code
<div class="rCol">
<div id ="prv" style="height:auto; width:auto; float:left; margin-bottom: 28px; margin-left: 200px;"></div>
</div>
<div class="rCol" style="clear:both;">
<label > Upload Photo : </label>
<input type="file" id="file" name='file' onChange=" return submitForm();">
<input type="hidden" id="filecount" value='0'>
Here is Ajax Code:
function submitForm() {
var fcnt = $('#filecount').val();
var fname = $('#filename').val();
var imgclean = $('#file');
if(fcnt<=5)
{
data = new FormData();
data.append('file', $('#file')[0].files[0]);
var imgname = $('input[type=file]').val();
var size = $('#file')[0].files[0].size;
var ext = imgname.substr( (imgname.lastIndexOf('.') +1) );
if(ext=='jpg' || ext=='jpeg' || ext=='png' || ext=='gif' || ext=='PNG' || ext=='JPG' || ext=='JPEG')
{
if(size<=1000000)
{
$.ajax({
url: "<?php echo base_url() ?>/upload.php",
type: "POST",
data: data,
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
}).done(function(data) {
if(data!='FILE_SIZE_ERROR' || data!='FILE_TYPE_ERROR' )
{
fcnt = parseInt(fcnt)+1;
$('#filecount').val(fcnt);
var img = '<div class="dialog" id ="img_'+fcnt+'" ><img src="<?php echo base_url() ?>/local_cdn/'+data+'"><a href="#" id="rmv_'+fcnt+'" onclick="return removeit('+fcnt+')" class="close-classic"></a></div><input type="hidden" id="name_'+fcnt+'" value="'+data+'">';
$('#prv').append(img);
if(fname!=='')
{
fname = fname+','+data;
}else
{
fname = data;
}
$('#filename').val(fname);
imgclean.replaceWith( imgclean = imgclean.clone( true ) );
}
else
{
imgclean.replaceWith( imgclean = imgclean.clone( true ) );
alert('SORRY SIZE AND TYPE ISSUE');
}
});
return false;
}//end size
else
{
imgclean.replaceWith( imgclean = imgclean.clone( true ) );//Its for reset the value of file type
alert('Sorry File size exceeding from 1 Mb');
}
}//end FILETYPE
else
{
imgclean.replaceWith( imgclean = imgclean.clone( true ) );
alert('Sorry Only you can uplaod JPEG|JPG|PNG|GIF file type ');
}
}//end filecount
else
{ imgclean.replaceWith( imgclean = imgclean.clone( true ) );
alert('You Can not Upload more than 6 Photos');
}
}
Here is PHP code :
$filetype = array('jpeg','jpg','png','gif','PNG','JPEG','JPG');
foreach ($_FILES as $key )
{
$name =time().$key['name'];
$path='local_cdn/'.$name;
$file_ext = pathinfo($name, PATHINFO_EXTENSION);
if(in_array(strtolower($file_ext), $filetype))
{
if($key['name']<1000000)
{
@move_uploaded_file($key['tmp_name'],$path);
echo $name;
}
else
{
echo "FILE_SIZE_ERROR";
}
}
else
{
echo "FILE_TYPE_ERROR";
}// Its simple code.Its not with proper validation.
Here upload and preview part done.Now if you want to delete and remove image from page and folder both then code is here for deletion. Ajax Part:
function removeit (arg) {
var id = arg;
// GET FILE VALUE
var fname = $('#filename').val();
var fcnt = $('#filecount').val();
// GET FILE VALUE
$('#img_'+id).remove();
$('#rmv_'+id).remove();
$('#img_'+id).css('display','none');
var dname = $('#name_'+id).val();
fcnt = parseInt(fcnt)-1;
$('#filecount').val(fcnt);
var fname = fname.replace(dname, "");
var fname = fname.replace(",,", "");
$('#filename').val(fname);
$.ajax({
url: 'delete.php',
type: 'POST',
data:{'name':dname},
success:function(a){
console.log(a);
}
});
}
Here is PHP part(delete.php):
$path='local_cdn/'.$_POST['name'];
if(@unlink($path))
{
echo "Success";
}
else
{
echo "Failed";
}
In this case you could use something like this:
User::where('this', '=', 1)
->whereNotNull('created_at')
->whereNotNull('updated_at')
->where(function($query){
return $query
->whereNull('alias')
->orWhere('alias', '=', 'admin');
});
It should supply you with a query like:
SELECT * FROM `user`
WHERE `user`.`this` = 1
AND `user`.`created_at` IS NOT NULL
AND `user`.`updated_at` IS NOT NULL
AND (`alias` IS NULL OR `alias` = 'admin')
you may need to try
pip install --upgrade setuptools
you may also need to install Visual Studio 2015, and remember to choose to install Visual C++ 14.0 https://visualstudio.microsoft.com/visual-cpp-build-tools/
To change DatePicker
colors (calendar mode) at application level define below properties.
<style name="MyAppTheme" parent="Theme.AppCompat.Light">
<item name="colorAccent">#ff6d00</item>
<item name="colorControlActivated">#33691e</item>
<item name="android:selectableItemBackgroundBorderless">@color/colorPrimaryDark</item>
<item name="colorControlHighlight">#d50000</item>
</style>
See http://www.zoftino.com/android-datepicker-example for other DatePicker
custom styles
an abstract class can have member variables that needs to be initialized,so they can be initialized in the abstract class constructor and this constructor is called when derived class object is initialized.
Original definitive documentation
0
, 1
and 2
only track how many of the necessary methods to make a request you've called so far.
3
tells you that the server's response has started to come in. But when you're using the XMLHttpRequest
object from a web page there's almost nothing(*) you can do with that information, since you don't have access to the extended properties that allow you to read the partial data.
readyState 4
is the only one that holds any meaning.
(*: about the only conceivable use I can think of for checking for readyState 3
is that it signals some form of life at the server end, so you could possibly increase the amount of time you wait for a full response when you receive it.)
{ "date" : "1000000" }
in your Mongo doc seems suspect. Since it's a number, it should be { date : 1000000 }
It's probably a type mismatch. Try post.findOne({date: "1000000"}, callback)
and if that works, you have a typing issue.
I think the best way is:
data: "{'Ids':['2','2']}"
To read this values Ids[0], Ids[1].
According to the documentation of the Item
property:
Sets or returns an item for a specified key in a Dictionary object.
In your case, you don't have an item whose key is 1
so doing:
s = d.Item(i)
actually creates a new key / value pair in your dictionary, and the value is empty because you have not used the optional newItem
argument.
The Dictionary also has the Items
method which allows looping over the indices:
a = d.Items
For i = 0 To d.Count - 1
s = a(i)
Next i
You have to add at least one file to the repository before committing, e.g. .gitignore
.
I got this error because Int was int in one file. So stupid.
I faced this issue because my selector was depend on id
meanwhile I did not set id for my element
my selector
was
$("#EmployeeName")
but my HTML element
<input type="text" name="EmployeeName">
so just make sure that your selector criteria are valid
One suggestion is to use LINQ to Entity Framework only for single-record CRUD statements.
For more involved queries, searches, reporting, etc, write a stored procedure and add it to the Entity Framework model as described on MSDN.
This is the approach I've taken with a couple of my sites and it seems to be a good compromise between productivity and performance. Entity Framework will not always generate the most efficient SQL for the task at hand. And rather than spending the time to figure out why, writing a stored procedure for the more complex queries actually saves time for me. Once you're familiar with the process, it's not too much of a hassle to add stored procs to your EF model. And of course the benefit of adding it to your model is that you get all that strongly typed goodness that comes from using an ORM.
You're looking for Action<T>
, which takes a parameter.
This error is a result of the protection level of ClassB
's constructor, not ClassB
itself. Since the name of the constructor is the same as the name of the class* , the error may be interpreted incorrectly. Since you did not specify the protection level of your constructor, it is assumed to be internal
by default. Declaring the constructor public
will fix this problem:
public ClassB() { }
* One could also say that constructors have no name, only a type; this does not change the essence of the problem.
I think collapsing your borders is the wrong thing to do in this case. Collapsing them basically means that the border between two neighboring cells becomes shared. This means it's unclear as to which direction it should curve given a radius.
Instead, you can give a border radius to the two lefthand corners of the first TD and the two righthand corners of the last one. You can use first-child
and last-child
selectors as suggested by theazureshadow, but these may be poorly supported by older versions of IE. It might be easier to just define classes, such as .first-column
and .last-column
to serve this purpose.
Instead of having static methods and passing around a pointer to the class instance, you could use functionality in the new C++11 standard: std::function
and std::bind
:
#include <functional>
class EventHandler
{
public:
void addHandler(std::function<void(int)> callback)
{
cout << "Handler added..." << endl;
// Let's pretend an event just occured
callback(1);
}
};
The addHandler
method now accepts a std::function
argument, and this "function object" have no return value and takes an integer as argument.
To bind it to a specific function, you use std::bind
:
class MyClass
{
public:
MyClass();
// Note: No longer marked `static`, and only takes the actual argument
void Callback(int x);
private:
int private_x;
};
MyClass::MyClass()
{
using namespace std::placeholders; // for `_1`
private_x = 5;
handler->addHandler(std::bind(&MyClass::Callback, this, _1));
}
void MyClass::Callback(int x)
{
// No longer needs an explicit `instance` argument,
// as `this` is set up properly
cout << x + private_x << endl;
}
You need to use std::bind
when adding the handler, as you explicitly needs to specify the otherwise implicit this
pointer as an argument. If you have a free-standing function, you don't have to use std::bind
:
void freeStandingCallback(int x)
{
// ...
}
int main()
{
// ...
handler->addHandler(freeStandingCallback);
}
Having the event handler use std::function
objects, also makes it possible to use the new C++11 lambda functions:
handler->addHandler([](int x) { std::cout << "x is " << x << '\n'; });
https://github.com/cscott/jsshaper implements a translator from JavaScript 1.8 to ECMAScript 5.1, which would allow you to use 'for each' in code running on webkit or node.
This can be quite easily achieved using the ProcessStartInfo.RedirectStandardOutput property. A full sample is contained in the linked MSDN documentation; the only caveat is that you may have to redirect the standard error stream as well to see all output of your application.
Process compiler = new Process();
compiler.StartInfo.FileName = "csc.exe";
compiler.StartInfo.Arguments = "/r:System.dll /out:sample.exe stdstr.cs";
compiler.StartInfo.UseShellExecute = false;
compiler.StartInfo.RedirectStandardOutput = true;
compiler.Start();
Console.WriteLine(compiler.StandardOutput.ReadToEnd());
compiler.WaitForExit();
This is not possible.
In Python, there really isn't any such thing as a "variable". What Python really has are "names" which can have objects bound to them. It makes no difference to the object what names, if any, it might be bound to. It might be bound to dozens of different names, or none.
Consider this example:
foo = 1
bar = 1
baz = 1
Now, suppose you have the integer object with value 1, and you want to work backwards and find its name. What would you print? Three different names have that object bound to them, and all are equally valid.
In Python, a name is a way to access an object, so there is no way to work with names directly. There might be some clever way to hack the Python bytecodes or something to get the value of the name, but that is at best a parlor trick.
If you know you want print foo
to print "foo"
, you might as well just execute print "foo"
in the first place.
EDIT: I have changed the wording slightly to make this more clear. Also, here is an even better example:
foo = 1
bar = foo
baz = foo
In practice, Python reuses the same object for integers with common values like 0 or 1, so the first example should bind the same object to all three names. But this example is crystal clear: the same object is bound to foo, bar, and baz.
I don't know whether there's a better answer out there as time goes by but this is simple and it works;
input[type='email'] {
background: white url(images/mail.svg) no-repeat ;
}
input[type='email']:focus {
background-image: none;
}
Style it up to suit.
A good reference is given at : http://msdn.microsoft.com/en-us/magazine/cc163442.aspx under the section "Disabling All Foreign Keys"
Inspired from it, an approach can be made by creating a temporary table and inserting the constraints in that table, and then dropping the constraints and then reapplying them from that temporary table. Enough said here is what i am talking about
SET NOCOUNT ON
DECLARE @temptable TABLE(
Id INT PRIMARY KEY IDENTITY(1, 1),
FKConstraintName VARCHAR(255),
FKConstraintTableSchema VARCHAR(255),
FKConstraintTableName VARCHAR(255),
FKConstraintColumnName VARCHAR(255),
PKConstraintName VARCHAR(255),
PKConstraintTableSchema VARCHAR(255),
PKConstraintTableName VARCHAR(255),
PKConstraintColumnName VARCHAR(255)
)
INSERT INTO @temptable(FKConstraintName, FKConstraintTableSchema, FKConstraintTableName, FKConstraintColumnName)
SELECT
KeyColumnUsage.CONSTRAINT_NAME,
KeyColumnUsage.TABLE_SCHEMA,
KeyColumnUsage.TABLE_NAME,
KeyColumnUsage.COLUMN_NAME
FROM
INFORMATION_SCHEMA.KEY_COLUMN_USAGE KeyColumnUsage
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS TableConstraints
ON KeyColumnUsage.CONSTRAINT_NAME = TableConstraints.CONSTRAINT_NAME
WHERE
TableConstraints.CONSTRAINT_TYPE = 'FOREIGN KEY'
UPDATE @temptable SET
PKConstraintName = UNIQUE_CONSTRAINT_NAME
FROM
@temptable tt
INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS ReferentialConstraint
ON tt.FKConstraintName = ReferentialConstraint.CONSTRAINT_NAME
UPDATE @temptable SET
PKConstraintTableSchema = TABLE_SCHEMA,
PKConstraintTableName = TABLE_NAME
FROM @temptable tt
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS TableConstraints
ON tt.PKConstraintName = TableConstraints.CONSTRAINT_NAME
UPDATE @temptable SET
PKConstraintColumnName = COLUMN_NAME
FROM @temptable tt
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KeyColumnUsage
ON tt.PKConstraintName = KeyColumnUsage.CONSTRAINT_NAME
--Now to drop constraint:
SELECT
'
ALTER TABLE [' + FKConstraintTableSchema + '].[' + FKConstraintTableName + ']
DROP CONSTRAINT ' + FKConstraintName + '
GO'
FROM
@temptable
--Finally to add constraint:
SELECT
'
ALTER TABLE [' + FKConstraintTableSchema + '].[' + FKConstraintTableName + ']
ADD CONSTRAINT ' + FKConstraintName + ' FOREIGN KEY(' + FKConstraintColumnName + ') REFERENCES [' + PKConstraintTableSchema + '].[' + PKConstraintTableName + '](' + PKConstraintColumnName + ')
GO'
FROM
@temptable
GO
I tried the below code,
function executeQuery() {
$.ajax({
url: 'url/path/here',
success: function(data) {
// do something with the return value here if you like
}
});
setTimeout(executeQuery, 5000); // you could choose not to continue on failure...
}
$(document).ready(function() {
// run the first time; all subsequent calls will take care of themselves
setTimeout(executeQuery, 5000);
});
This didn't work as expected for the specified interval,the page didn't load completely and the function was been called continuously.
Its better to call setTimeout(executeQuery, 5000);
outside executeQuery()
in a separate function as below,
function executeQuery() {
$.ajax({
url: 'url/path/here',
success: function(data) {
// do something with the return value here if you like
}
});
updateCall();
}
function updateCall(){
setTimeout(function(){executeQuery()}, 5000);
}
$(document).ready(function() {
executeQuery();
});
This worked exactly as intended.
$JAVA_HOME/bin/java -version says 'Permission Denied'
If you cannot access or run code, it which be ignored if added to your path. You need to make it accessible and runnable or get a copy of your own.
Do an
ls -ld $JAVA_HOME $JAVA_HOME/bin $JAVA_HOME/bin/java
to see why you cannot access or run this program,.
You can use list comprehension on a dataframe to count frequencies of the columns as such
[my_series[c].value_counts() for c in list(my_series.select_dtypes(include=['O']).columns)]
Breakdown:
my_series.select_dtypes(include=['O'])
Selects just the categorical data
list(my_series.select_dtypes(include=['O']).columns)
Turns the columns from above into a list
[my_series[c].value_counts() for c in list(my_series.select_dtypes(include=['O']).columns)]
Iterates through the list above and applies value_counts() to each of the columns
Join like this:
ON a.userid = b.sourceid AND a.listid = b.destinationid;
You can add a reference to System.Configuration
in your project and then:
using System.Configuration;
then
string sValue = ConfigurationManager.AppSettings["BatchFile"];
with an app.config
file like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="BatchFile" value="blah.bat" />
</appSettings>
</configuration>
On CentOS EL 6 and perhaps on earlier versions there is one way to get into this same mess.
Install CentOS EL6 with a minimal installation. For example I used kickstart to install the following:
%packages
@core
acpid
bison
cmake
dhcp-common
flex
gcc
gcc-c++
git
libaio-devel
make
man
ncurses-devel
perl
ntp
ntpdate
pciutils
tar
tcpdump
wget
%end
You will find that one of the dependencies of the above list is mysql-libs
. I found that my system has a default my.cnf
in /etc
and this contains:
[mysqld]
dataddir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
When you build from the Generic Linux (Architecture Independent), Compressed TAR Archive
your default data directory is /usr/local/mysql/data
which conflicts with the /etc/my.cnf
already present which defines datadir=/var/lib/mysql
. Also the pid-file
defined in the same file does not have permissions for the mysql user/group to write to it in /var/run/mysqld
.
A quick remedy is to mv /etc/my.cnf /etc/my.cnf.old
which should get your generic source procedure working.
Of course the experience is different of you use the source RPMs.
The second div is position: static
(the default) so the z-index does not apply to it.
You need to position (set the position property to anything other than static
, you probably want relative
in this case) anything you want to give a z-index
to.
import AVFoundation
var player:AVAudioPlayer!
func Play(){
guard let path = Bundle.main.path(forResource: "KurdishSong", ofType: "mp3")else{return}
let soundURl = URL(fileURLWithPath: path)
player = try? AVAudioPlayer(contentsOf: soundURl)
player.prepareToPlay()
player.play()
//player.pause()
//player.stop()
}
If you do it with a @Html.ActionLink()
then loading the PartialView is handled as a normal request when clicking a anchor-element, i.e. load new page with the reponse of the PartialViewResult method.
If you want to load it immedialty, then you use @Html.RenderPartial("_LoadView")
or @Html.RenderAction("Load")
.
If you want to do it upon userinteraction (i.e. clicking a link) then you need to use AJAX --> @Ajax.ActionLink()
I'd use a couple of tiny images. Would look better too.
Alternatively, you can try the Character Map utility that comes with Windows or try looking here.
Another solution I've seen is to use the Wingdings font for symbols. That has a lot fo arrows.
There is no "Numeric Keypad" for iPads out of the box. When you specify one iPads display the normal keypad with the numeric part displayed. You can switch over to alpha characters, etc. If you want to display a numbers only keyboard for iPad you must implement it yourself.
See here: Number keyboard in iPad?
The only way to control the size of stack within process is start a new Thread
. But you can also control by creating a self-calling sub Java process with the -Xss
parameter.
public class TT {
private static int level = 0;
public static long fact(int n) {
level++;
return n < 2 ? n : n * fact(n - 1);
}
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(null, null, "TT", 1000000) {
@Override
public void run() {
try {
level = 0;
System.out.println(fact(1 << 15));
} catch (StackOverflowError e) {
System.err.println("true recursion level was " + level);
System.err.println("reported recursion level was "
+ e.getStackTrace().length);
}
}
};
t.start();
t.join();
try {
level = 0;
System.out.println(fact(1 << 15));
} catch (StackOverflowError e) {
System.err.println("true recursion level was " + level);
System.err.println("reported recursion level was "
+ e.getStackTrace().length);
}
}
}
As is obvious from all the other answers, there's no adequate "built-in" function. This is a safe and simple method.
String getFileExtension(File file) {
if (file == null) {
return "";
}
String name = file.getName();
int i = name.lastIndexOf('.');
String ext = i > 0 ? name.substring(i + 1) : "";
return ext;
}
As the official documentation says:
body - entity body for PATCH, POST and PUT requests. Must be a Buffer, String or ReadStream. If json is true, then body must be a JSON-serializable object.
When sending JSON you just have to put it in body of the option.
var options = {
uri: 'https://myurl.com',
method: 'POST',
json: true,
body: {'my_date' : 'json'}
}
request(options, myCallback)
Just to show it in a different format that I prefer to use for some reason: The first way returns your itemList as an System.Linq.IOrderedQueryable
using(var context = new ItemEntities())
{
var itemList = context.Items.Where(x => !x.Items && x.DeliverySelection)
.OrderByDescending(x => x.Delivery.SubmissionDate);
}
That approach is fine, but if you wanted it straight into a List Object:
var itemList = context.Items.Where(x => !x.Items && x.DeliverySelection)
.OrderByDescending(x => x.Delivery.SubmissionDate).ToList();
All you have to do is append a .ToList() call to the end of the Query.
Something to note, off the top of my head I can't recall if the !(not) expression is acceptable in the Where() call.
.NET has a built functionality for compressing files in the System.IO.Compression namespace. Using this you do not have to take an extra library as a dependency. This functionality is available from .NET 2.0.
Here is the way to do the compressing from the MSDN page I linked:
public static void Compress(FileInfo fi)
{
// Get the stream of the source file.
using (FileStream inFile = fi.OpenRead())
{
// Prevent compressing hidden and already compressed files.
if ((File.GetAttributes(fi.FullName) & FileAttributes.Hidden)
!= FileAttributes.Hidden & fi.Extension != ".gz")
{
// Create the compressed file.
using (FileStream outFile = File.Create(fi.FullName + ".gz"))
{
using (GZipStream Compress = new GZipStream(outFile,
CompressionMode.Compress))
{
// Copy the source file into the compression stream.
byte[] buffer = new byte[4096];
int numRead;
while ((numRead = inFile.Read(buffer, 0, buffer.Length)) != 0)
{
Compress.Write(buffer, 0, numRead);
}
Console.WriteLine("Compressed {0} from {1} to {2} bytes.",
fi.Name, fi.Length.ToString(), outFile.Length.ToString());
}
}
}
}
You could declare your parameters in the file, like param:
[string]$para1
[string]$param2
And then call the PowerShell file like so .\temp.ps1 para1 para2....para10
, etc.
You have two " "
before the =
let imageToDeleteParameters = imagesToDelete.map { ["id": $0.id, "url": $0.url.absoluteString, "_destroy": true] }
The title attribute also works well with other html elements, for example a link...
<a title="hover text" ng-href="{{getUrl()}}"> download link
</a>
You separate the values you want to return by commas:
def get_name():
# you code
return first_name, last_name
The commas indicate it's a tuple, so you could wrap your values by parentheses:
return (first_name, last_name)
Then when you call the function you a) save all values to one variable as a tuple, or b) separate your variable names by commas
name = get_name() # this is a tuple
first_name, last_name = get_name()
(first_name, last_name) = get_name() # You can put parentheses, but I find it ugly
Here is what you are looking for:
Service hangs up at WaitForExit after calling batch file
It's about a question as to why a service can't execute a file, but it shows all the code necessary to do so.
I encountered a similar issue recently. In my case the versions of cffi
and cryptography
written in requirements.txt weren't compatible (cffi==1.8.9 and cryptography==1.9). I solved updating cffi
with the last available version.
I have to admit that all the "advantages" of MVC have never made my work easier, faster, or better. It just makes the whole codeing experience more abstract and time consuming. Maintenance is a nightmare when trying to debug someone elses conception of what separation means. Don't know how many of you people have ever tried to update a FLEX site that used Cairngorm as the MVC model but what should take 30 seconds to update can often take over 2 hours (hunting/tracing/debugging just to find a single event). MVC was and still is, for me, an "advantage" that you can stuff.
If you just do eval $cmd
when we do cmd="ls -l"
(interactively and in a script) we get the desired result. In your case, you have a pipe with a grep without a pattern, so the grep part will fail with an error message. Just $cmd
will generate a "command not found" (or some such) message.
So try use eval and use a finished command, not one that generates an error message.
The current HTML5 draft specification does not specify which video formats browsers should support in the video tag. User agents are free to support any video formats they feel are appropriate.
File file = context.getFilesDir();
file.mkdir();
String[] array = filePath.split("/");
for(int t = 0; t < array.length - 1; t++) {
file = new File(file, array[t]);
file.mkdir();
}
File f = new File(file,array[array.length- 1]);
RandomAccessFileOutputStream rvalue =
new RandomAccessFileOutputStream(f, append);
Well, you could go with the built-in libraries such as URL and URLConnection, but they don't give very much control.
Personally I'd go with the Apache HTTPClient library.
Edit: HTTPClient has been set to end of life by Apache. The replacement is: HTTP Components
For arbitrary SQL, use jOOQ. jOOQ currently supports SELECT
, INSERT
, UPDATE
, DELETE
, TRUNCATE
, and MERGE
. You can create SQL like this:
String sql1 = DSL.using(SQLDialect.MYSQL)
.select(A, B, C)
.from(MY_TABLE)
.where(A.equal(5))
.and(B.greaterThan(8))
.getSQL();
String sql2 = DSL.using(SQLDialect.MYSQL)
.insertInto(MY_TABLE)
.values(A, 1)
.values(B, 2)
.getSQL();
String sql3 = DSL.using(SQLDialect.MYSQL)
.update(MY_TABLE)
.set(A, 1)
.set(B, 2)
.where(C.greaterThan(5))
.getSQL();
Instead of obtaining the SQL string, you could also just execute it, using jOOQ. See
(Disclaimer: I work for the company behind jOOQ)
this seems to solve the problem:
<!DOCTYPE html>
<style type="text/css">
#someContainer br { display:none }
#someContainer br + a:before { content:"|"; color: transparent; letter-spacing:-100px; border-left: 1px dashed black; margin:0 5px; }
</style>
<div id="someContainer"><a>link</a><br /><a>link</a><br /><a>link</a></div>
If I am not mistaken, it will be onunload event.
"Occurs when the application is about to be unloaded." - MSDN
If you want to compare to a string literal you need to put it in (single) quotes:
<xsl:if test="Count != 'N/A'">
And if you want to access more than one column at a time you could do:
>>> test = np.arange(9).reshape((3,3))
>>> test
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
>>> test[:,[0,2]]
array([[0, 2],
[3, 5],
[6, 8]])
For those who want an elegant, bash version-independent solution (in fact should work in other modern shells) and those who love to use one-liners for quick tasks. Here we go!
ls | grep . && echo 'files found' || echo 'files not found'
(note as one of the comments mentioned, ls -al
and in fact, just -l
and -a
will all return something, so in my answer I use simple ls
You may use bellow like.
If you want use json array:
Create A class named Model like bellow
public class Model {
private String id = "";
private String name = "";
//getter sertter here
}
In sevlet getMethod you can use like bellow
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//begin get data from databse or other source
List<Model> list = new ArrayList<>();
Model model = new Model();
model.setId("101");
model.setName("Enamul Haque");
list.add(model);
Model model1 = new Model();
model1.setId("102");
model1.setName("Md Mohsin");
list.add(model1);
//End get data from databse or other source
try {
JSONArray ja = new JSONArray();
for (Model m : list) {
JSONObject jSONObject = new JSONObject();
jSONObject.put("id", m.getId());
jSONObject.put("name", m.getName());
ja.add(jSONObject);
}
System.out.println(" json ja = " + ja);
response.addHeader("Access-Control-Allow-Origin", "*");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().print(ja.toString());
response.getWriter().flush();
} catch (Exception e) {
e.printStackTrace();
}
}
Output:
[{"name":"Enamul Haque","id":"101"},{"name":"Md Mohsin","id":"102"}]
I you want json Object just use like:
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
JSONObject json = new JSONObject();
json.put("id", "108");
json.put("name", "Enamul Haque");
System.out.println(" json JSONObject= " + json);
response.addHeader("Access-Control-Allow-Origin", "*");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().print(json.toString());
response.getWriter().flush();
// System.out.println("Response Completed... ");
} catch (Exception e) {
e.printStackTrace();
}
}
Above function Output:
{"name":"Enamul Haque","id":"108"}
Full source is given to GitHub: https://github.com/enamul95/ServeletJson.git
If you need to check whether the elements of one vector are in another, the best solution is ismember
as mentioned in the other answers.
ismember([15 17],primes(20))
However when you are dealing with floating point numbers, or just want to have close matches (+- 1000 is also possible), the best solution I found is the fairly efficient File Exchange Submission: ismemberf
It gives a very practical example:
[tf, loc]=ismember(0.3, 0:0.1:1) % returns false
[tf, loc]=ismemberf(0.3, 0:0.1:1) % returns true
Though the default tolerance should normally be sufficient, it gives you more flexibility
ismemberf(9.99, 0:10:100) % returns false
ismemberf(9.99, 0:10:100,'tol',0.05) % returns true
The tuple
function takes only one argument which has to be an iterable
tuple([iterable])
Return a tuple whose items are the same and in the same order as iterable‘s items.
Try making 3,4
an iterable by either using [3,4]
(a list) or (3,4)
(a tuple)
For example
a_list.append(tuple((3, 4)))
will work
You could use this old fashioned one as well...
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
DECLARE @iCount int, @iMax int, @DatabaseName varchar(200), @SQL varchar (8000)
Select NAME, DBID, crdate, filename, version
INTO #TEMP
from MAster..SYSDatabASES
SELECT @iCount = Count(DBID) FROM #TEMP
Select @SQL='Create Table ##iFile1 ( DBName varchar( 200) NULL, Fileid INT, FileGroup int, TotalExtents INT , USedExtents INT ,
Name varchar(100), vFile varchar (300), AllocatedSpace int NUll, UsedSpace int Null, PercentageFree int Null ) '+ char(10)
exec (@SQL)
Create Table ##iTotals ( ServerName varchar(100), DBName varchar( 200) NULL, FileType varchar(10),Fileid INT, FileGroup int, TotalExtents INT , USedExtents INT ,
Name varchar(100), vFile varchar (300), AllocatedSpace int NUll, UsedSpace int Null, PercentageFree int Null )
WHILE @iCount>0
BEGIN
SELECT @iMax =Max(dbid) FROM #TEMP
Select @DatabaseName = Name FROM #TEMP where dbid =@iMax
SELECT @SQL = 'INSERT INTO ##iFile1(Fileid , FileGroup , TotalExtents , USedExtents , Name , vFile)
EXEC (''USE [' + @DatabaseName + '] DBCC showfilestats'') ' + char(10)
Print (@SQL)
EXEC (@SQL)
SELECT @SQL = 'UPDATE ##iFile1 SET DBName ='''+ @DatabaseName +''' WHERE DBName IS NULL'
EXEC (@SQL)
DELETE FROM #TEMP WHERE dbid =@iMax
Select @iCount =@iCount -1
END
UPDATE ##iFile1
SET AllocatedSpace = (TotalExtents * 64.0 / 1024.0 ), UsedSpace =(USedExtents * 64.0 / 1024.0 )
UPDATE ##iFile1
SET PercentageFree = 100-Convert(float,UsedSpace)/Convert(float,AllocatedSpace )* 100
WHERE USEDSPACE>0
CREATE TABLE #logspace (
DBName varchar( 100),
LogSize float,
PrcntUsed float,
status int
)
INSERT INTO #logspace
EXEC ('DBCC sqlperf( logspace)')
INSERT INTO ##iTotals(ServerName, DBName, FileType,Name, vFile,PercentageFree,AllocatedSpace)
select @@ServerName ,DBNAME, 'Data' as FileType,Name, vFile, PercentageFree , AllocatedSpace
from ##iFile1
UNION
select @@ServerName ,DBNAME, 'Log' as FileType ,DBName,'' as vFile ,PrcntUsed , LogSize
from #logspace
Select * from ##iTotals
select ServerName ,DBNAME, FileType, Sum( AllocatedSpace) as AllocatedSpaceMB
from ##iTotals
Group By ServerName ,DBNAME, FileType
Order By ServerName ,DBNAME, FileType
select ServerName ,DBNAME, Sum( AllocatedSpace) as AllocatedSpaceMB
from ##iTotals
Group By ServerName ,DBNAME
Order By ServerName ,DBNAME
drop table ##iFile1
drop table #logspace
drop table #TEMP
drop table ##iTotals
Try returning the dataset from your stored procedure to your datatable in C# or VB.Net. Then the large amount of data in your datatable can be copied to your destination table using a Bulk Copy. I have used BulkCopy for loading large datatables with thousands of rows, into Sql tables with great success in terms of performance.
You may want to experiment with BulkCopy in your C# or VB.Net code.
1st way is to use props
<Row id = "someRandomID">
Wherein, in the Definition, you may just go
const Row = props => {
div id = {props.id}
}
The same could be done with class, replacing id with className in the above example.
You might as well use react-html-id
, that is an npm package.
This is an npm package that allows you to use unique html IDs for components without any dependencies on other libraries.
Ref: react-html-id
Peace.
How you test depends on the Property's DataType:
| Type | Test | Test2 | Numeric (Long, Integer, Double etc.) | If obj.Property = 0 Then | | Boolen (True/False) | If Not obj.Property Then | If obj.Property = False Then | Object | If obj.Property Is Nothing Then | | String | If obj.Property = "" Then | If LenB(obj.Property) = 0 Then | Variant | If obj.Property = Empty Then |
You can tell the DataType by pressing F2 to launch the Object Browser and looking up the Object. Another way would be to just use the TypeName function:MsgBox TypeName(obj.Property)
Bootstrap 4 (^beta) has changed the classes for responsive hiding/showing elements. See this link for correct classes to use: http://getbootstrap.com/docs/4.0/utilities/display/#hiding-elements
You can set the value in the HTML and then init datepicker to start/highlight the actual date
<input name="datefrom" type="text" class="datepicker" value="20-1-2011">
<input name="dateto" type="text" class="datepicker" value="01-01-2012">
<input name="dateto2" type="text" class="datepicker" >
$(".datepicker").each(function() {
$(this).datepicker('setDate', $(this).val());
});
The above even works with danish date formats
I arrived to this question looking for the same but for Chromium (actually I'm using https://ungoogled-software.github.io). So in case anyone else is looking for the same:
Handling of extension MIME type requests
Always prompt for install
You're looking for the document.documentElement.scrollTop
property.
It worked for me this way, it's the best I've found. It is for a max length of 200 characters
editObservations.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (editObservations.getText().length() >= 201){
String str = editObservations.getText().toString().substring(0, 200);
editObservations.setText(str);
editObservations.setSelection(str.length());
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
In the iframe: So that means you have to add some code in the iframe page. Simply add this script to your code IN THE IFRAME:
<body onload="parent.alertsize(document.body.scrollHeight);">
In the holding page: In the page holding the iframe (in my case with ID="myiframe") add a small javascript:
<script>
function alertsize(pixels){
pixels+=32;
document.getElementById('myiframe').style.height=pixels+"px";
}
</script>
What happens now is that when the iframe is loaded it triggers a javascript in the parent window, which in this case is the page holding the iframe.
To that JavaScript function it sends how many pixels its (iframe) height is.
The parent window takes the number, adds 32 to it to avoid scrollbars, and sets the iframe height to the new number.
That's it, nothing else is needed.
But if you like to know some more small tricks keep on reading...
DYNAMIC HEIGHT IN THE IFRAME? If you like me like to toggle content the iframe height will change (without the page reloading and triggering the onload). I usually add a very simple toggle script I found online:
<script>
function toggle(obj) {
var el = document.getElementById(obj);
if ( el.style.display != 'block' ) el.style.display = 'block';
else el.style.display = 'none';
}
</script>
to that script just add:
<script>
function toggle(obj) {
var el = document.getElementById(obj);
if ( el.style.display != 'block' ) el.style.display = 'block';
else el.style.display = 'none';
parent.alertsize(document.body.scrollHeight); // ADD THIS LINE!
}
</script>
How you use the above script is easy:
<a href="javascript:toggle('moreheight')">toggle height?</a><br />
<div style="display:none;" id="moreheight">
more height!<br />
more height!<br />
more height!<br />
</div>
For those that like to just cut and paste and go from there here is the two pages. In my case I had them in the same folder, but it should work cross domain too (I think...)
Complete holding page code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>THE IFRAME HOLDER</title>
<script>
function alertsize(pixels){
pixels+=32;
document.getElementById('myiframe').style.height=pixels+"px";
}
</script>
</head>
<body style="background:silver;">
<iframe src='theiframe.htm' style='width:458px;background:white;' frameborder='0' id="myiframe" scrolling="auto"></iframe>
</body>
</html>
Complete iframe code: (this iframe named "theiframe.htm")
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>IFRAME CONTENT</title>
<script>
function toggle(obj) {
var el = document.getElementById(obj);
if ( el.style.display != 'block' ) el.style.display = 'block';
else el.style.display = 'none';
parent.alertsize(document.body.scrollHeight);
}
</script>
</head>
<body onload="parent.alertsize(document.body.scrollHeight);">
<a href="javascript:toggle('moreheight')">toggle height?</a><br />
<div style="display:none;" id="moreheight">
more height!<br />
more height!<br />
more height!<br />
</div>
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
THE END
</body>
</html>
Why is $observe different than $watch?
The watchExpression is evaluated and compared to the previous value each digest() cycle, if there's a change in the watchExpression value, the watch function is called.
$observe is specific to watching for interpolated values. If a directive's attribute value is interpolated, eg dir-attr="{{ scopeVar }}"
, the observe function will only be called when the interpolated value is set (and therefore when $digest has already determined updates need to be made). Basically there's already a watcher for the interpolation, and the $observe function piggybacks off that.
See $observe & $set in compile.js
Had same issue with Android Studio 3.3 Canary 13.
I was able to solve it by following these steps:
When you complete these steps the module will be copied into your project again, AS will start syncing Gradle again and that succeeds without errors :-) Check your GIT status and you will see as soon as you add your module directory to GIT again that nothing has changed to your working directory. So it's purely an issue with AS that gets somehow out-of-sync...
Based my solution on this comment: https://issuetracker.google.com/issues/37008041#comment3
I was able to login using ec2-user
ssh -i [full path to keypair file] ec2-user@[EC2 instance hostname or IP address]
You need to use the Graphics
class in order to write on the bitmap.
Specifically, one of the DrawString
methods.
Bitmap a = new Bitmap(@"path\picture.bmp");
using(Graphics g = Graphics.FromImage(a))
{
g.DrawString(....); // requires font, brush etc
}
pictuteBox1.Image = a;
Easy way ,but you need bootstrap
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-envelope"></i></span> <!-- icon envelope "class="fa fa-envelope""-->
</div>
<input type="email" id="senha_nova" placeholder="Email">
</div><!-- input-group -->
you should try:
request.url
It suppose to work always, even on localhost (just did it).
CREATE VIEW AS
SELECT e1.emp_Id EmployeeId, e1.emp_name EmployeeName,
e1.emp_mgr_id ManagerId, e2.emp_name AS ManagerName
FROM tblEmployeeDetails e1
JOIN tblEmployeeDetails e2
ON e1.emp_mgr_id = e2.emp_id
EDIT: Left Join will work if emp_mgr_id is null.
CREATE VIEW AS
SELECT e1.emp_Id EmployeeId, e1.emp_name EmployeeName,
e1.emp_mgr_id ManagerId, e2.emp_name AS ManagerName
FROM tblEmployeeDetails e1
LEFT JOIN tblEmployeeDetails e2
ON e1.emp_mgr_id = e2.emp_id
I found this answer here and I'm using it like this.
Code from my Library:
$.fn.customContextMenu = function(callBack){
$(this).each(function(){
$(this).bind("contextmenu",function(e){
e.preventDefault();
callBack();
});
});
}
Code from my page's script:
$("#newmagazine").customContextMenu(function(){
alert("some code");
});
In case, you want to rename _id in same collection (for instance, if you want to prefix some _ids):
db.someCollection.find().snapshot().forEach(function(doc) {
if (doc._id.indexOf("2019:") != 0) {
print("Processing: " + doc._id);
var oldDocId = doc._id;
doc._id = "2019:" + doc._id;
db.someCollection.insert(doc);
db.someCollection.remove({_id: oldDocId});
}
});
if (doc._id.indexOf("2019:") != 0) {... needed to prevent infinite loop, since forEach picks the inserted docs, even throught .snapshot() method used.
You have 2 options for this error:
upload_max_filesize = 9M; post_max_size = 9M;
API 21 has view.setElevation(float)
build-in
Use ViewCompat.setElevation(view, float);
for backward compatibility
More methods ViewCompat.setZ(v, pixels)
and ViewCompat.setTranslationZ(v, pixels)
Another way collect buttons or view array and use addView
to add to RelativeLayout
Mad a similar error, easy to fix:
TypeError Traceback (most recent call last) <ipython-input-2-1eb12bfdc7db> in <module>
3 mylist = [10,20,30] ----> 4 arr = np.array[(10,20,30)] 5 d = {'a':10, 'b':20, 'c':30} TypeError: 'builtin_function_or_method' object is not subscriptable
but I should have written it as:
arr = np.array([10,20,30])
Very fixable, rookie/dumb mistake.
For my case, I deleted the mappedBy and joined tables like this:
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name = "user_group", joinColumns = {
@JoinColumn(name = "user", referencedColumnName = "user_id")
}, inverseJoinColumns = {
@JoinColumn(name = "group", referencedColumnName = "group_id")
})
private List<User> users;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JsonIgnore
private List<Group> groups;
Alternatively, if you are using phpMyAdmin
, you can take a look at the sum of the table sizes in the footer of your database structure
tab. The actual database size may be slightly over this size, however it appears to be consistent with the table_schema
method mentioned above.
Screen-shot :
No need of row number functions if field ID is unique.
SELECT TOP 1 *
FROM (
SELECT TOP 2 *
FROM yourTable
ORDER BY ID
) z
ORDER BY ID DESC
<div class="row-2">
<ul>
<li><a href="index.html" class="active"><p style="margin-top: 10px;">Buy</p></a></li>
</ul>
Play with it
ERR_CACHE_MISS
error solutionyou just need add one line code <uses-permission android:name="android.permission.INTERNET"/>
in your app/src/main/AndroidManifest.xml
file as below screenshots shows.
data1.reset_index(inplace=True)
If it's just for display purposes, you can render the text as upper or lower case in pure CSS, without any Javascript using the text-transform
property:
.myclass {
text-transform: lowercase;
}
See https://developer.mozilla.org/en/CSS/text-transform for more info.
However, note that this doesn't actually change the value to lower case; it just displays it that way. This means that if you examine the contents of the element (ie using Javascript), it will still be in its original format.
My mac was connected to a 2.5GHZ network, I had to enable my wifi to 5GHz. And the problem disappeared.
You can use <CTRL-V><Tab>
in "insert mode". In insert mode, <CTRL-V>
inserts a literal copy of your next character.
If you need to do this often, @Dee`Kej suggested (in the comments) setting Shift+Tab to insert a real tab with this mapping:
:inoremap <S-Tab> <C-V><Tab>
Also, as noted by @feedbackloop, on Windows you may need to press <CTRL-Q>
rather than <CTRL-V>
.
You can also get this error if you fail to include .htaccess or have a problem in it. The file should be something like this
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
That's my solution
<div class="main" style="width: 100%;">
<div class="container">
<div class="sizing"></div>
<div class="content"></div>
</div>
</div>
.main {
width: 100%;
}
.container {
width: 30%;
float: right;
position: relative;
}
.sizing {
width: 100%;
padding-bottom: 50%;
visibility: hidden;
}
.content {
width: 100%;
height: 100%;
background-color: red;
position: absolute;
margin-top: -50%;
}
If you're running Windows 10 Creators Update (1703) and are comfortable navigating around a Unix terminal, you could potentially achieve this using the native Feature Bash on Ubuntu on Windows (aka Bash/WSL)
This was originally introduced on the launch of Build 2016 but many additions and bug fixes were addressed at the Creators update but please be warned this is still in Beta.
To enable simply navigate to Control Panel\All Control Panel Items\Programs and Features\Turn Windows features on or off
Then select the Windows Subsystem for Linux (Beta) as below Bash on Windows Feature