My solution is in the DataContext instance (or ViewModel if using MVVM). I add a property that returns true if the Not Null condition I want is met.
Public ReadOnly Property IsSomeFieldNull() As Boolean
Get
Return If(SomeField is Null, True, False)
End Get
End Property
and bind the DataTrigger to the above property. Note: In VB.NET be sure to use the operator If and NOT the IIf function, which doesn't work with Null objects. Then the XAML is:
<DataTrigger Binding="{Binding IsSomeFieldNull}" Value="False">
<Setter Property="TextBlock.Text" Value="It's NOT NULL Baby!" />
</DataTrigger>
To elaborate on @serine's answer and illustrate working with non-trivial multi-valued condition: I had a need to show a "dim-out" overlay on an item for the boolean condition NOT a AND (b OR NOT c)
.
For background, this is a "Multiple Choice" question. If the user picks a wrong answer it becomes disabled (dimmed out and cannot be selected again). An automated agent has the ability to focus on any particular choice to give an explanation (border highlighted). When the agent focuses on an item, it should not be dimmed out even if it is disabled. All items that are not in focused are marked de-focused, and should be dimmed out.
The logic for dimming is thus:
NOT IsFocused AND (IsDefocused OR NOT Enabled)
To implement this logic, I made a generic IMultiValueConverter
named (awkwardly) to match my logic
// 'P' represents a parenthesis
// ! a && ( b || ! c )
class NOT_a_AND_P_b_OR_NOT_c_P : IMultiValueConverter
{
// redacted [...] for brevity
public object Convert(object[] values, ...)
{
bool a = System.Convert.ToBoolean(values[0]);
bool b = System.Convert.ToBoolean(values[1]);
bool c = System.Convert.ToBoolean(values[2]);
return !a && (b || !c);
}
...
}
In the XAML I use this in a MultiDataTrigger
in a <Style><Style.Triggers>
resource
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<!-- when the equation is TRUE ... -->
<Condition Value="True">
<Condition.Binding>
<MultiBinding Converter="{StaticResource NOT_a_AND_P_b_OR_NOT_c_P}">
<!-- NOT IsFocus AND ( IsDefocused OR NOT Enabled ) -->
<Binding Path="IsFocus"/>
<Binding Path="IsDefocused" />
<Binding Path="Enabled" />
</MultiBinding>
</Condition.Binding>
</Condition>
</MultiDataTrigger.Conditions>
<MultiDataTrigger.Setters>
<!-- ... show the 'dim-out' overlay -->
<Setter Property="Visibility" Value="Visible" />
</MultiDataTrigger.Setters>
</MultiDataTrigger>
And for completeness sake, my converter is defined in a ResourceDictionary
<ResourceDictionary xmlns:conv="clr-namespace:My.Converters" ...>
<conv:NOT_a_AND_P_b_OR_NOT_c_P x:Key="NOT_a_AND_P_b_OR_NOT_c_P" />
</ResourceDictionary>
I've tried doing the request you need using an iframe to show the result for latitude, longitude, and zoom needed:
<iframe
width="300"
height="170"
frameborder="0"
scrolling="no"
marginheight="0"
marginwidth="0"
src="https://maps.google.com/maps?q='+YOUR_LAT+','+YOUR_LON+'&hl=es&z=14&output=embed"
>
</iframe>
<br />
<small>
<a
href="https://maps.google.com/maps?q='+data.lat+','+data.lon+'&hl=es;z=14&output=embed"
style="color:#0000FF;text-align:left"
target="_blank"
>
See map bigger
</a>
</small>
There are some different way to do that
sass --watch --style=compressed main.scss main.css
or
sass --watch a.scss:a.css --style compressed
or
By Using visual studio code extension live sass compiler
I got this error because, on my system at least, if extension_dir
in php.ini is set to a relative path, it is taken as being relative to the root Apache directory, so to get it to point to the correct directory I had to use an absolute path: "C:\Program Files (x86)\PHP\ext"
. (This was PHP 5.5.31 and Apache 2.4.23 on Windows 10; setting extension_dir
to ext
worked just fine with the same setup on Windows 7. I first got it to work by putting an ext directory in the Apache folder with the necessary dlls, then figured out what was happening.)
It was also necessary to set the PATH correctly or make sure the dlls mentioned above (libeay32.dll, libssh2.dll, and ssleay32.dll) are in Apache's bin directory (or most likely any of the places other answers mention). The fact that I got the same error message for Apache not being able to find lib_curl.dll as for it not being able to find libssh2.dll did not make things any easier to figure out.
The res.render stuff will throw an error if you're not using a view engine.
If you just want to serve json replace the res.render('error', { error: err });
lines in your code with:
res.json({ error: err })
PS: People usually also have message in the returned object:
res.status(err.status || 500);
res.json({
message: err.message,
error: err
});
As BalausC mentioned in a comment, you are probably looking for CSS (Cascading Style Sheets) not HTML attributes.
To position an element, a <table>
in your case you want to use either padding or margins.
the difference between margins and paddings can be seen as the "box model":
Image from HTML Dog article on margins and padding http://www.htmldog.com/guides/cssbeginner/margins/.
I highly recommend the article above if you need to learn how to use CSS.
To move the table down and right I would use margins like so:
table{
margin:25px 0 0 25px;
}
This is in shorthand so the margins are as follows:
margin: top right bottom left;
Or you can use an arrow function to define it:
$(document).ready(() => {
$('#bfCaptchaEntry').click(()=>{
});
});
For better browser support:
$(document).ready(function() {
$('#bfCaptchaEntry').click(function (){
});
});
This looks like a missing SPN issue. The website you had pointed to has
principal="webserver/[email protected]"
This is the principal for which the ticket would be obtained. Did you change this to a value relative to your AD domain?
You could use the command line kerberos tools to test if you have the SPN defined:
[root@gen-cs218 bin]# kinit Administrator
[email protected]'s Password:
[root@gen-cs218 bin]# kgetcred host/[email protected]
[root@gen-cs218 bin]# klist
Credentials cache: FILE:/tmp/krb5cc_0
Principal: [email protected]
Issued Expires Principal <br>
Dec 15 11:42:34 2012 Dec 15 21:42:34 2012 krbtgt/[email protected]
Dec 15 11:42:48 2012 Dec 15 21:42:34 2012 host/[email protected]
Hostname based SPNs are pre-defined. If you want to use a SPN that is not pre-defined you will have to explicitly define it in AD using the setspn.exe tool and associate it with either a computer or an user account, for example:
c:\> setspn.exe -A "webserver/bully@MYDOMAIN" myuser
You can check which account a SPN is associated with by using the command below. This will not show pre-defined SPNs.
c:\> setspn.exe -L "webserver/bully@MYDOMAIN"
If it is a normal then the port number is always 80 and may be written as http://www.somewhere.com:80 Though you don't need to specify it as :80 is the default of every web browser.
If the site chose to use something else then they are intending to hide from anything not sent by a "friendly" or linked to. Those ones usually show with https and their port number is unknown and decided by their admin.
If you choose to runn a port scanner trying every number nn from say 10000 to 30000 in https://something.somewhere.com:nn Then your isp or their antivirus will probably notice and disconnect you.
Accepted answer is certainly a good solution, but here is the way I went about generating a CSV and serving it from a view.
Thought it was worth while putting this here as it took me a little bit of fiddling to get all the desirable behaviour (overwrite existing file, storing to the right spot, not creating duplicate files etc).
Django 1.4.1
Python 2.7.3
#Model
class MonthEnd(models.Model):
report = models.FileField(db_index=True, upload_to='not_used')
import csv
from os.path import join
#build and store the file
def write_csv():
path = join(settings.MEDIA_ROOT, 'files', 'month_end', 'report.csv')
f = open(path, "w+b")
#wipe the existing content
f.truncate()
csv_writer = csv.writer(f)
csv_writer.writerow(('col1'))
for num in range(3):
csv_writer.writerow((num, ))
month_end_file = MonthEnd()
month_end_file.report.name = path
month_end_file.save()
from my_app.models import MonthEnd
#serve it up as a download
def get_report(request):
month_end = MonthEnd.objects.get(file_criteria=criteria)
response = HttpResponse(month_end.report, content_type='text/plain')
response['Content-Disposition'] = 'attachment; filename=report.csv'
return response
var y_axis_name=[];
for(var point in jsonData[0].data)
{
y_axis_name.push(point);
}
y_axis_name is having all the key name
try on jsfiddle
You can use the SimpleDateFormat class:
SimpleDateFormat s = new SimpleDateFormat("ddMMyyyyhhmmss");
String format = s.format(new Date());
Sequences have a method index(value)
which returns index of first occurrence - in your case this would be verts.index(value)
.
You can run it on verts[::-1]
to find out the last index. Here, this would be len(verts) - 1 - verts[::-1].index(value)
The authority, as listed in android:authorities
must be unique. Quoting the documentation for this attribute:
To avoid conflicts, authority names should use a Java-style naming convention (such as com.example.provider.cartoonprovider). Typically, it's the name of the ContentProvider subclass that implements the provider
You are looking for the cp
command. You need to change directories so that you are outside of the directory you are trying to copy.
If the directory you're copying is called dir1
and you want to copy it to your /home/Pictures
folder:
cp -r dir1/ ~/Pictures/
Linux is case-sensitive and also needs the /
after each directory to know that it isn't a file. ~
is a special character in the terminal that automatically evaluates to the current user's home directory. If you need to know what directory you are in, use the command pwd
.
When you don't know how to use a Linux command, there is a manual page that you can refer to by typing:
man [insert command here]
at a terminal prompt.
Also, to auto complete long file paths when typing in the terminal, you can hit Tab after you've started typing the path and you will either be presented with choices, or it will insert the remaining part of the path.
For just plotting a vector, you should use the following command:
text(your.vector, labels=your.labels, cex= labels.size, pos=labels.position)
You can create a very simplistic multi-dictionary, which automates to process of inserting values like this:
public class MultiDictionary<TKey, TValue> : Dictionary<TKey, List<TValue>>
{
public void Add(TKey key, TValue value)
{
if (TryGetValue(key, out List<TValue> valueList)) {
valueList.Add(value);
} else {
Add(key, new List<TValue> { value });
}
}
}
This creates an overloaded version of the Add
method. The original one allows you to insert a list of items for a key, if no entry for this entry exists yet. This version allows you to insert a single item in any case.
If you would like to ignore case you could use the following:
String s = "yip";
String best = "yodel";
int compare = s.compareToIgnoreCase(best);
if(compare < 0){
//-1, --> s is less than best. ( s comes alphabetically first)
}
else if(compare > 0 ){
// best comes alphabetically first.
}
else{
// strings are equal.
}
In python generally “with” statement is used to open a file, process the data present in the file, and also to close the file without calling a close() method. “with” statement makes the exception handling simpler by providing cleanup activities.
General form of with:
with open(“file name”, “mode”) as file-var:
processing statements
note: no need to close the file by calling close() upon file-var.close()
Use IFERROR(value, value_if_error)
Not every jar file is executable.
Now, you need to import the classes, which are there under the jar, in your java file. For example,
import org.xml.sax.SAXException;
If you are working on an IDE, then you should refer its documentation. Or at least specify which one you are using here in this thread. It would definitely enable us to help you further.
And if you are not using any IDE, then please look at javac -cp option. However, it's much better idea to package your program in a jar
file, and include all the required jar
s within that. Then, in order to execute your jar
, like,
java -jar my_program.jar
you should have a META-INF/MANIFEST.MF
file in your jar
. See here, for how-to.
You can disable port 80 and 443 as alternative incoming connections in Skype settings - Advanced settings - Connection.
(source: ctrlv.in)
gem update --system
will update the rubygems and will fix the problem.
Give this a try :P
s = '#'.repeat(10)_x000D_
_x000D_
document.body.innerHTML = s
_x000D_
I just can't believe that there are people still using ViewData/ViewBag in ASP.NET MVC 3 instead of having strongly typed views and view models:
public class MyViewModel
{
[Required]
public string CategoryId { get; set; }
public IEnumerable<Category> Categories { get; set; }
}
and in your controller:
public class HomeController: Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
Categories = Repository.GetCategories()
}
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (!ModelState.IsValid)
{
// there was a validation error =>
// rebind categories and redisplay view
model.Categories = Repository.GetCategories();
return View(model);
}
// At this stage the model is OK => do something with the selected category
return RedirectToAction("Success");
}
}
and then in your strongly typed view:
@Html.DropDownListFor(
x => x.CategoryId,
new SelectList(Model.Categories, "ID", "CategoryName"),
"-- Please select a category --"
)
@Html.ValidationMessageFor(x => x.CategoryId)
Also if you want client side validation don't forget to reference the necessary scripts:
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
Lets take a case when you have an array of 1 element, and you want to extend the size to accommodate 1 million elements dynamically.
Case 1:
String [] wordList = new String[1];
String [] tmp = new String[wordList.length + 1];
for(int i = 0; i < wordList.length ; i++){
tmp[i] = wordList[i];
}
wordList = tmp;
Case 2 (increasing size by a addition factor):
String [] wordList = new String[1];
String [] tmp = new String[wordList.length + 10];
for(int i = 0; i < wordList.length ; i++){
tmp[i] = wordList[i];
}
wordList = tmp;
Case 3 (increasing size by a multiplication factor):
String [] wordList = new String[1];
String [] tmp = new String[wordList.length * 2];
for(int i = 0; i < wordList.length ; i++){
tmp[i] = wordList[i];
}
wordList = tmp;
When extending the size of an Array dynamically, using Array.copy or iterating over the array and copying the elements to a new array using the for loop, actually iterates over each element of the array. This is a costly operation. Array.copy would be clean and optimized, still costly. So, I'd suggest increasing the array length by a multiplication factor.
How it helps is,
In case 1, to accommodate 1 million elements you have to increase the size of array 1 million - 1 times i.e. 999,999 times.
In case 2, you have to increase the size of array 1 million / 10 - 1 times i.e. 99,999 times.
In case 3, you have to increase the size of array by log21 million - 1 time i.e. 18.9 (hypothetically).
Multi - page pdf can be extracted as text at single stretch instead of giving individual page number as argument using below code
import PyPDF2
import collections
pdf_file = open('samples.pdf', 'rb')
read_pdf = PyPDF2.PdfFileReader(pdf_file)
number_of_pages = read_pdf.getNumPages()
c = collections.Counter(range(number_of_pages))
for i in c:
page = read_pdf.getPage(i)
page_content = page.extractText()
print page_content.encode('utf-8')
As @user786653 suggested, use the xxd(1)
program:
xxd -r -p input.txt output.bin
If you delete the "[__MigrationHistory]" table from your "database > System Tables" then it will work.
I was working with a list of toasts (alert messages), List<Alert>
from C# and needed it as JavaScript array for Toastr in a partial view (.cshtml
file). The JavaScript code below is what worked for me:
var toasts = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(alerts));
toasts.forEach(function (entry) {
var command = entry.AlertStyle;
var message = entry.Message;
if (command === "danger") { command = "error"; }
toastr[command](message);
});
I've found none of the suggestions to really work. Here's a more robust one that normalizes spacing when finding classes.
//Inside closure so that the inner functions don't need regeneration on every call.
const getCssClasses = (function () {
function normalize(str) {
if (!str) return '';
str = String(str).replace(/\s*([>~+])\s*/g, ' $1 '); //Normalize symbol spacing.
return str.replace(/(\s+)/g, ' ').trim(); //Normalize whitespace
}
function split(str, on) { //Split, Trim, and remove empty elements
return str.split(on).map(x => x.trim()).filter(x => x);
}
function containsAny(selText, ors) {
return selText ? ors.some(x => selText.indexOf(x) >= 0) : false;
}
return function (selector) {
const logicalORs = split(normalize(selector), ',');
const sheets = Array.from(window.document.styleSheets);
const ruleArrays = sheets.map((x) => Array.from(x.rules || x.cssRules || []));
const allRules = ruleArrays.reduce((all, x) => all.concat(x), []);
return allRules.filter((x) => containsAny(normalize(x.selectorText), logicalORs));
};
})();
Here's it in action from the Chrome console.
Finally solved issue of reinitialization of select2 after ajax call.
You can call this in success function of ajax.
Note : Don't forget to replace ".selector" to your class of <select class="selector">
element.
jQuery('.select2-container').remove();
jQuery('.selector').select2({
placeholder: "Placeholder text",
allowClear: true
});
jQuery('.select2-container').css('width','100%');
Well, the most likely difference is that you still have to do an actual lookup of localhost
somewhere.
If you use 127.0.0.1
, then (intelligent) software will just turn that directly into an IP address and use it. Some implementations of gethostbyname
will detect the dotted format (and presumably the equivalent IPv6 format) and not do a lookup at all.
Otherwise, the name has to be resolved. And there's no guarantee that your hosts
file will actually be used for that resolution (first, or at all) so localhost
may become a totally different IP address.
By that I mean that, on some systems, a local hosts
file can be bypassed. The host.conf
file controls this on Linux (and many other Unices).
I tried all of the above solutions and none worked.
What I did was:
And then it worked. The shocking thing was that I had entered the Storyboar ID in interface builder and it got removed/deleted after opening Xcode again.
Hope this helps someone.
i have successfully done by below line
//data == html data which you want to load
String data = "Your data which you want to load";
WebView webview = (WebView)this.findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadData(data, "text/html; charset=utf-8", "UTF-8");
Or You can try
webview.loadDataWithBaseURL(null, data, "text/html", "utf-8", null);
Just open a bug report with your OS vendor asking them to put the socket in /var/run so it automagically gets removed at reboot. It's a bug to keep this socket after an unclean reboot, /var/run is the spot for these kinds of files.
This will return 5.1 for xp or 6/1 for windows 7
for /f "tokens=4-7 delims=[.] " %%i in ('ver') do (
if %%i == Version set OSVersion=%%j.%%k
if %%i neq Version set OSVersion=%%i.%%j
)
Another method would be to get the error code from the exception class directly. For example:
catch (Exception ex)
{
if (ex.InnerException is ServiceResponseException)
{
ServiceResponseException srex = ex.InnerException as ServiceResponseException;
string ErrorCode = srex.ErrorCode.ToString();
}
}
If you are using a List<Object>
to hold objects of a subtype that has a name field (lets call the subtype NamedObject
), you'll need to downcast the list elements in order to access the name. You have 3 options, the best of which is the first:
List<Object>
in the first place if you can help it - keep your named objects in a List<NamedObject>
List<Object>
elements into a List<NamedObject>
, downcasting in the process, do the sort, then copy them backOption 3 would look like this:
Collections.sort(p, new Comparator<Object> () {
int compare (final Object a, final Object b) {
return ((NamedObject) a).getName().compareTo((NamedObject b).getName());
}
}
According to the documentation for UINavigationItem
:
self.navigationItem.setHidesBackButton(true, animated: true)
Instead of using ->bindParam()
you can pass the data only at the time of ->execute()
:
$data = [ ':item_name' => $_POST['item_name'], ':item_type' => $_POST['item_type'], ':item_price' => $_POST['item_price'], ':item_description' => $_POST['item_description'], ':image_location' => 'images/'.$_FILES['file']['name'], ':status' => 0, ':id' => 0, ]; $stmt->execute($data);
In this way you would know exactly what values are going to be sent.
PointZeroTwo has got elegant answer & the same in Java ...
public void reverseList(){
if(head!=null){
head = reverseListNodes(null , head);
}
}
private Node reverseListNodes(Node parent , Node child ){
Node next = child.next;
child.next = parent;
return (next==null)?child:reverseListNodes(child, next);
}
You have to use the compareToIgnoreCase
method of the String
object.
int compareValue = str1.compareToIgnoreCase(str2);
if (compareValue == 0)
it means str1
equals str2
.
If you support IE, for versions of Internet Explorer 8 and above, this:
<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7" />
Forces the browser to render as that particular version's standards. It is not supported for IE7 and below.
If you separate with semi-colon, it sets compatibility levels for different versions. For example:
<meta http-equiv="X-UA-Compatible" content="IE=7; IE=9" />
Renders IE7 and IE8 as IE7, but IE9 as IE9. It allows for different levels of backwards compatibility. In real life, though, you should only chose one of the options:
<meta http-equiv="X-UA-Compatible" content="IE=8" />
This allows for much easier testing and maintenance. Although generally the more useful version of this is using Emulate:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />
For this:
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
It forces the browser the render at whatever the most recent version's standards are.
For more information, there is plenty to read about on MSDN,
Here is a simple way i did it in my project.
lets say you need to use clipboard.min.js
and for the sake of the example lets say that inside clipboard.min.js
there is a function that called test2()
.
in order to use test2() function you need:
clipboard.min.js
to your component.here are only the relevant parts from my project (see the comments):
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Angular QuickStart</title>
<base href="/src/">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<!-- Polyfill(s) for older browsers -->
<script src="/node_modules/core-js/client/shim.min.js"></script>
<script src="/node_modules/zone.js/dist/zone.js"></script>
<script src="/node_modules/systemjs/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('main.js').catch(function (err) { console.error(err); });
</script>
<!-- ************ HERE IS THE REFERENCE TO clipboard.min.js -->
<script src="app/txtzone/clipboard.min.js"></script>
</head>
<body>
<my-app>Loading AppComponent content here ...</my-app>
</body>
</html>
app.component.ts:
import '../txtzone/clipboard.min.js';
declare var test2: any; // variable as the name of the function inside clipboard.min.js
@Component({
selector: 'txt-zone',
templateUrl: 'app/txtzone/Txtzone.component.html',
styleUrls: ['app/txtzone/TxtZone.css'],
})
export class TxtZoneComponent implements AfterViewInit {
// call test2
callTest2()
{
new test2(); // the javascript function will execute
}
}
If you create a new Date object, by default it will be set to the current time:
import java.util.Date;
Date now = new Date();
If this error arises when manipulating a file that was just opened, check to see if you opened it in 'rb'
mode
You can't, but you can use BETWEEN
SELECT job FROM mytable WHERE id BETWEEN 10 AND 15
Note that BETWEEN
is inclusive, and will include items with both id 10 and 15.
If you do not want inclusion, you'll have to fall back to using the >
and <
operators.
SELECT job FROM mytable WHERE id > 10 AND id < 15
This is not a problem with XAML. The error message is saying that it tried to create an instance of DVRClientInterface.MainWindow
and your constructor threw an exception.
You will need to look at the "Inner Exception" property to determine the underlying cause. It could be quite literally anything, but should provide direction.
An example would be that if you are connecting to a database in the constructor for your window, and for some reason that database is unavailable, the inner exception may be a TimeoutException
or a SqlException
or any other exception thrown by your database code.
If you are throwing exceptions in static constructors, the exception could be generated from any class referenced by the MainWindow
. Class initializers are also run, if any MainWindow
fields are calling a method which may throw.
I had the same problem, so here's what I came up with. This is what my folder structure looked like when I ran node server.js
app/
index.html
server.js
After printing out the __dirname
path, I realized that the __dirname
path was where my server was running (app/
).
So, the answer to your question is this:
If your server.js
file is in the same folder as the files you are trying to render, then
app.use(express.static(__dirname + '/default.htm'));
should actually be
app.use(express.static(__dirname));
The only time you would want to use the original syntax that you had would be if you had a folder tree like so:
app/
index.html
server.js
where index.html
is in the app/
directory, whereas server.js
is in the root directory (i.e. the same level as the app/
directory).
Overall, your code could look like:
var express = require('express');
var app = express();
app.use(express.static(__dirname));
app.listen(process.env.PORT);
You can use assertException extension to assert more than one exception during one test execution.
Insert method into your TestCase and use:
public function testSomething()
{
$test = function() {
// some code that has to throw an exception
};
$this->assertException( $test, 'InvalidArgumentException', 100, 'expected message' );
}
I also made a trait for lovers of nice code..
The javadoc for setParameter(String, Object)
is explicit, saying that the Object value must be non-null. It's a shame that it doesn't throw an exception if a null is passed in, though.
An alternative is setParameter(String, Object, Type)
, which does allow null values, although I'm not sure what Type
parameter would be most appropriate here.
Make sure you understand the three return values of os.walk
:
for root, subdirs, files in os.walk(rootdir):
has the following meaning:
root
: Current path which is "walked through"subdirs
: Files in root
of type directoryfiles
: Files in root
(not in subdirs
) of type other than directoryAnd please use os.path.join
instead of concatenating with a slash! Your problem is filePath = rootdir + '/' + file
- you must concatenate the currently "walked" folder instead of the topmost folder. So that must be filePath = os.path.join(root, file)
. BTW "file" is a builtin, so you don't normally use it as variable name.
Another problem are your loops, which should be like this, for example:
import os
import sys
walk_dir = sys.argv[1]
print('walk_dir = ' + walk_dir)
# If your current working directory may change during script execution, it's recommended to
# immediately convert program arguments to an absolute path. Then the variable root below will
# be an absolute path as well. Example:
# walk_dir = os.path.abspath(walk_dir)
print('walk_dir (absolute) = ' + os.path.abspath(walk_dir))
for root, subdirs, files in os.walk(walk_dir):
print('--\nroot = ' + root)
list_file_path = os.path.join(root, 'my-directory-list.txt')
print('list_file_path = ' + list_file_path)
with open(list_file_path, 'wb') as list_file:
for subdir in subdirs:
print('\t- subdirectory ' + subdir)
for filename in files:
file_path = os.path.join(root, filename)
print('\t- file %s (full path: %s)' % (filename, file_path))
with open(file_path, 'rb') as f:
f_content = f.read()
list_file.write(('The file %s contains:\n' % filename).encode('utf-8'))
list_file.write(f_content)
list_file.write(b'\n')
If you didn't know, the with
statement for files is a shorthand:
with open('filename', 'rb') as f:
dosomething()
# is effectively the same as
f = open('filename', 'rb')
try:
dosomething()
finally:
f.close()
the key point is finding the right path where your grunt was installed.
I installed grunt through npm, but my grunt path was /Users/${whoyouare}/.npm-global/lib/node_modules/grunt/bin/grunt
. So after I added /Users/${whoyouare}/.npm-global/lib/node_modules/grunt/bin
to ~/.bash_profile
,and source ~/.bash_profile
, It worked.
So the steps are as followings:
1. find the path where your grunt was installed(when you installed grunt, it told you. if you don't remember, you can install it one more time)
2. vi ~/.bash_profile
3. export PATH=$PATH:/your/path/where/grunt/was/installed
4. source ~/.bash_profile
You can refer http://www.hongkiat.com/blog/grunt-command-not-found/
You could use Role Strategy plugin for that purpose. It works like a charm, just setup some roles and assign them. Even on project-specific level.
Use the group collection of the Match object, indexing it with the capturing group name, e.g.
foreach (Match m in mc){
MessageBox.Show(m.Groups["link"].Value);
}
It was changed between 3.1 and 3.2:
This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.
Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.
So use it without the quotes thus:
i="test"
if [[ $i =~ 200[78] ]] ; then
echo "OK"
else
echo "not OK"
fi
Adding to the other answers:
you can create a function for trimming the date from a datetime
CREATE FUNCTION dbo.f_trimdate (@dat datetime) RETURNS DATETIME AS BEGIN
RETURN CONVERT(DATETIME, CONVERT(FLOAT, @dat) - CONVERT(INT, @dat))
END
So this:
DECLARE @dat DATETIME
SELECT @dat = '20080201 02:25:46.000'
SELECT dbo.f_trimdate(@dat)
Will return 1900-01-01 02:25:46.000
Simple PHP file/image upload code on same page.
<form action="" method="post" enctype="multipart/form-data">
<table border="1px">
<tr><td><input type="file" name="image" ></td></tr>
<tr><td> <input type="submit" value="upload" name="btn"></td></tr>
</table>
</form>
<?php
if(isset($_POST['btn'])){
$image=$_FILES['image']['name'];
$imageArr=explode('.',$image); //first index is file name and second index file type
$rand=rand(10000,99999);
$newImageName=$imageArr[0].$rand.'.'.$imageArr[1];
$uploadPath="uploads/".$newImageName;
$isUploaded=move_uploaded_file($_FILES["image"]["tmp_name"],$uploadPath);
if($isUploaded)
echo 'successfully file uploaded';
else
echo 'something went wrong';
}
?>
Finally I can fix the issue now.
At first, we need to identify or understand the problem which mostly people not really findout, my VM is came with guest OS of Ubuntu 64-bits but after import, we check on that VM it shows only 32-bits OS.
When we start the VM, we got error as:
Failed to open a session for the virtual machine ERPNext-Develop-20180331192506.
Raw-mode is unavailable courtesy of Hyper-V. (VERR_SUPDRV_NO_RAW_MODE_HYPER_V_ROOT).
Result Code: E_FAIL (0x80004005)
Component: ConsoleWrap
Interface: IConsole {872da645-4a9b-1727-bee2-5585105b9eed}
I did try above solutions, somehow not really work or I might miss something.
Then I notice the point above (32-bits OS) so I think the problem might be with this one.
With some posts around the Internet, it could explain that Windows 10 also comes with the Hyper-V which is conflict with Oracle VM VirtualBox.
So solution I did...
1. Disable Virtualization Based Security in group policy
Disable Microsoft Hyper-V
Then we can use the VM, it's started. Among the two steps above, I believe that step 2 is really solved.
Anyway, please try it and let's know if it helps.
I was in the same situation as you, the half answers scattered throughout the Internet were quite annoying, since it seemed that many people had the same issue, but no one could be bothered to fully explain how they solved it.
The Sonar docs refer to a GitHub project with examples that are helpful. What I did to solve this was to apply the integration tests logic to regular unit tests (although proper unit tests should be submodule specific, this isn't always the case).
In the parent pom.xml, add these properties:
<properties>
<!-- Sonar -->
<sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>
<sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>
<sonar.jacoco.reportPath>${project.basedir}/../target/jacoco.exec</sonar.jacoco.reportPath>
<sonar.language>java</sonar.language>
</properties>
This will make Sonar pick up unit testing reports for all submodules in the same place (a target folder in the parent project). It also tells Sonar to reuse reports ran manually instead of rolling its own. We just need to make jacoco-maven-plugin run for all submodules by placing this in the parent pom, inside build/plugins:
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.6.0.201210061924</version>
<configuration>
<destFile>${sonar.jacoco.reportPath}</destFile>
<append>true</append>
</configuration>
<executions>
<execution>
<id>agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
</executions>
</plugin>
destFile
places the report file in the place where Sonar will look for it and append
makes it append to the file rather than overwriting it. This will combine all JaCoCo reports for all submodules in the same file.
Sonar will look at that file for each submodule, since that's what we pointed him at above, giving us combined unit testing results for multi module files in Sonar.
Based on antoinepairet's comment/example:
Using uib-collapse
attribute provides animations: http://plnkr.co/edit/omyoOxYnCdWJP8ANmTc6?p=preview
<nav class="navbar navbar-default" role="navigation">
<div class="navbar-header">
<!-- note the ng-init and ng-click here: -->
<button type="button" class="navbar-toggle" ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Brand</a>
</div>
<div class="collapse navbar-collapse" uib-collapse="navCollapsed">
<ul class="nav navbar-nav">
...
</ul>
</div>
</nav>
I see that the question is framed around BS2, but I thought I'd pitch in with a solution for Bootstrap 3 using ng-class solution based on suggestions in ui.bootstrap issue 394:
The only variation from the official bootstrap example is the addition of ng-
attributes noted by comments, below:
<nav class="navbar navbar-default" role="navigation">
<div class="navbar-header">
<!-- note the ng-init and ng-click here: -->
<button type="button" class="navbar-toggle" ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Brand</a>
</div>
<!-- note the ng-class here -->
<div class="collapse navbar-collapse" ng-class="{'in':!navCollapsed}">
<ul class="nav navbar-nav">
...
Here is an updated working example: http://plnkr.co/edit/OlCCnbGlYWeO7Nxwfj5G?p=preview (hat tip Lars)
This seems to works for me in simple use cases, but you'll note in the example that the second dropdown is cut off… good luck!
Wrap all the children inside of another LinearLayout with wrap_content
for both the width and the height as well as the vertical orientation.
I've also been looking for solution to this problem, here's what I eventually came up with:
function getTimeStr() {
var dt = new Date();
var d = dt.toLocaleDateString();
var t = dt.toLocaleTimeString();
t = t.replace(/\u200E/g, '');
t = t.replace(/^([^\d]*\d{1,2}:\d{1,2}):\d{1,2}([^\d]*)$/, '$1$2');
var result = d + ' ' + t;
return result;
}
You can try it here: http://jsfiddle.net/B5Zrx/
\u200E is some formatting character that I've seen on some IE version (it's unicode left-to-right mark).
I assume that if the formatted time contains something like "XX:XX:XX" then it must be time with seconds and I remove the last part, if I don't find this pattern, nothing is changed. Pretty safe, but there is a risk of leaving seconds in some weird circumstances.
I just hope that there is no locale that would change the order of formatted time parts (e.g. make it ss:mm:hh). This left-to-right mark is making me a bit nervous about that though, that is why I don't remove the right-to-left mark (\u202E) - I prefer to not find a match in this case and leave the time formatted with seconds in such case.
You absolutely need to know where the files to be read can be located. However, this information can be relative of course so it may be well adapted to other systems.
So it could relate to the current directory (get it from Directory.GetCurrentDirectory()
) or to the application executable path (eg. Application.ExecutablePath
comes to mind if using Windows Forms or via Assembly.GetEntryAssembly().Location
) or to some special Windows directory like "Documents and Settings" (you should use Environment.GetFolderPath()
with one element of the Environment.SpecialFolder
enumeration).
Note that the "current directory" and the path of the executable are not necessarily identical. You need to know where to look!
In either case, if you need to manipulate a path use the Path class to split or combine parts of the path.
To quickly add a Javadoc use following shortcut:
Windows: alt + shift + J
Mac: ? + Alt + J
Depending on selected context, a Javadoc will be printed. To create Javadoc written by OP, select corresponding method and hit the shotcut keys.
Unexpected token < in JSON at position 0
A simple solution to this error is to write a comment in styles.less
file.
The SaveFileDialog
control won't do any saving at all. All it does is providing you a convenient interface to actually display Windows' default file save dialog.
Set the property InitialDirectory
to the drive you'd like it to show some other default. Just think of other computers that might have a different layout. By default windows will save the directory used the last time and present it again.
That is handled outside the control. You'll have to check the dialog's results and then do the saving yourself (e.g. write a text or binary file).
Just as a quick example (there are alternative ways to do it).
savefile
is a control of type SaveFileDialog
SaveFileDialog savefile = new SaveFileDialog();
// set a default file name
savefile.FileName = "unknown.txt";
// set filters - this can be done in properties as well
savefile.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
if (savefile.ShowDialog() == DialogResult.OK)
{
using (StreamWriter sw = new StreamWriter(savefile.FileName))
sw.WriteLine ("Hello World!");
}
you can do
findViewById
from the radio group .
Here it is sample :
((RadioButton)my_radio_group.findViewById(R.id.radiobtn_veg)).setChecked(true);
What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.
I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)
All solutions above and below (my solution including) suffer from possibility of being incorrect, especially on IE — it is quite possible to (re)define some objects/methods/properties to mimic a DOM node rendering the test invalid.
So usually I use the duck-typing-style testing: I test specifically for things I use. For example, if I want to clone a node I test it like this:
if(typeof node == "object" && "nodeType" in node &&
node.nodeType === 1 && node.cloneNode){
// most probably this is a DOM node, we can clone it safely
clonedNode = node.cloneNode(false);
}
Basically it is a little sanity check + the direct test for a method (or a property) I am planning to use.
Incidentally the test above is a good test for DOM nodes on all browsers. But if you want to be on the safe side always check the presence of methods and properties and verify their types.
EDIT: IE uses ActiveX objects to represent nodes, so their properties do not behave as true JavaScript object, for example:
console.log(typeof node.cloneNode); // object
console.log(node.cloneNode instanceof Function); // false
while it should return "function" and true
respectively. The only way to test methods is to see if the are defined.
You can index into a string in C# like an array, and you get the character at that index.
Example:
In Java, you would say
str.charAt(8);
In C#, you would say
str[8];
argc
is the number of arguments being passed into your program from the command line and argv
is the array of arguments.
You can loop through the arguments knowing the number of them like:
for(int i = 0; i < argc; i++)
{
// argv[i] is the argument at index i
}
if (pathname.substring(0, 6) == "/sub/1") {
// ...
}
Insert the var msg in the click event with scope.$apply to make the changes to the confirm, based on your controller changes to the variables shown in ng-confirm-click therein.
<button type="button" class="btn" ng-confirm-click="You are about to send {{quantity}} of {{thing}} selected? Confirm with OK" confirmed-click="youraction(id)" aria-describedby="passwordHelpBlock">Send</button>
app.directive('ngConfirmClick', [
function() {
return {
link: function(scope, element, attr) {
var clickAction = attr.confirmedClick;
element.on('click', function(event) {
var msg = attr.ngConfirmClick || "Are you sure? Click OK to confirm.";
if (window.confirm(msg)) {
scope.$apply(clickAction)
}
});
}
};
}
])
Also there is
aRange.EntireColumn.AutoFit();
See What is the difference between Range.Columns and Range.EntireColumn.
some thing as follows ::
Add this After the body tag
This is a rough sketch, you will need to modify it according to your needs.
<script>
var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('action',"submit.php");
var i = document.createElement("input"); //input element, text
i.setAttribute('type',"text");
i.setAttribute('name',"username");
var s = document.createElement("input"); //input element, Submit button
s.setAttribute('type',"submit");
s.setAttribute('value',"Submit");
f.appendChild(i);
f.appendChild(s);
//and some more input elements here
//and dont forget to add a submit button
document.getElementsByTagName('body')[0].appendChild(f);
</script>
It is used in transaction management to ensure that any errors result in the transaction being rolled back.
add the -s
(silent) option to remove the progress meter, then redirect stderr to stdout to get verbose output on the same fd as the response body
curl -vs google.com 2>&1 | less
This is how i solved my problem
xampp/mysql/data
directoryHere's a simple example demonstrating the creation of a comma delimited string using String.Join() from a list of Strings:
List<string> histList = new List<string>();
histList.Add(dt.ToString("MM/dd/yyyy::HH:mm:ss.ffff"));
histList.Add(Index.ToString());
/*arValue is array of Singles */
foreach (Single s in arValue)
{
histList.Add(s.ToString());
}
String HistLine = String.Join(",", histList.ToArray());
netstat -a -n | find /c "10.240.199.9:8080"
it will give you number of sockets active on a specific IP and port(Server port number)
My lightweight implementation of ParallelForEach async.
Features:
public static class AsyncEx
{
public static async Task ParallelForEachAsync<T>(this IEnumerable<T> source, Func<T, Task> asyncAction, int maxDegreeOfParallelism = 10)
{
var semaphoreSlim = new SemaphoreSlim(maxDegreeOfParallelism);
var tcs = new TaskCompletionSource<object>();
var exceptions = new ConcurrentBag<Exception>();
bool addingCompleted = false;
foreach (T item in source)
{
await semaphoreSlim.WaitAsync();
asyncAction(item).ContinueWith(t =>
{
semaphoreSlim.Release();
if (t.Exception != null)
{
exceptions.Add(t.Exception);
}
if (Volatile.Read(ref addingCompleted) && semaphoreSlim.CurrentCount == maxDegreeOfParallelism)
{
tcs.TrySetResult(null);
}
});
}
Volatile.Write(ref addingCompleted, true);
await tcs.Task;
if (exceptions.Count > 0)
{
throw new AggregateException(exceptions);
}
}
}
Usage example:
await Enumerable.Range(1, 10000).ParallelForEachAsync(async (i) =>
{
var data = await GetData(i);
}, maxDegreeOfParallelism: 100);
Alternatively, in plain text: (also available as a a screenshot)
Bracket Matching -. .- Line Numbering
Smart Indent -. | | .- UML Editing / Viewing
Source Control Integration -. | | | | .- Code Folding
Error Markup -. | | | | | | .- Code Templates
Integrated Python Debugging -. | | | | | | | | .- Unit Testing
Multi-Language Support -. | | | | | | | | | | .- GUI Designer (Qt, Eric, etc)
Auto Code Completion -. | | | | | | | | | | | | .- Integrated DB Support
Commercial/Free -. | | | | | | | | | | | | | | .- Refactoring
Cross Platform -. | | | | | | | | | | | | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Atom |Y |F |Y |Y*|Y |Y |Y |Y |Y |Y | |Y |Y | | | | |*many plugins
Editra |Y |F |Y |Y | | |Y |Y |Y |Y | |Y | | | | | |
Emacs |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y | | | |
Eric Ide |Y |F |Y | |Y |Y | |Y | |Y | |Y | |Y | | | |
Geany |Y |F |Y*|Y | | | |Y |Y |Y | |Y | | | | | |*very limited
Gedit |Y |F |Y¹|Y | | | |Y |Y |Y | | |Y²| | | | |¹with plugin; ²sort of
Idle |Y |F |Y | |Y | | |Y |Y | | | | | | | | |
IntelliJ |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |
JEdit |Y |F | |Y | | | | |Y |Y | |Y | | | | | |
KDevelop |Y |F |Y*|Y | | |Y |Y |Y |Y | |Y | | | | | |*no type inference
Komodo |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y | |Y |Y |Y | |Y | |
NetBeans* |Y |F |Y |Y |Y | |Y |Y |Y |Y |Y |Y |Y |Y | | |Y |*pre-v7.0
Notepad++ |W |F |Y |Y | |Y*|Y*|Y*|Y |Y | |Y |Y*| | | | |*with plugin
Pfaide |W |C |Y |Y | | | |Y |Y |Y | |Y |Y | | | | |
PIDA |LW|F |Y |Y | | | |Y |Y |Y | |Y | | | | | |VIM based
PTVS |W |F |Y |Y |Y |Y |Y |Y |Y |Y | |Y | | |Y*| |Y |*WPF bsed
PyCharm |Y |CF|Y |Y*|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |*JavaScript
PyDev (Eclipse) |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y | | | |
PyScripter |W |F |Y | |Y |Y | |Y |Y |Y | |Y |Y |Y | | | |
PythonWin |W |F |Y | |Y | | |Y |Y | | |Y | | | | | |
SciTE |Y |F¹| |Y | |Y | |Y |Y |Y | |Y |Y | | | | |¹Mac version is
ScriptDev |W |C |Y |Y |Y |Y | |Y |Y |Y | |Y |Y | | | | | commercial
Spyder |Y |F |Y | |Y |Y | |Y |Y |Y | | | | | | | |
Sublime Text |Y |CF|Y |Y | |Y |Y |Y |Y |Y | |Y |Y |Y*| | | |extensible w/Python,
TextMate |M |F | |Y | | |Y |Y |Y |Y | |Y |Y | | | | | *PythonTestRunner
UliPad |Y |F |Y |Y |Y | | |Y |Y | | | |Y |Y | | | |
Vim |Y |F |Y |Y |Y |Y |Y |Y |Y |Y | |Y |Y |Y | | | |
Visual Studio |W |CF|Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |Y |? |Y |
Visual Studio Code|Y |F |Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |? |? |Y |uses plugins
WingIde |Y |C |Y |Y*|Y |Y |Y |Y |Y |Y | |Y |Y |Y | | | |*support for C
Zeus |W |C | | | | |Y |Y |Y |Y | |Y |Y | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Cross Platform -' | | | | | | | | | | | | | | | |
Commercial/Free -' | | | | | | | | | | | | | | '- Refactoring
Auto Code Completion -' | | | | | | | | | | | | '- Integrated DB Support
Multi-Language Support -' | | | | | | | | | | '- GUI Designer (Qt, Eric, etc)
Integrated Python Debugging -' | | | | | | | | '- Unit Testing
Error Markup -' | | | | | | '- Code Templates
Source Control Integration -' | | | | '- Code Folding
Smart Indent -' | | '- UML Editing / Viewing
Bracket Matching -' '- Line Numbering
Acronyms used:
L - Linux
W - Windows
M - Mac
C - Commercial
F - Free
CF - Commercial with Free limited edition
? - To be confirmed
I don't mention basics like syntax highlighting as I expect these by default.
This is a just dry list reflecting your feedback and comments, I am not advocating any of these tools. I will keep updating this list as you keep posting your answers.
PS. Can you help me to add features of the above editors to the list (like auto-complete, debugging, etc.)?
We have a comprehensive wiki page for this question https://wiki.python.org/moin/IntegratedDevelopmentEnvironments
You may be interested in the csv
module, which is designed for comma-separated files but can be easily modified to use a custom delimiter.
import csv
csv.register_dialect( "myDialect", delimiter = "__", <other-options> )
lines = [ "MATCHES__STRING" ]
for row in csv.reader( lines ):
...
Solution to this is
http://www.dotnetzone.gr/cs/forums/48758/ShowThread.aspx#48758
from item in db.vw_Dropship_OrderItems
where (listStatus != null ? listStatus.Contains(item.StatusCode) : true) &&
(listMerchants != null ? listMerchants.Contains(item.MerchantId) : true)
select item;
Might give strange behavior if both listMerchants and listStatus are both null.
What you want cannot be done, because plt.legend()
places a legend in the current axes, in your case in the last one.
If, on the other hand, you can be content with placing a comprehensive legend in the last subplot, you can do like this
f, (ax1, ax2, ax3) = plt.subplots(3, sharex=True, sharey=True)
l1,=ax1.plot(x,y, color='r', label='Blue stars')
l2,=ax2.plot(x,y, color='g')
l3,=ax3.plot(x,y, color='b')
ax1.set_title('2012/09/15')
plt.legend([l1, l2, l3],["HHZ 1", "HHN", "HHE"])
plt.show()
Note that you pass to legend
not the axes, as in your example code, but the lines as returned by the plot
invocation.
Of course you can invoke legend
after each subplot, but in my understanding you already knew that and were searching for a method for doing it at once.
i need to change the sheet name by the name of the file was opened
Sub Get_Data_From_File5()
Dim FileToOpen As Variant
Dim OpenBook As Workbook
Dim currentName As String
currentName = ActiveSheet.Name
Application.ScreenUpdating = False
FileToOpen = Application.GetOpenFilename(Title:="Browse for your File & Import Range", FileFilter:="Excel Files (*.csv*),*csv*")
If FileToOpen <> False Then
Set OpenBook = Application.Workbooks.Open(FileToOpen)
OpenBook.Sheets(1).Range("A1:g5000").Copy
ThisWorkbook.Worksheets(currentName).Range("Aw1:bc5000").PasteSpecial xlPasteValues
OpenBook.Close False
End If
Application.ScreenUpdating = True
End Sub
Here is another way of doing it, similar to Dan Allan's answer but without the lambda function:
>>> pd.options.display.float_format = '{:.2f}'.format
>>> Series(np.random.randn(3))
0 0.41
1 0.99
2 0.10
or
>>> pd.set_option('display.float_format', '{:.2f}'.format)
Make sure to run mvn install
before you compile your war.
Go to enterprise manager, design table, click on your field.
Make a decimal column
In the properties at the bottom there is a precision property
You have four main options for converting types in pandas:
to_numeric()
- provides functionality to safely convert non-numeric types (e.g. strings) to a suitable numeric type. (See also to_datetime()
and to_timedelta()
.)
astype()
- convert (almost) any type to (almost) any other type (even if it's not necessarily sensible to do so). Also allows you to convert to categorial types (very useful).
infer_objects()
- a utility method to convert object columns holding Python objects to a pandas type if possible.
convert_dtypes()
- convert DataFrame columns to the "best possible" dtype that supports pd.NA
(pandas' object to indicate a missing value).
Read on for more detailed explanations and usage of each of these methods.
to_numeric()
The best way to convert one or more columns of a DataFrame to numeric values is to use pandas.to_numeric()
.
This function will try to change non-numeric objects (such as strings) into integers or floating point numbers as appropriate.
The input to to_numeric()
is a Series or a single column of a DataFrame.
>>> s = pd.Series(["8", 6, "7.5", 3, "0.9"]) # mixed string and numeric values
>>> s
0 8
1 6
2 7.5
3 3
4 0.9
dtype: object
>>> pd.to_numeric(s) # convert everything to float values
0 8.0
1 6.0
2 7.5
3 3.0
4 0.9
dtype: float64
As you can see, a new Series is returned. Remember to assign this output to a variable or column name to continue using it:
# convert Series
my_series = pd.to_numeric(my_series)
# convert column "a" of a DataFrame
df["a"] = pd.to_numeric(df["a"])
You can also use it to convert multiple columns of a DataFrame via the apply()
method:
# convert all columns of DataFrame
df = df.apply(pd.to_numeric) # convert all columns of DataFrame
# convert just columns "a" and "b"
df[["a", "b"]] = df[["a", "b"]].apply(pd.to_numeric)
As long as your values can all be converted, that's probably all you need.
But what if some values can't be converted to a numeric type?
to_numeric()
also takes an errors
keyword argument that allows you to force non-numeric values to be NaN
, or simply ignore columns containing these values.
Here's an example using a Series of strings s
which has the object dtype:
>>> s = pd.Series(['1', '2', '4.7', 'pandas', '10'])
>>> s
0 1
1 2
2 4.7
3 pandas
4 10
dtype: object
The default behaviour is to raise if it can't convert a value. In this case, it can't cope with the string 'pandas':
>>> pd.to_numeric(s) # or pd.to_numeric(s, errors='raise')
ValueError: Unable to parse string
Rather than fail, we might want 'pandas' to be considered a missing/bad numeric value. We can coerce invalid values to NaN
as follows using the errors
keyword argument:
>>> pd.to_numeric(s, errors='coerce')
0 1.0
1 2.0
2 4.7
3 NaN
4 10.0
dtype: float64
The third option for errors
is just to ignore the operation if an invalid value is encountered:
>>> pd.to_numeric(s, errors='ignore')
# the original Series is returned untouched
This last option is particularly useful when you want to convert your entire DataFrame, but don't not know which of our columns can be converted reliably to a numeric type. In that case just write:
df.apply(pd.to_numeric, errors='ignore')
The function will be applied to each column of the DataFrame. Columns that can be converted to a numeric type will be converted, while columns that cannot (e.g. they contain non-digit strings or dates) will be left alone.
By default, conversion with to_numeric()
will give you either a int64
or float64
dtype (or whatever integer width is native to your platform).
That's usually what you want, but what if you wanted to save some memory and use a more compact dtype, like float32
, or int8
?
to_numeric()
gives you the option to downcast to either 'integer', 'signed', 'unsigned', 'float'. Here's an example for a simple series s
of integer type:
>>> s = pd.Series([1, 2, -7])
>>> s
0 1
1 2
2 -7
dtype: int64
Downcasting to 'integer' uses the smallest possible integer that can hold the values:
>>> pd.to_numeric(s, downcast='integer')
0 1
1 2
2 -7
dtype: int8
Downcasting to 'float' similarly picks a smaller than normal floating type:
>>> pd.to_numeric(s, downcast='float')
0 1.0
1 2.0
2 -7.0
dtype: float32
astype()
The astype()
method enables you to be explicit about the dtype you want your DataFrame or Series to have. It's very versatile in that you can try and go from one type to the any other.
Just pick a type: you can use a NumPy dtype (e.g. np.int16
), some Python types (e.g. bool), or pandas-specific types (like the categorical dtype).
Call the method on the object you want to convert and astype()
will try and convert it for you:
# convert all DataFrame columns to the int64 dtype
df = df.astype(int)
# convert column "a" to int64 dtype and "b" to complex type
df = df.astype({"a": int, "b": complex})
# convert Series to float16 type
s = s.astype(np.float16)
# convert Series to Python strings
s = s.astype(str)
# convert Series to categorical type - see docs for more details
s = s.astype('category')
Notice I said "try" - if astype()
does not know how to convert a value in the Series or DataFrame, it will raise an error. For example if you have a NaN
or inf
value you'll get an error trying to convert it to an integer.
As of pandas 0.20.0, this error can be suppressed by passing errors='ignore'
. Your original object will be return untouched.
astype()
is powerful, but it will sometimes convert values "incorrectly". For example:
>>> s = pd.Series([1, 2, -7])
>>> s
0 1
1 2
2 -7
dtype: int64
These are small integers, so how about converting to an unsigned 8-bit type to save memory?
>>> s.astype(np.uint8)
0 1
1 2
2 249
dtype: uint8
The conversion worked, but the -7 was wrapped round to become 249 (i.e. 28 - 7)!
Trying to downcast using pd.to_numeric(s, downcast='unsigned')
instead could help prevent this error.
infer_objects()
Version 0.21.0 of pandas introduced the method infer_objects()
for converting columns of a DataFrame that have an object datatype to a more specific type (soft conversions).
For example, here's a DataFrame with two columns of object type. One holds actual integers and the other holds strings representing integers:
>>> df = pd.DataFrame({'a': [7, 1, 5], 'b': ['3','2','1']}, dtype='object')
>>> df.dtypes
a object
b object
dtype: object
Using infer_objects()
, you can change the type of column 'a' to int64:
>>> df = df.infer_objects()
>>> df.dtypes
a int64
b object
dtype: object
Column 'b' has been left alone since its values were strings, not integers. If you wanted to try and force the conversion of both columns to an integer type, you could use df.astype(int)
instead.
convert_dtypes()
Version 1.0 and above includes a method convert_dtypes()
to convert Series and DataFrame columns to the best possible dtype that supports the pd.NA
missing value.
Here "best possible" means the type most suited to hold the values. For example, this a pandas integer type if all of the values are integers (or missing values): an object column of Python integer objects is converted to Int64
, a column of NumPy int32
values will become the pandas dtype Int32
.
With our object
DataFrame df
, we get the following result:
>>> df.convert_dtypes().dtypes
a Int64
b string
dtype: object
Since column 'a' held integer values, it was converted to the Int64
type (which is capable of holding missing values, unlike int64
).
Column 'b' contained string objects, so was changed to pandas' string
dtype.
By default, this method will infer the type from object values in each column. We can change this by passing infer_objects=False
:
>>> df.convert_dtypes(infer_objects=False).dtypes
a object
b string
dtype: object
Now column 'a' remained an object column: pandas knows it can be described as an 'integer' column (internally it ran infer_dtype
) but didn't infer exactly what dtype of integer it should have so did not convert it. Column 'b' was again converted to 'string' dtype as it was recognised as holding 'string' values.
Here is the difference:
This sets the image to half of its original size.
<img src="#" width="173" height="206.5">
This sets the image to half of its available presentation area.
<img src="#" width="50%" height="50%">
For example, if you put this as the only element on the page, it would attempt to take up 50% of the width of the page, thus making it potentially larger than its original size - not half of its original size as you are expecting.
If it is being presented at larger than original size, the image will appear greatly pixelated.
When I need to write new lines a lot, I define a lambda that uses a print
function:
out = open(file_name, 'w')
fwl = lambda *x, **y: print(*x, **y, file=out) # FileWriteLine
fwl('Hi')
This approach has the benefit that it can utilize all the features that are available with the print
function.
Update: As is mentioned by Georgy in the comment section, it is possible to improve this idea further with the partial
function:
from functools import partial
fwl = partial(print, file=out)
IMHO, this is a more functional and less cryptic approach.
If you came across the error when tried to generate a jks file (keystore), so try adding
/Applications/Android\ Studio.app/Contents/jre/jdk/Contents/Home/bin/keytool
before running the command, like so:
/Applications/Android\ Studio.app/Contents/jre/jdk/Contents/Home/bin/keytool -genkey -v -keystore ~/key.jks -keyalg RSA -keysize 2048 -validity 10000 -alias key
Another simple solution for this case using jQuery. Keep in mind it's not a good practice to use inline javascript.
I've added IDs to html on the total price and on the buttons. Here is the jQuery.
$('#two').click(function(){
$('#count').val('2');
$('#total').text('Product price: $1000');
});
$('#four').click(function(){
$('#count').val('4');
$('#total').text('Product price: $2000');
});
when you use the svn:// URI it uses port 3690 and probably won't use http proxy
The Array prototype's reverse method modifies the array and returns a reference to it, which means you can do this:
var sortedAsc = _.sortBy(collection, 'propertyName');
var sortedDesc = _.sortBy(collection, 'propertyName').reverse();
Also, the underscore documentation reads:
In addition, the Array prototype's methods are proxied through the chained Underscore object, so you can slip a
reverse
or apush
into your chain, and continue to modify the array.
which means you can also use .reverse()
while chaining:
var sortedDescAndFiltered = _.chain(collection)
.sortBy('propertyName')
.reverse()
.filter(_.property('isGood'))
.value();
From MySQL 5.7 onwards, this is possible, but requires first enabling the mdl
instrument in the performance_schema.setup_instruments
table. You can do this temporarily (until the server is next restarted) by running:
UPDATE performance_schema.setup_instruments
SET enabled = 'YES'
WHERE name = 'wait/lock/metadata/sql/mdl';
Or permanently, by adding the following incantation to the [mysqld]
section of your my.cnf
file (or whatever config files MySQL reads from on your installation):
[mysqld]
performance_schema_instrument = 'wait/lock/metadata/sql/mdl=ON'
(Naturally, MySQL will need to be restarted to make the config change take effect if you take the latter approach.)
Locks you take out after the mdl
instrument has been enabled can be seen by running a SELECT
against the performance_schema.metadata_locks
table. As noted in the docs, GET_LOCK
locks have an OBJECT_TYPE
of 'USER LEVEL LOCK'
, so we can filter our query down to them with a WHERE
clause:
mysql> SELECT GET_LOCK('foobarbaz', -1);
+---------------------------+
| GET_LOCK('foobarbaz', -1) |
+---------------------------+
| 1 |
+---------------------------+
1 row in set (0.00 sec)
mysql> SELECT * FROM performance_schema.metadata_locks
-> WHERE OBJECT_TYPE='USER LEVEL LOCK'
-> \G
*************************** 1. row ***************************
OBJECT_TYPE: USER LEVEL LOCK
OBJECT_SCHEMA: NULL
OBJECT_NAME: foobarbaz
OBJECT_INSTANCE_BEGIN: 139872119610944
LOCK_TYPE: EXCLUSIVE
LOCK_DURATION: EXPLICIT
LOCK_STATUS: GRANTED
SOURCE: item_func.cc:5482
OWNER_THREAD_ID: 35
OWNER_EVENT_ID: 3
1 row in set (0.00 sec)
mysql>
The meanings of the columns in this result are mostly adequately documented at https://dev.mysql.com/doc/refman/en/metadata-locks-table.html, but one point of confusion is worth noting: the OWNER_THREAD_ID
column does not contain the connection ID (like would be shown in the PROCESSLIST
or returned by CONNECTION_ID()
) of the thread that holds the lock. Confusingly, the term "thread ID" is sometimes used as a synonym of "connection ID" in the MySQL documentation, but this is not one of those times. If you want to determine the connection ID of the connection that holds a lock (for instance, in order to kill that connection with KILL
), you'll need to look up the PROCESSLIST_ID
that corresponds to the THREAD_ID
in the performance_schema.threads
table. For instance, to kill the connection that was holding my lock above...
mysql> SELECT OWNER_THREAD_ID FROM performance_schema.metadata_locks
-> WHERE OBJECT_TYPE='USER LEVEL LOCK'
-> AND OBJECT_NAME='foobarbaz';
+-----------------+
| OWNER_THREAD_ID |
+-----------------+
| 35 |
+-----------------+
1 row in set (0.00 sec)
mysql> SELECT PROCESSLIST_ID FROM performance_schema.threads
-> WHERE THREAD_ID=35;
+----------------+
| PROCESSLIST_ID |
+----------------+
| 10 |
+----------------+
1 row in set (0.00 sec)
mysql> KILL 10;
Query OK, 0 rows affected (0.00 sec)
If you want to copy a source directory entirely with the same directory structure, Then don't use a star(*). Write COPY command in Dockerfile as below.
COPY . destinatio-directory/
On Linux machines u can use wondershaper
apt-get install wondershaper
$ sudo wondershaper {interface} {down} {up}
the {down} and {up} are bandwidth in kpbs
So for example if you want to limit the bandwidth of interface eth1 to 256kbps uplink and 128kbps downlink,
$ sudo wondershaper eth1 256 128
To clear the limit,
$ sudo wondershaper clear eth1
Here's a technical consideration: will the image be generated dynamically? It tends to be a lot easier to generate the <img>
tag in HTML than to try to dynamically edit a CSS property.
select = driver.FindElement(By.CssSelector("select[uniq id']"));
selectElement = new SelectElement(select);
var optionList =
driver.FindElements(By.CssSelector("select[uniq id']>option"));
selectElement.SelectByText(optionList[GenerateRandomNumber(1, optionList.Count())].Text);
Maybe it's not exactly what you want to do, but using the ajax complete solved my problem of hiding a spinner when the ajax call returned.
So it would look something like this
var table = $('#example').DataTable( {
"ajax": {
"type" : "GET",
"url" : "ajax.php",
"dataSrc": "",
"success": function () {
alert("Done!");
}
},
"columns": [
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "extn" },
{ "data": "start_date" },
{ "data": "salary" }
]
} );
To put it simply, if in linear regression model more test cases arrive which are far away from the threshold(say =0.5)for a prediction of y=1 and y=0. Then in that case the hypothesis will change and become worse.Therefore linear regression model is not used for classification problem.
Another Problem is that if the classification is y=0 and y=1, h(x) can be > 1 or < 0.So we use Logistic regression were 0<=h(x)<=1.
In a comment on @paxdiablo's answer, you asked:
"So basically, is it better to use Double than Float?"
That is a complicated question. I will deal with it in two parts
double
versus float
On the one hand, a double
occupies 8 bytes versus 4 bytes for a float
. If you have many of them, this may be significant, though it may also have no impact. (Consider the case where the values are in fields or local variables on a 64bit machine, and the JVM aligns them on 64 bit boundaries.) Additionally, floating point arithmetic with double
values is typically slower than with float
values ... though once again this is hardware dependent.
On the other hand, a double
can represent larger (and smaller) numbers than a float
and can represent them with more than twice the precision. For the details, refer to Wikipedia.
The tricky question is knowing whether you actually need the extra range and precision of a double
. In some cases it is obvious that you need it. In others it is not so obvious. For instance if you are doing calculations such as inverting a matrix or calculating a standard deviation, the extra precision may be critical. On the other hand, in some cases not even double
is going to give you enough precision. (And beware of the trap of expecting float
and double
to give you an exact representation. They won't and they can't!)
There is a branch of mathematics called Numerical Analysis that deals with the effects of rounding error, etc in practical numerical calculations. It used to be a standard part of computer science courses ... back in the 1970's.
Double
versus Float
For the Double
versus Float
case, the issues of precision and range are the same as for double
versus float
, but the relative performance measures will be slightly different.
A Double
(on a 32 bit machine) typically takes 16 bytes + 4 bytes for the reference, compared with 12 + 4 bytes for a Float
. Compare this to 8 bytes versus 4 bytes for the double
versus float
case. So the ratio is 5 to 4 versus 2 to 1.
Arithmetic involving Double
and Float
typically involves dereferencing the pointer and creating a new object to hold the result (depending on the circumstances). These extra overheads also affect the ratios in favor of the Double
case.
Having said all that, the most important thing is correctness, and this typically means getting the most accurate answer. And even if accuracy is not critical, it is usually not wrong to be "too accurate". So, the simple "rule of thumb" is to use double
in preference to float
, UNLESS there is an overriding performance requirement, AND you have solid evidence that using float
will make a difference with respect to that requirement.
Probably a more appropriate way of changing outline color is using the outline-color
CSS rule.
textarea {
outline-color: #719ECE;
}
or for input
input {
outline-color: #719ECE;
}
box-shadow
isn't quite the same thing and it may look different than the outline, especially if you apply custom styling to your element.
"I do not know if it is out of ignorance, but I do not like that kind of programming, as it is using exceptions to perform flow control."
In the Python world, using exceptions for flow control is common and normal.
Even the Python core developers use exceptions for flow-control and that style is heavily baked into the language (i.e. the iterator protocol uses StopIteration to signal loop termination).
In addition, the try-except-style is used to prevent the race-conditions inherent in some of the "look-before-you-leap" constructs. For example, testing os.path.exists results in information that may be out-of-date by the time you use it. Likewise, Queue.full returns information that may be stale. The try-except-else style will produce more reliable code in these cases.
"It my understanding that exceptions are not errors, they should only be used for exceptional conditions"
In some other languages, that rule reflects their cultural norms as reflected in their libraries. The "rule" is also based in-part on performance considerations for those languages.
The Python cultural norm is somewhat different. In many cases, you must use exceptions for control-flow. Also, the use of exceptions in Python does not slow the surrounding code and calling code as it does in some compiled languages (i.e. CPython already implements code for exception checking at every step, regardless of whether you actually use exceptions or not).
In other words, your understanding that "exceptions are for the exceptional" is a rule that makes sense in some other languages, but not for Python.
"However, if it is included in the language itself, there must be a good reason for it, isn't it?"
Besides helping to avoid race-conditions, exceptions are also very useful for pulling error-handling outside loops. This is a necessary optimization in interpreted languages which do not tend to have automatic loop invariant code motion.
Also, exceptions can simplify code quite a bit in common situations where the ability to handle an issue is far removed from where the issue arose. For example, it is common to have top level user-interface code calling code for business logic which in turn calls low-level routines. Situations arising in the low-level routines (such as duplicate records for unique keys in database accesses) can only be handled in top-level code (such as asking the user for a new key that doesn't conflict with existing keys). The use of exceptions for this kind of control-flow allows the mid-level routines to completely ignore the issue and be nicely decoupled from that aspect of flow-control.
There is a nice blog post on the indispensibility of exceptions here.
Also, see this Stack Overflow answer: Are exceptions really for exceptional errors?
"What is the reason for the try-except-else to exist?"
The else-clause itself is interesting. It runs when there is no exception but before the finally-clause. That is its primary purpose.
Without the else-clause, the only option to run additional code before finalization would be the clumsy practice of adding the code to the try-clause. That is clumsy because it risks raising exceptions in code that wasn't intended to be protected by the try-block.
The use-case of running additional unprotected code prior to finalization doesn't arise very often. So, don't expect to see many examples in published code. It is somewhat rare.
Another use-case for the else-clause is to perform actions that must occur when no exception occurs and that do not occur when exceptions are handled. For example:
recip = float('Inf')
try:
recip = 1 / f(x)
except ZeroDivisionError:
logging.info('Infinite result')
else:
logging.info('Finite result')
Another example occurs in unittest runners:
try:
tests_run += 1
run_testcase(case)
except Exception:
tests_failed += 1
logging.exception('Failing test case: %r', case)
print('F', end='')
else:
logging.info('Successful test case: %r', case)
print('.', end='')
Lastly, the most common use of an else-clause in a try-block is for a bit of beautification (aligning the exceptional outcomes and non-exceptional outcomes at the same level of indentation). This use is always optional and isn't strictly necessary.
Make sure to add the following:
if (event.getAction()!=KeyEvent.ACTION_DOWN)
return true;
in the onKey block of code to avoid the event calling twice.
I had the same error, then I tried <asp:PostBackTrigger ControlID="xyz"/>
instead of AsyncPostBackTrigger .This worked for me. It is because we don't want a partial postback.
Shortcut Alt+Enter shows intention actions where you can choose "Add Javadoc".
You only can have one unique ID per page. Change those IDs to classes, and change the jQuery selectors as well.
Also, move the .on() outside of the .click() function, as you only need to set it once.
http://jsfiddle.net/samliew/3AJcj/2/
$(document).ready(function(){
$(".addCF").click(function(){
$("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> <input type="text" class="code" id="customFieldValue" name="customFieldValue[]" value="" placeholder="Input Value" /> <a href="javascript:void(0);" class="remCF">Remove</a></td></tr>');
});
$("#customFields").on('click','.remCF',function(){
$(this).parent().parent().remove();
});
});
git config --global core.editor "'C:/Program Files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"
Or, for 64-bit Windows and a 32-bit install of Notepad++:
git config --global core.editor "'C:/Program Files (x86)/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"
Or, the following can be issued on the command line on either 32-bit or 64-bit Windows. It will pull the location of notepad++.exe from the registry and configure git to use it automatically:
FOR /F "usebackq tokens=2*" %A IN (`REG QUERY "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\App Paths\notepad++.exe" /ve`) DO git config --global core.editor "'%B' -multiInst -notabbar -nosession -noPlugin"
If you wish to place the above from a .BAT or .CMD file, you must replace %A with %%A and %B with %%B
final ListView lv = (ListView) findViewById(R.id.ListView01);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
String selectedFromList =(String) (lv.getItemAtPosition(myItemInt));
}
});
I hope this fixes your problem.
I was also facing this issue
Error- Windows cannot find 'http://127.0.01:%HTTPPORT%/apex/f?p=4950'. Make sure you typed the name correctly, and then try again
After some research work, I found out that my HTTPPORT
ie. 8080
was occupied by Apace HTTP Server
and hence connection by OracleServiceXE
could not be established.
What I did to solve this issue was :
Apache2.4
and manually stopped it to free my 8080
port.Start Database
, and I received message : The OracleServiceXE service is starting.............. The OracleServiceXE service was started successfully.
http://127.0.0.1:8080/apex/f?p=4950
url to my browser which auto redirected me to http://127.0.0.1:8080/apex/f?p=4950:1:3763261197573303
That's it my issue got resolved.
In order to remember this new url and make sure that next time whenever I hit Get Started
I should be redirected to http://127.0.0.1:8080/apex/f?p=4950:1:3763261197573303
instead of http://127.0.0.1:8080/apex/f?p=4950
, what I did was :
Directory:\OracleDatabase\app\oracle\product\11.2.0\server
and search for Get_Started.html
.Get_Started.html
and select Properties
Apply
Hope this Helps.
Building off the above (great!) answer, we can also make a horizontal bar plot with just a few adjustments:
# Bring some raw data.
frequencies = [6, -16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
freq_series = pd.Series(frequencies)
y_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0,
121740.0, 123980.0, 126220.0, 128460.0, 130700.0]
# Plot the figure.
plt.figure(figsize=(12, 8))
ax = freq_series.plot(kind='barh')
ax.set_title('Amount Frequency')
ax.set_xlabel('Frequency')
ax.set_ylabel('Amount ($)')
ax.set_yticklabels(y_labels)
ax.set_xlim(-40, 300) # expand xlim to make labels easier to read
rects = ax.patches
# For each bar: Place a label
for rect in rects:
# Get X and Y placement of label from rect.
x_value = rect.get_width()
y_value = rect.get_y() + rect.get_height() / 2
# Number of points between bar and label. Change to your liking.
space = 5
# Vertical alignment for positive values
ha = 'left'
# If value of bar is negative: Place label left of bar
if x_value < 0:
# Invert space to place label to the left
space *= -1
# Horizontally align label at right
ha = 'right'
# Use X value as label and format number with one decimal place
label = "{:.1f}".format(x_value)
# Create annotation
plt.annotate(
label, # Use `label` as label
(x_value, y_value), # Place label at end of the bar
xytext=(space, 0), # Horizontally shift label by `space`
textcoords="offset points", # Interpret `xytext` as offset in points
va='center', # Vertically center label
ha=ha) # Horizontally align label differently for
# positive and negative values.
plt.savefig("image.png")
I actually just thought of an interesting solution. While Windows will not allow you to easily alias programs, you can instead create renamed batch files that will call the current program.
Instead of renaming the executable which will break a lot of thing including pip, create the file python2.bat in the same directory as the python2.exe. Then add the following line:
%~dp0python %*
What does this archaic syntax mean? Well, it's a batch script, (Windows version of bash). %~dp0 gets the current directory and %* will just pass all the arguments to python that were passed to the script.
Repeat for python3.bat
You can also do the same for pip and other utilities, just replace the word python in the file with pip or whathever the filename. The alias will be whatever the file is named.
Best of all, when added to the PATH, Windows ignores the extension so running
python3
Will launch the python3 version and and the command python2 will launch the python2 version.
BTW, this is the same technique Spyder uses to add itself to the path on Windows. :)
Sorry for answering it bit late; There is a pre-defined function in the Angular Routing Documentation which helps us in routing with a hashtag to page anchor i.e, anchorScrolling: 'enabled'
Step-1:- First Import the RouterModule in the app.module.ts file:-
imports:[
BrowserModule,
FormsModule,
RouterModule.forRoot(routes,{
anchorScrolling: 'enabled'
})
],
Step-2:- Go to the HTML Page, Create the navigation and add two important attributes like [routerLink] and fragment for matching the respective Div ID's:-
<ul>
<li> <a [routerLink] = "['/']" fragment="home"> Home </a></li>
<li> <a [routerLink] = "['/']" fragment="about"> About Us </a></li>
<li> <a [routerLink] = "['/']" fragment="contact"> Contact Us </a></li>
</ul>
Step-3:- Create a section/div by matching the ID name with the fragment:-
<section id="home" class="home-section">
<h2> HOME SECTION </h2>
</section>
<section id="about" class="about-section">
<h2> ABOUT US SECTION </h2>
</section>
<section id="contact" class="contact-section">
<h2> CONTACT US SECTION </h2>
</section>
For your reference, I have added the example below by creating a small demo which helps to solve your problem.
Let's say I have Table1
with primary key _id
and a boolean column doc_availability
; Table2
with foreign key _id
and DateTime column last_update
and I want to change the availability of a document with _id
14 in Table1
to 0 i.e unavailable and update Table2
with the timestamp when the document was last updated. The following query would do the task:
UPDATE Table1, Table2
SET doc_availability = 0, last_update = NOW()
WHERE Table1._id = Table2._id AND Table1._id = 14
If you are using the new support library for 5.1 in android studio, you can instead use this on your AppCompatActivity
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.mipmap.ic_arrow_back_white_24dp);
actionBar.setDisplayShowHomeEnabled(true);
cheers.
<head>
<script type="text/javascript">
<%=YourScript %>
function functionname1(arg1,arg2){content}
</script>
</head>
public string YourScript = "";
public string functionname(arg)
{
if (condition)
{
YourScript = "functionname1(arg1,arg2);";
}
}
If you don't want 'a' in the index
In :
col = ['a','b','c']
data = DataFrame([[1,2,3],[10,11,12],[20,21,22]],columns=col)
data
Out:
a b c
0 1 2 3
1 10 11 12
2 20 21 22
In :
data2 = data.set_index('a')
Out:
b c
a
1 2 3
10 11 12
20 21 22
In :
data2.index.name = None
Out:
b c
1 2 3
10 11 12
20 21 22
I just delete my application temp data from this path
C:/Windows/Microsoft.NET/Framework/v4.0.30319/Temporary ASP.NET Files
Problem resolve
You need to set more fields then just border-width. The style basically puts the border on the page. Width controls the thickness, and color tells it what color to make the border.
border-style: solid; border-width:thin; border-color: #FFFFFF;
I came here because I had the same problem.
What was the problem for me was that the procedure was defined in the package body, but not in the package header.
I was executing my function with a lose BEGIN END statement.
SELECT to_char(to_date(month,'yyyy-mm'),'Mon yyyy'), nos
FROM (SELECT to_char(credit_date,'yyyy-mm') MONTH,count(*) nos
FROM HCN
WHERE TRUNC(CREDIT_dATE) BEtween '01-jul-2014' AND '30-JUN-2015'
AND CATEGORYCODECFR=22
--AND CREDIT_NOTE_NO IS NOT NULL
AND CANCELDATE IS NULL
GROUP BY to_char(credit_date,'yyyy-mm')
ORDER BY to_char(credit_date,'yyyy-mm') ) mm
Output:
Jul 2014 49
Aug 2014 35
Sep 2014 57
Oct 2014 50
Nov 2014 45
Dec 2014 88
Jan 2015 131
Feb 2015 112
Mar 2015 76
Apr 2015 45
May 2015 49
Jun 2015 40
Steps to start Apache httpd.exe (I am using x64 VC11 example here)
http://www.apachelounge.com/download/VC11/
Be sure that you have installed Visual C++ Redistributable for Visual Studio 2012 : VC11 vcredist_x64/86.exe
http://www.microsoft.com/en-us/download/details.aspx?id=30679
You may need to have Visual Studio 2012 Update 3 (VS2012.3)
http://www.microsoft.com/en-us/download/details.aspx?id=30679 (vcredirect.exe)
http://support.microsoft.com/kb/2835600
Unzip httpd-2.4.4-win64-VC11.zip and copy paste in
C:\Apache24
Unzip modules-2.4-win64-VC11.zip and copy paste them in
C:\Apache24\modules
http://www.apachelounge.com/viewtopic.php?p=25091
For further info on the modules see the Apache Lounge VC10 Win64 download page and/or the readme in the .zip's there.
http://www.apachelounge.com/download/win64/
In
C:\Apache24\conf\httpd.conf
un-comment (remove # sign) starting below this like copy pasted list in here
# Example:
# LoadModule foo_module modules/mod_foo.so
LoadModule access_compat_module modules/mod_access_compat.so
LoadModule actions_module modules/mod_actions.so
LoadModule alias_module modules/mod_alias.so
LoadModule allowmethods_module modules/mod_allowmethods.so
LoadModule asis_module modules/mod_asis.so
LoadModule auth_basic_module modules/mod_auth_basic.so
LoadModule auth_digest_module modules/mod_auth_digest.so
LoadModule authn_anon_module modules/mod_authn_anon.so
LoadModule authn_core_module modules/mod_authn_core.so
LoadModule authn_dbd_module modules/mod_authn_dbd.so
LoadModule authn_dbm_module modules/mod_authn_dbm.so
LoadModule authn_file_module modules/mod_authn_file.so
LoadModule authn_socache_module modules/mod_authn_socache.so
LoadModule authnz_ldap_module modules/mod_authnz_ldap.so
LoadModule authz_core_module modules/mod_authz_core.so
LoadModule authz_dbd_module modules/mod_authz_dbd.so
LoadModule authz_dbm_module modules/mod_authz_dbm.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule authz_owner_module modules/mod_authz_owner.so
LoadModule authz_user_module modules/mod_authz_user.so
LoadModule autoindex_module modules/mod_autoindex.so
LoadModule buffer_module modules/mod_buffer.so
LoadModule cache_module modules/mod_cache.so
LoadModule cache_disk_module modules/mod_cache_disk.so
LoadModule cern_meta_module modules/mod_cern_meta.so
LoadModule cgi_module modules/mod_cgi.so
LoadModule charset_lite_module modules/mod_charset_lite.so
LoadModule data_module modules/mod_data.so
LoadModule dav_module modules/mod_dav.so
LoadModule dav_fs_module modules/mod_dav_fs.so
LoadModule dav_lock_module modules/mod_dav_lock.so
LoadModule dbd_module modules/mod_dbd.so
LoadModule deflate_module modules/mod_deflate.so
LoadModule dir_module modules/mod_dir.so
LoadModule dumpio_module modules/mod_dumpio.so
LoadModule env_module modules/mod_env.so
LoadModule expires_module modules/mod_expires.so
LoadModule ext_filter_module modules/mod_ext_filter.so
LoadModule file_cache_module modules/mod_file_cache.so
LoadModule filter_module modules/mod_filter.so
LoadModule headers_module modules/mod_headers.so
LoadModule heartbeat_module modules/mod_heartbeat.so
LoadModule heartmonitor_module modules/mod_heartmonitor.so
LoadModule ident_module modules/mod_ident.so
LoadModule imagemap_module modules/mod_imagemap.so
LoadModule include_module modules/mod_include.so
LoadModule info_module modules/mod_info.so
LoadModule isapi_module modules/mod_isapi.so
LoadModule lbmethod_bybusyness_module modules/mod_lbmethod_bybusyness.so
LoadModule lbmethod_byrequests_module modules/mod_lbmethod_byrequests.so
LoadModule lbmethod_bytraffic_module modules/mod_lbmethod_bytraffic.so
LoadModule lbmethod_heartbeat_module modules/mod_lbmethod_heartbeat.so
LoadModule ldap_module modules/mod_ldap.so
LoadModule logio_module modules/mod_logio.so
LoadModule log_config_module modules/mod_log_config.so
LoadModule log_debug_module modules/mod_log_debug.so
LoadModule log_forensic_module modules/mod_log_forensic.so
LoadModule lua_module modules/mod_lua.so
LoadModule mime_module modules/mod_mime.so
LoadModule mime_magic_module modules/mod_mime_magic.so
LoadModule negotiation_module modules/mod_negotiation.so
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule proxy_connect_module modules/mod_proxy_connect.so
LoadModule proxy_express_module modules/mod_proxy_express.so
LoadModule proxy_fcgi_module modules/mod_proxy_fcgi.so
LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
LoadModule proxy_html_module modules/mod_proxy_html.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule proxy_scgi_module modules/mod_proxy_scgi.so
LoadModule ratelimit_module modules/mod_ratelimit.so
LoadModule reflector_module modules/mod_reflector.so
LoadModule remoteip_module modules/mod_remoteip.so
LoadModule request_module modules/mod_request.so
LoadModule reqtimeout_module modules/mod_reqtimeout.so
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule sed_module modules/mod_sed.so
LoadModule session_module modules/mod_session.so
LoadModule session_cookie_module modules/mod_session_cookie.so
LoadModule session_crypto_module modules/mod_session_crypto.so
LoadModule session_dbd_module modules/mod_session_dbd.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule slotmem_plain_module modules/mod_slotmem_plain.so
LoadModule slotmem_shm_module modules/mod_slotmem_shm.so
LoadModule socache_dbm_module modules/mod_socache_dbm.so
LoadModule socache_memcache_module modules/mod_socache_memcache.so
LoadModule socache_shmcb_module modules/mod_socache_shmcb.so
LoadModule speling_module modules/mod_speling.so
LoadModule ssl_module modules/mod_ssl.so
LoadModule status_module modules/mod_status.so
LoadModule substitute_module modules/mod_substitute.so
LoadModule unique_id_module modules/mod_unique_id.so
LoadModule userdir_module modules/mod_userdir.so
LoadModule usertrack_module modules/mod_usertrack.so
LoadModule version_module modules/mod_version.so
LoadModule vhost_alias_module modules/mod_vhost_alias.so
LoadModule watchdog_module modules/mod_watchdog.so
LoadModule xml2enc_module modules/mod_xml2enc.so
Then find
C:\Apache24\bin\ApacheMonitor.exe
and double click on it.
Then in Command Prompt (CMD.exe) type
C:\Apache24\bin\httpd.exe
and press enter. It shows any error remaining.
Build with the latest Update 3 Visual Studio® 2012 aka VC11. VC11 has improvements, fixes and optimizations over VC10 in areas like Performance, MemoryManagement and Stability. For example code quality tuning and improvements done across different code generation areas for "speed". And makes more use of modern processors and win7, win8, 2008 and Server 2012 internal features.
The VC11 binaries loads VC11, VC10 and VC9 modules, and does not run on XP and 2003. Minimum system required: Windows 7 SP1, Windows 8 / 8.1, Windows Vista SP2, Windows Server 2008 R2 SP1, Windows Server 2012 / R2
After you have downloaded and before you attempt to install it, you should make sure that it is intact and has not been tampered with. Use the PGP Signature and/or the SHA Checksums to verify the integrity.
Thank you
In my understanding you want to match a non-blank and non-empty string, so the top answer is doing the opposite. I suggest:
(.|\s)*\S(.|\s)*
- this matches any string containing at least one non-whitespace character (the \S
in the middle). It can be preceded and followed by anything, any char or whitespace sequence (including new lines) - (.|\s)*
.
You can try it with explanation on https://regex101.com/.
Use re.findall
or re.finditer
instead.
re.findall(pattern, string)
returns a list of matching strings.
re.finditer(pattern, string)
returns an iterator over MatchObject
objects.
Example:
re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']
[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']
No need to convert. You can apply conditions on Enums inside a switch. Like so,
public enum Operator
{
PLUS,
MINUS,
MULTIPLY,
DIVIDE
}
public double Calculate(int left, int right, Operator op)
{
switch (op)
{
case Operator.PLUS: return left + right;
case Operator.MINUS: return left - right;
case Operator.MULTIPLY: return left * right;
case Operator.DIVIDE: return left / right;
default: return 0.0;
}
}
Then, call it like this:
Console.WriteLine("The sum of 5 and 5 is " + Calculate(5, 5, Operator.PLUS));
A double quote to the left of the text you want to comment.
Example:
" this is how a comment looks like in ~/.vimrc
Item[] newItemList = new Item[itemList.length+1];
//for loop to go thorough the list one by one
for(int i=0; i< itemList.length;i++){
//value is stored here in the new list from the old one
newItemList[i]=itemList[i];
}
//all the values of the itemLists are stored in a bigger array named newItemList
itemList=newItemList;
I find using these interactive tools help visualize what's happening, and whats possible
http://css3gen.com/box-shadow/
http://www.cssmatic.com/box-shadow
Edit: Check out the other tools for experimenting with the other generators and combinations. I have to remind myself sometimes that just because you can, doesn't mean you should - its easy to get carried away!
To make this easier to use, I wrote a generic extension:
public static string ToDescription<TEnum>(this TEnum EnumValue) where TEnum : struct
{
return Enumerations.GetEnumDescription((Enum)(object)((TEnum)EnumValue));
}
now I can write:
MyEnum my = MyEnum.HereIsAnother;
string description = my.ToDescription();
System.Diagnostics.Debug.Print(description);
Note: replace "Enumerations" above with your class name
Here's my attempt with Javascript and CSS3 animation So the HTML:
<div id="handle">Fade</div>
<div id="slideSource">Whatever you want images or text here</div>
The CSS3 with transitions:
div#slideSource {
opacity:1;
-webkit-transition: opacity 3s;
-moz-transition: opacity 3s;
transition: opacity 3s;
}
div#slideSource.fade {
opacity:0;
}
The Javascript part. Check if the className exists, if it does then add the class and transitions.
document.getElementById('handle').onclick = function(){
if(slideSource.className){
document.getElementById('slideSource').className = '';
} else {
document.getElementById('slideSource').className = 'fade';
}
}
Just click and it will fade in and out. I would recommend using JQuery as Itai Sagi mentioned. I left out Opera and MS, so I would recommend using prefixr to add that in the css. This is my first time posting on stackoverflow but it should work fine.
import json
array = '{"fruits": ["apple", "banana", "orange"]}'
data = json.loads(array)
print data['fruits']
# the print displays:
# [u'apple', u'banana', u'orange']
You had everything you needed. data
will be a dict, and data['fruits']
will be a list
You can try this
diff --changed-group-format='%>' --unchanged-group-format='' A1 A2
The options are documented in man diff
:
--GTYPE-group-format=GFMT
format GTYPE input groups with GFMT
and:
LTYPE is 'old', 'new', or 'unchanged'.
GTYPE is LTYPE or 'changed'.
and:
GFMT (only) may contain:
%< lines from FILE1
%> lines from FILE2
[...]
You can also use the [Required]
data annotation attribute to solve this:
public class Foo
{
public string FooId { get; set; }
public Boo Boo { get; set; }
}
public class Boo
{
public string BooId { get; set; }
[Required]
public Foo Foo {get; set; }
}
Foo
is required for Boo
.
The usual error is one tries to put Content-Type: {multipart/form-data}
into the header of the post request. That will fail, it is best to let Postman do it for you. For example:
For constants, you can use an enum, which supports retrieving its name.
The command in the keyboard shortcuts menu/editor is editor.action.jumpToBracket
there you can set it to whatever you like. There is also one called editor.action.selectToBracket
which has no shortcut by default (at least on Mac).
On the Mac editor.action.jumpToBracket
starts out as Cmd+Shift+\
and I changed it to Ctrl+] to be in line with what others say here. I did so in the hopes that I could use Ctrl+Shift+] to "Extend selection to matching bracket". That is what lead me to discover the details above. I set editor.action.selectToBracket
to Ctrl+Shift+] and got exactly the behavior I wanted.
The former is fastest. Turns out that val
is immutable, and so a new string object is created with String.ToLowerCase(), rather than just direct comparison with the string comparer. Creating a new string object can be costly if you're doing this many times a second.
Most IIS sections are locked by default but you can "unlock" them by setting the attribute overrideModeDefault
from "Deny" to "Allow" for the relevant section group by modifying the ApplicationHost.config file located in %windir%\system32\inetsrv\config
in Administrator mode
Note that your main
arguments are not correct. The standard form should be:
int main(int argc, char *argv[])
or equivalently:
int main(int argc, char **argv)
There are many ways to achieve the conversion. This is one approach:
#include <sstream>
int main(int argc, char *argv[])
{
if (argc >= 2)
{
std::istringstream iss( argv[1] );
int val;
if (iss >> val)
{
// Conversion successful
}
}
return 0;
}
On the same theme as other answers, keeping it simple
Sub PrintArray(Data As Variant, Cl As Range)
Cl.Resize(UBound(Data, 1), UBound(Data, 2)) = Data
End Sub
Sub Test()
Dim MyArray() As Variant
ReDim MyArray(1 To 3, 1 To 3) ' make it flexible
' Fill array
' ...
PrintArray MyArray, ActiveWorkbook.Worksheets("Sheet1").[A1]
End Sub
To understand the differences, you have to first understand what Node.js does to every module during runtime. Node.js creates a wrapper function for every module:
(function(exports, require, module, __filename, __dirname) {
})()
Notice the first param exports
is an empty object, and the third param module
is an object with many properties, and one of the properties is named exports
. This is what exports
comes from and what module.exports
comes from. The former one is a variable object, and the latter one is a property of module
object.
Within the module, Node.js automatically does this thing at the beginning: module.exports = exports
, and ultimately returns module.exports
.
So you can see that if you reassign some value to exports
, it won't have any effect to module.exports
. (Simply because exports
points to another new object, but module.exports
still holds the old exports
)
let exports = {};
const module = {};
module.exports = exports;
exports = { a: 1 }
console.log(module.exports) // {}
But if you updates properties of exports
, it will surely have effect on module.exports
. Because they both point to the same object.
let exports = {};
const module = {};
module.exports = exports;
exports.a = 1;
module.exports.b = 2;
console.log(module.exports) // { a: 1, b: 2 }
Also notice that if you reassign another value to module.exports
, then it seems meaningless for exports
updates. Every updates on exports
is ignored because module.exports
points to another object.
let exports = {};
const module = {};
module.exports = exports;
exports.a = 1;
module.exports = {
hello: () => console.log('hello')
}
console.log(module.exports) // { hello: () => console.log('hello')}
If All else fails. Just make sure you didn't Archive your project. That was my problem, puts the whole solution in a read only mode.
You will need a custom class loader for this, have a look at One Jar.
One-JAR lets you package a Java application together with its dependency Jars into a single executable Jar file.
It has an ant task which can simplify the building of it as well.
REFERENCE (from background)
Most developers reasonably assume that putting a dependency Jar file into their own Jar file, and adding a Class-Path attribute to the META-INF/MANIFEST will do the trick:
jarname.jar
| /META-INF
| | MANIFEST.MF
| | Main-Class: com.mydomain.mypackage.Main
| | Class-Path: commons-logging.jar
| /com/mydomain/mypackage
| | Main.class
| commons-logging.jar
Unfortunately this is does not work. The Java
Launcher$AppClassLoader
does not know how to load classes from a Jar inside a Jar with this kind ofClass-Path
. Trying to usejar:file:jarname.jar!/commons-logging.jar
also leads down a dead-end. This approach will only work if you install (i.e. scatter) the supporting Jar files into the directory where the jarname.jar file is installed.
As I got this case at my own and the answers here didn't help me, my situation was because of I downgraded the targetSdkVersion
in gradle app module file from 24 to 22 for some reason, and apparently the apk doesn't accept another one with downgraded targetSdkVersion
to be installed over it.
So, once I changed it back to 24 the error disappeared and app installed correctly.
You can do simple check
if(!a) {
// do something when `a` is not undefined, null, ''.
}
You can not ask for instance during configuration phase - you can ask only for providers.
var app = angular.module('modx', []);
// configure stuff
app.config(function($routeProvider, $locationProvider) {
// you can inject any provider here
});
// run blocks
app.run(function($rootScope) {
// you can inject any instance here
});
See http://docs.angularjs.org/guide/module for more info.
using System;
using System.ComponentModel;
using System.Threading;
namespace BackGroundWorkerExample
{
class Program
{
private static BackgroundWorker backgroundWorker;
static void Main(string[] args)
{
backgroundWorker = new BackgroundWorker
{
WorkerReportsProgress = true,
WorkerSupportsCancellation = true
};
backgroundWorker.DoWork += backgroundWorker_DoWork;
//For the display of operation progress to UI.
backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged;
//After the completation of operation.
backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
backgroundWorker.RunWorkerAsync("Press Enter in the next 5 seconds to Cancel operation:");
Console.ReadLine();
if (backgroundWorker.IsBusy)
{
backgroundWorker.CancelAsync();
Console.ReadLine();
}
}
static void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < 200; i++)
{
if (backgroundWorker.CancellationPending)
{
e.Cancel = true;
return;
}
backgroundWorker.ReportProgress(i);
Thread.Sleep(1000);
e.Result = 1000;
}
}
static void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
Console.WriteLine("Completed" + e.ProgressPercentage + "%");
}
static void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
Console.WriteLine("Operation Cancelled");
}
else if (e.Error != null)
{
Console.WriteLine("Error in Process :" + e.Error);
}
else
{
Console.WriteLine("Operation Completed :" + e.Result);
}
}
}
}
Also, referr the below link you will understand the concepts of Background
:
http://www.c-sharpcorner.com/UploadFile/1c8574/threads-in-wpf/
I am sure we have a lot of good answers here. But, I just thought of adding the way I have used enumerated types
package main
import "fmt"
type Enum interface {
name() string
ordinal() int
values() *[]string
}
type GenderType uint
const (
MALE = iota
FEMALE
)
var genderTypeStrings = []string{
"MALE",
"FEMALE",
}
func (gt GenderType) name() string {
return genderTypeStrings[gt]
}
func (gt GenderType) ordinal() int {
return int(gt)
}
func (gt GenderType) values() *[]string {
return &genderTypeStrings
}
func main() {
var ds GenderType = MALE
fmt.Printf("The Gender is %s\n", ds.name())
}
This is by far one of the idiomatic ways we could create Enumerated types and use in Go.
Edit:
Adding another way of using constants to enumerate
package main
import (
"fmt"
)
const (
// UNSPECIFIED logs nothing
UNSPECIFIED Level = iota // 0 :
// TRACE logs everything
TRACE // 1
// INFO logs Info, Warnings and Errors
INFO // 2
// WARNING logs Warning and Errors
WARNING // 3
// ERROR just logs Errors
ERROR // 4
)
// Level holds the log level.
type Level int
func SetLogLevel(level Level) {
switch level {
case TRACE:
fmt.Println("trace")
return
case INFO:
fmt.Println("info")
return
case WARNING:
fmt.Println("warning")
return
case ERROR:
fmt.Println("error")
return
default:
fmt.Println("default")
return
}
}
func main() {
SetLogLevel(INFO)
}
The easy way to change version is first to check your available version using nvm ls then select version from the list nvm use version
Installing the "security" package extras for requests
solved for me:
sudo apt-get install libffi-dev
sudo pip install -U requests[security]
There is currently no solution to your problem, as far as I know: the function that you give to map()
must be accessible through an import of your module. This is why robert's code works: the function f()
can be obtained by importing the following code:
def f(x):
return x*x
class Calculate(object):
def run(self):
p = Pool()
return p.map(f, [1,2,3])
if __name__ == '__main__':
cl = Calculate()
print cl.run()
I actually added a "main" section, because this follows the recommendations for the Windows platform ("Make sure that the main module can be safely imported by a new Python interpreter without causing unintended side effects").
I also added an uppercase letter in front of Calculate
, so as to follow PEP 8. :)
My new answer is to use ffmpeg to transcode the .mov
like ffmpeg -i sourceFile.mov destinationFile.mp4
. Do same for the webm format.
OLD Answer: Here's what you do:
<video controls>
<source src="somevideo.webm" type="video/webm">
<source src="somevideo.mp4" type="video/mp4">
I'm sorry; your browser doesn't support HTML5 video in WebM with VP8/VP9 or MP4 with H.264.
<!-- You can embed a Flash player here, to play your mp4 video in older browsers -->
</video>
<video>
element with CSS to suit your needs. For example Materializecss has a simple helper class to render the video nicely across device types.Here is email code I used in one of my databases. I just made variables for the person I wanted to send it to, CC, subject, and the body. Then you just use the DoCmd.SendObject command. I also set it to "True" after the body so you can edit the message before it automatically sends.
Public Function SendEmail2()
Dim varName As Variant
Dim varCC As Variant
Dim varSubject As Variant
Dim varBody As Variant
varName = "[email protected]"
varCC = "[email protected], [email protected]"
'separate each email by a ','
varSubject = "Hello"
'Email subject
varBody = "Let's get ice cream this week"
'Body of the email
DoCmd.SendObject , , , varName, varCC, , varSubject, varBody, True, False
'Send email command. The True after "varBody" allows user to edit email before sending.
'The False at the end will not send it as a Template File
End Function
Adding to @Narendra solution...
IMPORTANT: When working with fragments, navigations is closely related to host acivity so, you can't justo jump from fragment to fragment without implement that fragment class in host Activity.
Sample:
public class MyHostActivity extends AppCompatActivity implements MyFragmentOne.OnFragmentInteractionListener {
Also, check your host activity has the next override function:
@Override
public void onFragmentInteraction(Uri uri) {}
Hope this helps...
By some reason sql server save some identity columns in different tables, the code that work for me, is the following:
select TABLE_NAME tabla,COLUMN_NAME columna
from INFORMATION_SCHEMA.COLUMNS
where COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
union all
select o.name tabla, c.name columna
from sys.objects o
inner join sys.columns c on o.object_id = c.object_id
where c.is_identity = 1
You have the same result when calling .size() method or .length property but the .length property is preferred because it doesn't have the overhead of a function call. So the best way:
$("#mylist li").length
Angular 2 and Angular 4
In a ngFor loop it must be look like this:
<div class="column" *ngFor="let u of events ">
<div class="thumb">
<img src="assets/uploads/{{u.image}}">
<h4>{{u.name}}</h4>
</div>
<div class="info">
<img src="assets/uploads/{{u.image}}">
<h4>{{u.name}}</h4>
<p>{{u.text}}</p>
</div>
</div>
If you're looking for something as nice as Python's x[-1] notation, I think you're out of luck. The standard idiom is
x[length(x)]
but it's easy enough to write a function to do this:
last <- function(x) { return( x[length(x)] ) }
This missing feature in R annoys me too!
extend: function(){
if(arguments.length === 0){ return; }
var x = arguments.length === 1 ? this : arguments[0];
var y;
for(var i = 1, len = arguments.length; i < len; i++) {
y = arguments[i];
for(var key in y){
if(!(y[key] instanceof Function)){
x[key] = y[key];
}
}
};
return x;
}
Extends multiple json objects (ignores functions):
extend({obj: 'hej'}, {obj2: 'helo'}, {obj3: {objinside: 'yes'}});
Will result in a single json object
This is quite simple really.
-> This is centered Text <-
So taking that in mind you can apply this to the img syntax.
->![alt text](/link/to/img)<-
Correct syntax looks like this. See MSDN.
SELECT *
FROM [FAEB].[dbo].[ExportaComisiones] AS f
JOIN [zCredifiel].[dbo].[optPerson] AS p
ON p.vTreasuryId COLLATE Latin1_General_CI_AS = f.RFC COLLATE Latin1_General_CI_AS
I was thundered when the following code worked.
import os
for file in os.listdir("../FutureBookList"):
if file.endswith(".adoc"):
filename, file_extension = os.path.splitext(file)
print(filename)
print(file_extension)
continue
else:
continue
So, I checked the documentation and it says:
Changed in version 3.6: Accepts a path-like object.
An object representing a file system path. A path-like object is either a str or...
I did a little more digging and the following also works:
with open("../FutureBookList/file.txt") as file:
data = file.read()
I think there is a difference between whether something SHOULD be unique or MUST be unique (i.e. enforced by web browsers).
Should IDs be unique? YES.
Must IDs be unique? NO, at least IE and FireFox allow multiple elements to have the same ID.
I ended up with this slightly different version:
var dirty = false;
window.onbeforeunload = function() {
return dirty ? "If you leave this page you will lose your unsaved changes." : null;
}
Elsewhere I set the dirty flag to true when the form gets dirtied (or I otherwise want to prevent navigating away). This allows me to easily control whether or not the user gets the Confirm Navigation prompt.
With the text in the selected answer you see redundant prompts:
Best way is using BoxDecoration()
Advantage
Disadvantage
BoxDecoration
only use with Container
widget so you want to wrap your widget in Container()
Example
Container(
margin: EdgeInsets.all(10),
padding: EdgeInsets.all(10),
alignment: Alignment.center,
decoration: BoxDecoration(
color: Colors.orange,
border: Border.all(
color: Colors.pink[800],// set border color
width: 3.0), // set border width
borderRadius: BorderRadius.all(
Radius.circular(10.0)), // set rounded corner radius
boxShadow: [BoxShadow(blurRadius: 10,color: Colors.black,offset: Offset(1,3))]// make rounded corner of border
),
child: Text("My demo styling"),
)
var selectoption = document.getElementById("dropdown");
var optionText = selectoption.options[selectoption.selectedIndex].text;
Here is the Complete solution
#First Datasource (DB1)
db1.datasource.url: url
db1.datasource.username:user
db1.datasource.password:password
#Second Datasource (DB2)
db2.datasource.url:url
db2.datasource.username:user
db2.datasource.password:password
Since we are going to get access two different databases (db1, db2), we need to configure each data source configuration separately like:
public class DB1_DataSource {
@Autowired
private Environment env;
@Bean
@Primary
public LocalContainerEntityManagerFactoryBean db1EntityManager() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(db1Datasource());
em.setPersistenceUnitName("db1EntityManager");
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
HashMap<string, object=""> properties = new HashMap<>();
properties.put("hibernate.dialect",
env.getProperty("hibernate.dialect"));
properties.put("hibernate.show-sql",
env.getProperty("jdbc.show-sql"));
em.setJpaPropertyMap(properties);
return em;
}
@Primary
@Bean
public DataSource db1Datasource() {
DriverManagerDataSource dataSource
= new DriverManagerDataSource();
dataSource.setDriverClassName(
env.getProperty("jdbc.driver-class-name"));
dataSource.setUrl(env.getProperty("db1.datasource.url"));
dataSource.setUsername(env.getProperty("db1.datasource.username"));
dataSource.setPassword(env.getProperty("db1.datasource.password"));
return dataSource;
}
@Primary
@Bean
public PlatformTransactionManager db1TransactionManager() {
JpaTransactionManager transactionManager
= new JpaTransactionManager();
transactionManager.setEntityManagerFactory(
db1EntityManager().getObject());
return transactionManager;
}
}
Second Datasource :
public class DB2_DataSource {
@Autowired
private Environment env;
@Bean
public LocalContainerEntityManagerFactoryBean db2EntityManager() {
LocalContainerEntityManagerFactoryBean em
= new LocalContainerEntityManagerFactoryBean();
em.setDataSource(db2Datasource());
em.setPersistenceUnitName("db2EntityManager");
HibernateJpaVendorAdapter vendorAdapter
= new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
HashMap<string, object=""> properties = new HashMap<>();
properties.put("hibernate.dialect",
env.getProperty("hibernate.dialect"));
properties.put("hibernate.show-sql",
env.getProperty("jdbc.show-sql"));
em.setJpaPropertyMap(properties);
return em;
}
@Bean
public DataSource db2Datasource() {
DriverManagerDataSource dataSource
= new DriverManagerDataSource();
dataSource.setDriverClassName(
env.getProperty("jdbc.driver-class-name"));
dataSource.setUrl(env.getProperty("db2.datasource.url"));
dataSource.setUsername(env.getProperty("db2.datasource.username"));
dataSource.setPassword(env.getProperty("db2.datasource.password"));
return dataSource;
}
@Bean
public PlatformTransactionManager db2TransactionManager() {
JpaTransactionManager transactionManager
= new JpaTransactionManager();
transactionManager.setEntityManagerFactory(
db2EntityManager().getObject());
return transactionManager;
}
}
Here you can find the complete Example on my blog : Spring Boot with Multiple DataSource Configuration
Like that
var purchCount = (from purchase in myBlaContext.purchases select purchase).Count();
or even easier
var purchCount = myBlaContext.purchases.Count()
This one would also work:
google.maps.event.addListener(marker, 'click', function() {
if(!marker.open){
infowindow.open(map,marker);
marker.open = true;
}
else{
infowindow.close();
marker.open = false;
}
});
Which will open an infoWindow when clicked on it, close it when clicked on it if it was opened.
Also having seen Logan's solution, these 2 can be combined into this:
google.maps.event.addListener(marker, 'click', function() {
if(!marker.open){
infowindow.open(map,marker);
marker.open = true;
}
else{
infowindow.close();
marker.open = false;
}
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
marker.open = false;
});
});
Which will open an infoWindow when clicked on it, close it when clicked on it and it was opened, and close it if it's clicked anywhere on the map and the infoWindows was opened.
For me, ASP.NET 5 is not yet required, I removed update, and then reinstalled ASP.NET 4.5. It's a bit tricky:
No longer follow the notification of update in Visual Studio 2015!!!
The only option I can think of is using width:100%
. If you want to have a padding on the input field too, than just place a container label
around it, move the formatting to that label instead, while also specify the padding to the label. Input fields are rigid.
css files do not support conditional statements.
If you want something to look one of two ways, depending on some condition, give it a suitable class using your server side scripting language or javascript. eg
<div class="oh-yes"></div>
<div class="hell-no"></div>
It depends on how and when you want to redirect the user to another page.
If you want to instantly redirect a user to another page without him seeing anything of a site in between, you should use the PHP header
redirect method.
If you have a Javascript and some action of the user has to result in him entering another page, that is when you should use window.location
.
The meta
tag refresh is often used on download sites whenever you see these "Your download should start automatically" messages. You can let the user load a page, wait for a certain amount of time, then redirect him (e.g. to a to-be-downloaded file) without Javascript.
Using LINQ to SQL:
XDocument
.Load(resxFileName)
.Descendants()
.Where(_ => _.Name == "data")
.Select(_ => $"{ _.Attributes().First(a => a.Name == "name").Value} - {_.Value}");
Or spin Linux instance for SFTP Gateway in your AWS infrastructure that saves uploaded files to your Amazon S3 bucket.
Supported by Thorntech
You can always use TO_NUMBER() function in order to remove this error.This can be included as INSERT INTO employees phone_number values(TO_NUMBER('0419 853 694');
Remove these two lines:
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
XMLHttpRequest isn't allowed to set these headers, they are being set automatically by the browser. The reason is that by manipulating these headers you might be able to trick the server into accepting a second request through the same connection, one that wouldn't go through the usual security checks - that would be a security vulnerability in the browser.
Try:
public class Main {
public static void main(String[] args) {
String line = "foo,bar,c;qual=\"baz,blurb\",d;junk=\"quux,syzygy\"";
String[] tokens = line.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1);
for(String t : tokens) {
System.out.println("> "+t);
}
}
}
Output:
> foo
> bar
> c;qual="baz,blurb"
> d;junk="quux,syzygy"
In other words: split on the comma only if that comma has zero, or an even number of quotes ahead of it.
Or, a bit friendlier for the eyes:
public class Main {
public static void main(String[] args) {
String line = "foo,bar,c;qual=\"baz,blurb\",d;junk=\"quux,syzygy\"";
String otherThanQuote = " [^\"] ";
String quotedString = String.format(" \" %s* \" ", otherThanQuote);
String regex = String.format("(?x) "+ // enable comments, ignore white spaces
", "+ // match a comma
"(?= "+ // start positive look ahead
" (?: "+ // start non-capturing group 1
" %s* "+ // match 'otherThanQuote' zero or more times
" %s "+ // match 'quotedString'
" )* "+ // end group 1 and repeat it zero or more times
" %s* "+ // match 'otherThanQuote'
" $ "+ // match the end of the string
") ", // stop positive look ahead
otherThanQuote, quotedString, otherThanQuote);
String[] tokens = line.split(regex, -1);
for(String t : tokens) {
System.out.println("> "+t);
}
}
}
which produces the same as the first example.
As mentioned by @MikeFHay in the comments:
I prefer using Guava's Splitter, as it has saner defaults (see discussion above about empty matches being trimmed by
String#split()
, so I did:Splitter.on(Pattern.compile(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"))
This work well on Windows:
npm install --save-dev copyfiles
package.json
I have a copy task : "copy": "copyfiles -u 1 ./app/index.html ./deploy"
This move my index.html from the app folder into the deploy folder.
<object>.__class__.__name__
http://momentjs.com/ or https://date-fns.org/
From Moment docs:
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // =1
or to include the start:
a.diff(b, 'days')+1 // =2
Beats messing with timestamps and time zones manually.
Depending on your specific use case, you can either
a/b.startOf('day')
and/or a/b.endOf('day')
to force the diff to be inclusive or exclusive at the "ends" (as suggested by @kotpal in the comments). true
to get a floating point diff which you can then Math.floor
, Math.ceil
or Math.round
as needed.'seconds'
instead of 'days'
and then dividing by 24*60*60
.Please take a look here:
1) You can use this with Windows (incl. MinGW) as well as Linux. Alternative you can only use the code as an example.
2) Step-by-step tutorial how to use serial ports on windows
3) You can use this literally on MinGW
Here's some very, very simple code (without any error handling or settings):
#include <windows.h>
/* ... */
// Open serial port
HANDLE serialHandle;
serialHandle = CreateFile("\\\\.\\COM1", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
// Do some basic settings
DCB serialParams = { 0 };
serialParams.DCBlength = sizeof(serialParams);
GetCommState(serialHandle, &serialParams);
serialParams.BaudRate = baudrate;
serialParams.ByteSize = byteSize;
serialParams.StopBits = stopBits;
serialParams.Parity = parity;
SetCommState(serialHandle, &serialParams);
// Set timeouts
COMMTIMEOUTS timeout = { 0 };
timeout.ReadIntervalTimeout = 50;
timeout.ReadTotalTimeoutConstant = 50;
timeout.ReadTotalTimeoutMultiplier = 50;
timeout.WriteTotalTimeoutConstant = 50;
timeout.WriteTotalTimeoutMultiplier = 10;
SetCommTimeouts(serialHandle, &timeout);
Now you can use WriteFile()
/ ReadFile()
to write / read bytes.
Don't forget to close your connection:
CloseHandle(serialHandle);
This answer might be stupid, but I spent quite some time to figure it out.
What happened to me was I didn't set display: flex
to the container. And of course, justify-content
won't work without a container with that property.
Some easy ways:
Use Apache's digest authorization.
Use lighttpd's digest authorization.
Use php's header digest authorization.
If you want you can also make it so only certain ip addresses can login.. :) really easy with lighttpd
Update: I will post some examples soon, so don't vote down for no examples, i just need to get some down for this answer.
If you want to use sessions the following is the best way to go:
# admin.php
session_start();
if(!$_SESSION["AUTH"])
require_once "login.php";
# Do stuff, we are logged in..
# login.php
session_start();
if($_REQUEST["username"] == "user" && $_REQUEST["password"] == "pass")
$_SESSION["AUTH"] = true;
else $_SESSION["AUTH"] = false; # This logs you out if you visit this login script page without login details.
if($_SESSION["AUTH"])
require_once "admin.php";
This method does not contain the examples for above but you seamed interested in this method. The other method examples are still to come, I have not got enough time to get it for apache or lighttpd settings and the php header auth: http://php.net/manual/en/features.http-auth.php Will do.
A follow up to vincent's answer.
Not a direct answer to the question since the question is using a form.
For me, it wasn't the name of the input tag that was used, but the name when appending the file to the formData.
front end file
var formData = new FormData();
formData.append('<NAME>',this.new_attachments)
web service file:
app.post('/upload', upload.single('<NAME>'),...
I found that these instructions were not enough. I also had to search through the code files for models, controllers, and views as well as the AppStart files to change the namespace.
Since I was copying my project not just renaming it, I also had to go into the applicationhost.config for IIS express and recreate the bindings using different port numbers and change the physical directory as well.
Take a look at this video tutorial about Autolayout, they explain it carefully
To send a Whatsapp message from a website, use the below URL.
Here the phone and text are parameters were one of them is required.
This URL is also can be used. It displays a blank screen if there is no application found!
URL: whatsapp://send?text=The text to share!
Note: All the above will work in web, only if WhatsApp desktop app is installed
Use either the <button>
element or use an <input type="button"/>
.
Piere's answer is correct but one issue is that bulk_save_objects
by default does not return the primary keys of the objects, if that is of concern to you. Set return_defaults
to True
to get this behavior.
The documentation is here.
foos = [Foo(bar='a',), Foo(bar='b'), Foo(bar='c')]
session.bulk_save_objects(foos, return_defaults=True)
for foo in foos:
assert foo.id is not None
session.commit()
In your case it should be:
Select convert(datetime,convert(varchar(10),GRADUATION_DATE,120)) as
'GRADUATION_DATE' from mydb
This is a known bug. flexWrap: 'wrap'
didn't work for me but this solution seems to work for most people
Code
<View style={styles.container}>
<Text>Some text</Text>
</View>
Styles
export default StyleSheet.create({
container: {
width: 0,
flexGrow: 1,
flex: 1,
}
});