Use psexec -s
The s switch will cause it to run under system account which is the same as running an elevated admin prompt. just used it to enable WinRM remotely.
You have an extra -c
you need to get rid of:
psexec -u administrator -p force \\135.20.230.160 -s -d cmd.exe /c "C:\Amitra\bogus.bat"
I had a case where AV was quarantining Psexec - had to disable On-access scanning
If one wants to have the conf\logging.properties
read one must (see also here) dump this file into the Servers\Tomcat v7.0 Server at localhost-config\
folder and then add the lines :
-Djava.util.logging.config.file="${workspace_loc}\Servers\Tomcat v7.0 Server at localhost-config\logging.properties" -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
to the VM arguments of the launch configuration one is using.
This may have taken a restart or two (or not) but finally I saw in the console in bright red :
FINE: No TLD files were found in [file:/C:/Dropbox/eclipse_workspaces/javaEE/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/ted2012/WEB-INF/lib/logback-classic-1.0.7.jar]. Consider adding the JAR to the tomcat.util.scan.DefaultJarScanner.jarsToSkip or org.apache.catalina.startup.TldConfig.jarsToSkip property in CATALINA_BASE/conf/catalina.properties file. //etc
I still don't know when exactly this EDIT: from the comment by @Stephan: "The FINE warning appears each time any change is done in the JSP file".FINE
warning appears - does not appear immediately on tomcat launch
Bonus: To make the warning go away add in catalina.properties
:
# Additional JARs (over and above the default JARs listed above) to skip when
# scanning for TLDs. The list must be a comma separated list of JAR file names.
org.apache.catalina.startup.TldConfig.jarsToSkip=logback-classic-1.0.7.jar,\
joda-time-2.1.jar,joda-time-2.1-javadoc.jar,mysql-connector-java-5.1.24-bin.jar,\
logback-core-1.0.7.jar,javax.servlet.jsp.jstl-api-1.2.1.jar
global $woocommerce;
var_dump($woocommerce->customer->get_country());
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product = new WC_product($cart_item['product_id']);
var_dump($product);
}
Your sample does not work in IE for me, you have to specify Doctype header in your document to render your page in standard way in IE to use the content CSS property:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<head>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<html>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>
</html>
Second way is to use CSS 3 selectors
li:not(:last-of-type):after
{
content: " |";
}
But you still need to specify Doctype
And third way is to use JQuery with some script like following:
<script type="text/javascript" src="jquery-1.4.1.js"></script>
<link href="style2.css" rel="stylesheet" type="text/css">
</head>
<html>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>
<script type="text/javascript">
$(document).ready(function () {
$("li:not(:last)").append(" | ");
});
</script>
Advantage of third way is that you dont have to specify doctype and jQuery will take care of compatibility.
You can't use IF like that. You can do what you want with AND and OR:
SELECT t.first_name,
t.last_name,
t.employid,
t.status
FROM employeetable t
WHERE ((status_flag = STATUS_ACTIVE AND t.status = 'A')
OR (status_flag = STATUS_INACTIVE AND t.status = 'T')
OR (source_flag = SOURCE_FUNCTION AND t.business_unit = 'production')
OR (source_flag = SOURCE_USER AND t.business_unit = 'users'))
AND t.first_name LIKE firstname
AND t.last_name LIKE lastname
AND t.employid LIKE employeeid;
async function main() {
var getQuoteError
var quote = await getQuote().catch(err => { getQuoteError = err }
if (getQuoteError) return console.error(err)
console.log(quote)
}
Alternatively instead of declaring a possible var to hold an error at the top you can do
if (quote instanceof Error) {
// ...
}
Though that won't work if something like a TypeError or Reference error is thrown. You can ensure it is a regular error though with
async function main() {
var quote = await getQuote().catch(err => {
console.error(err)
return new Error('Error getting quote')
})
if (quote instanceOf Error) return quote // get out of here or do whatever
console.log(quote)
}
My preference for this is wrapping everything in a big try-catch block where there's multiple promises being created can make it cumbersome to handle the error specifically to the promise that created it. With the alternative being multiple try-catch blocks which I find equally cumbersome
While astype
is probably the "best" option there are several other ways to convert it to an integer array. I'm using this arr
in the following examples:
>>> import numpy as np
>>> arr = np.array([1,2,3,4], dtype=float)
>>> arr
array([ 1., 2., 3., 4.])
int*
functions from NumPy>>> np.int64(arr)
array([1, 2, 3, 4])
>>> np.int_(arr)
array([1, 2, 3, 4])
*array
functions themselves:>>> np.array(arr, dtype=int)
array([1, 2, 3, 4])
>>> np.asarray(arr, dtype=int)
array([1, 2, 3, 4])
>>> np.asanyarray(arr, dtype=int)
array([1, 2, 3, 4])
astype
method (that was already mentioned but for completeness sake):>>> arr.astype(int)
array([1, 2, 3, 4])
Note that passing int
as dtype to astype
or array
will default to a default integer type that depends on your platform. For example on Windows it will be int32
, on 64bit Linux with 64bit Python it's int64
. If you need a specific integer type and want to avoid the platform "ambiguity" you should use the corresponding NumPy types like np.int32
or np.int64
.
Maybe it is not quite as elegant, but the following might also work. I suspect asynchronously this would not be a good solution.
$p = Start-Process myjob.bat -redirectstandardoutput $logtempfile -redirecterroroutput $logtempfile -wait
add-content $logfile (get-content $logtempfile)
It will be application/font-woff
.
see http://www.w3.org/TR/WOFF/#appendix-b (W3C Candidate Recommendation 04 August 2011)
and http://www.w3.org/2002/06/registering-mediatype.html
From Mozilla css font-face notes
In Gecko, web fonts are subject to the same domain restriction (font files must be on the same domain as the page using them), unless HTTP access controls are used to relax this restriction. Note: Because there are no defined MIME types for TrueType, OpenType, and WOFF fonts, the MIME type of the file specified is not considered.
source: https://developer.mozilla.org/en/CSS/@font-face#Notes
It should be noted that you do not have to even use the "replace" method to change the value original value. If you assign one of the hash values for a hash, you are changing the original value.
def my_foo(a_hash)
a_hash["test"]="reference"
end;
hash = {"test"=>"value"}
my_foo(hash)
puts "Ruby is pass-by-#{hash["test"]}"
You just needed to read a little further and you would have been introduced to the *ngIf structural directive.
selectedHero.name doesn't exist yet because the user has yet to select a hero so it returns undefined.
<div *ngIf="selectedHero">
<h2>{{selectedHero.name}} details!</h2>
<div><label>id: </label>{{selectedHero.id}}</div>
<div>
<label>name: </label>
<input [(ngModel)]="selectedHero.name" placeholder="name"/>
</div>
</div>
The *ngIf directive keeps selectedHero off the DOM until it is selected and therefore becomes truthy.
This document helped me understand structural directives.
If you really must use tabs, and you don't mind the grey background-color and padding, <pre>
tags might work (if supported):
<pre>
This That And This
That This And That
</pre>
This That And This That This And That
StringEscapeUtils.escapeJavaScript
/ StringEscapeUtils.escapeEcmaScript
should do the trick too.
To pass arguments to your python script while running a script via command line
python create_thumbnail.py test1.jpg test2.jpg
here, script name - create_thumbnail.py, argument 1 - test1.jpg, argument 2 - test2.jpg
With in the create_thumbnail.py script i use
sys.argv[1:]
which give me the list of arguments i passed in command line as ['test1.jpg', 'test2.jpg']
This issue is happening because you have installed jre1.8.0_101-1.8.0_101-fcs.i58.rpm as well jdk-1.7.0_80-fcs.x86_64.rpm. so just uninstall your jre rpm & restart your application. It should work out.
You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree
option for single commands, or the GIT_WORK_TREE
environment variable. There is also the core.worktree
configuration option but it will not work in a bare repository (check the man page for what it does).
# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status
I wanted a pure html approach as I wanted to collapse and expand html that was added on the fly via a template! I came up with this...
https://jsfiddle.net/3mguht2y/1/
var noJavascript = ":)";
Which might be of use to someone :)
Here's how you would do it in Kotlin
fun <T> myMethod(item: T) where T : ClassA, T : InterfaceB {
//your code here
}
var countries = ['United States', 'Canada', 'Argentina', 'Armenia'];
var cList = $('ul.mylist')
$.each(countries, function(i) {
var li = $('<li/>')
.addClass('ui-menu-item')
.attr('role', 'menuitem')
.appendTo(cList);
var a = $('<a/>')
.addClass('ui-all')
.text( this )
.appendTo(li);
});
Thanks to AddRange
:
Example:
public class Person
{
private string Name;
private string FirstName;
public Person(string name, string firstname) => (Name, FirstName) = (name, firstname);
}
To add multiple Person
to a List<>
:
List<Person> listofPersons = new List<Person>();
listofPersons.AddRange(new List<Person>
{
new Person("John1", "Doe" ),
new Person("John2", "Doe" ),
new Person("John3", "Doe" ),
});
The screenshot was very helpful - the following code will do the job (assuming data is located in column A starting A1):
Sub RemoveRows()
Dim i As Long
i = 1
Do While i <= ThisWorkbook.ActiveSheet.Range("A1").CurrentRegion.Rows.Count
If InStr(1, ThisWorkbook.ActiveSheet.Cells(i, 1).Text, "-", vbTextCompare) > 0 Then
ThisWorkbook.ActiveSheet.Cells(i, 1).EntireRow.Delete
Else
i = i + 1
End If
Loop
End Sub
Sample file is shared: https://www.dropbox.com/s/2vhq6vw7ov7ssya/RemoweDashRows.xlsm
I had the same on my project.
I tried " super.setIntegerProperty("loadUrlTimeoutValue", 70000); " but to no avail.
I ensured all files were linked properly [ CSS, JS files etc ], validated the HTML using w3c validator [ http://validator.w3.org/#validate_by_upload ] , and cleaned the project [ Project -> Clean ]
It now loads and executes without the same error.
Hope this helps
My approach
function file_format_size($bytes, $decimals = 2) {
$unit_list = array('B', 'KB', 'MB', 'GB', 'PB');
if ($bytes == 0) {
return $bytes . ' ' . $unit_list[0];
}
$unit_count = count($unit_list);
for ($i = $unit_count - 1; $i >= 0; $i--) {
$power = $i * 10;
if (($bytes >> $power) >= 1)
return round($bytes / (1 << $power), $decimals) . ' ' . $unit_list[$i];
}
}
In my and other many vim users, the best option is to,
:e file_name.extension
And then just Ctrl + 6 to change to the last buffer. Or, you can always press
:ls to list the buffer and then change the buffer using b followed by the buffer number.
:vsp for vertical split
:sp for horizantal split
And then <C-W><C-H/K/L/j>
to change the working split.
You can ofcourse edit any file in any number of splits.
Perhaps they would have been satisfied with a knowledge of memalign? And as Jonathan Leffler points out, there are two newer preferable functions to know about.
Oops, florin beat me to it. However, if you read the man page I linked to, you'll most likely understand the example supplied by an earlier poster.
decimal Total = 0;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
Total+= Convert.ToDecimal(dataGridView1.Rows[i].Cells["ColumnName"].Value);
}
labelName.Text = Total.ToString();
Below is the fixed code:
#!/bin/ksh
safeRunCommand() {
typeset cmnd="$*"
typeset ret_code
echo cmnd=$cmnd
eval $cmnd
ret_code=$?
if [ $ret_code != 0 ]; then
printf "Error : [%d] when executing command: '$cmnd'" $ret_code
exit $ret_code
fi
}
command="ls -l | grep p"
safeRunCommand "$command"
Now if you look into this code few things that I changed are:
typeset
is not necessary but a good practice. It make cmnd
and ret_code
local to safeRunCommand
ret_code
is not necessary but a good practice to store return code in some variable (and store it ASAP) so that you can use it later like I did in printf "Error : [%d] when executing command: '$command'" $ret_code
safeRunCommand "$command"
. If you dont then cmnd
will get only the value ls
and not ls -l
. And it is even more important if your command contains pipes.typeset cmnd="$*"
instead of typeset cmnd="$1"
if you want to keep the spaces. You can try with both depending upon how complex is your command argument.NOTE: Do remember some commands give 1 as return code even though there is no error like grep
. If grep
found something it will return 0 else 1.
I had tested with KSH/BASH. And it worked fine. Let me know if u face issues running this.
Here is an example:
MySqlConnection con = new MySqlConnection(
"Server=ServerName;Database=DataBaseName;UID=username;Password=password");
MySqlCommand cmd = new MySqlCommand(
" INSERT Into Test (lat, long) VALUES ('"+OSGconv.deciLat+"','"+
OSGconv.deciLon+"')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI tooltip</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<script>
$(function() {
$("#tooltip").tooltip();
});
</script>
</head>
<body>
<div id="tooltip" title="I am tooltip">mouse over me</div>
</body>
</html>
You can also customise tooltip style. Please refer this link: http://jqueryui.com/tooltip/#custom-style
Nothing compares to extjs in terms of community size and presence on StackOverflow. Despite previous controversy, Ext JS now has a GPLv3 open source license. Its learning curve is long, but it can be quite rewarding once learned. Ext JS lacks a Material Design theme, and the team has repeatedly refused to release the source code on GitHub. For mobile, one must use the separate Sencha Touch library.
Have in mind also that,
large JavaScript libraries, such as YUI, have been receiving less attention from the community. Many developers today look at large JavaScript libraries as walled gardens they don’t want to be locked into.
-- Announcement of YUI development being ceased
That said, below are a number of Ext JS alternatives currently available.
Blueprint is a React-based UI toolkit developed by big data analytics company Palantir in TypeScript, and "optimized for building complex data-dense interfaces for desktop applications". Actively developed on GitHub as of May 2019, with comprehensive documentation. Components range from simple (chips, toast, icons) to complex (tree, data table, tag input with autocomplete, date range picker. No accordion or resizer.
Blueprint targets modern browsers (Chrome, Firefox, Safari, IE 11, and Microsoft Edge) and is licensed under a modified Apache license.
Sandbox / demo • GitHub • Docs
Webix - an advanced, easy to learn, mobile-friendly, responsive and rich free&open source JavaScript UI components library. Webix spun off from DHTMLX Touch (a project with 8 years of development behind it - see below) and went on to become a standalone UI components framework. The GPL3 edition allows commercial use and lets non-GPL applications using Webix keep their license, e.g. MIT, via a license exemption for FLOSS. Webix has 55 UI widgets, including trees, grids, treegrids and charts. Funding comes from a commercial edition with some advanced widgets (Pivot, Scheduler, Kanban, org chart etc.). Webix has an extensive list of free and commercial widgets, and integrates with most popular frameworks (React, Vue, Meteor, etc) and UI components.
Skins look modern, and include a Material Design theme. The Touch theme also looks quite Material Design-ish. See also the Skin Builder.
Minimal GitHub presence, but includes the library code, and the documentation (which still needs major improvements). Webix suffers from a having a small team and a lack of marketing. However, they have been responsive to user feedback, both on GitHub and on their forum.
The library was lean (128Kb gzip+minified for all 55 widgets as of ~2015), faster than ExtJS, dojo and others, and the design is pleasant-looking. The current version of Webix (v6, as of Nov 2018) got heavier (400 - 676kB minified but NOT gzipped).
The demos on Webix.com look and function great. The developer, XB Software, uses Webix in solutions they build for paying customers, so there's likely a good, funded future ahead of it.
Webix aims for backwards compatibility down to IE8, and as a result carries some technical debt.
Wikipedia • GitHub • Playground/sandbox • Admin dashboard demo • Demos • Widget samples
react-md - MIT-licensed Material Design UI components library for React. Responsive, accessible. Implements components from simple (buttons, cards) to complex (sortable tables, autocomplete, tags input, calendars). One lead author, ~1900 GitHub stars.
kendo - jQuery-based UI toolkit with 40+ basic open-source widgets, plus commercial professional widgets (grids, trees, charts etc.). Responsive&mobile support. Works with Bootstrap and AngularJS. Modern, with Material Design themes. The documentation is available on GitHub, which has enabled numerous contributions from users (4500+ commits, 500+ PRs as of Jan 2015).
Well-supported commercially, claiming millions of developers, and part of a large family of developer tools. Telerik has received many accolades, is a multi-national company (Bulgaria, US), was acquired by Progress Software, and is a thought leader.
A Kendo UI Professional developer license costs $700 and posting access to most forums is conditioned upon having a license or being in the trial period.
[Wikipedia] • GitHub/Telerik • Demos • Playground • Tools
OpenUI5 - jQuery-based UI framework with 180 widgets, Apache 2.0-licensed and fully-open sourced and funded by German software giant SAP SE.
The community is much larger than that of Webix, SAP is hiring developers to grow OpenUI5, and they presented OpenUI5 at OSCON 2014.
The desktop themes are rather lackluster, but the Fiori design for web and mobile looks clean and neat.
Wikipedia • GitHub • Mobile-first controls demos • Desktop controls demos • SO
DHTMLX - JavaScript library for building rich Web and Mobile apps. Looks most like ExtJS - check the demos. Has been developed since 2005 but still looks modern. All components except TreeGrid are available under GPLv2 but advanced features for many components are only available in the commercial PRO edition - see for example the tree. Claims to be used by many Fortune 500 companies.
Minimal presence on GitHub (the main library code is missing) and StackOverflow but active forum. The documentation is not available on GitHub, which makes it difficult to improve by the community.
Polymer, a Web Components polyfill, plus Polymer Paper, Google's implementation of the Material design. Aimed at web and mobile apps. Doesn't have advanced widgets like trees or even grids but the controls it provides are mobile-first and responsive. Used by many big players, e.g. IBM or USA Today.
Ant Design claims it is "a design language for background applications", influenced by "nature" and helping designers "create low-entropy atmosphere for developer team". That's probably a poor translation from Chinese for "UI components for enterprise web applications". It's a React UI library written in TypeScript, with many components, from simple (buttons, cards) to advanced (autocomplete, calendar, tag input, table).
The project was born in China, is popular with Chinese companies, and parts of the documentation are available only in Chinese. Quite popular on GitHub, yet it makes the mistake of splitting the community into Chinese and English chat rooms. The design looks Material-ish, but fonts are small and the information looks lost in a see of whitespace.
PrimeUI - collection of 45+ rich widgets based on jQuery UI. Apache 2.0 license. Small GitHub community. 35 premium themes available.
qooxdoo - "a universal JavaScript framework with a coherent set of individual components", developed and funded by German hosting provider 1&1 (see the contributors, one of the world's largest hosting companies. GPL/EPL (a business-friendly license).
Mobile themes look modern but desktop themes look old (gradients).
Wikipedia • GitHub • Web/Mobile/Desktop demos • Widgets Demo browser • Widget browser • SO • Playground • Community
jQuery UI - easy to pick up; looks a bit dated; lacks advanced widgets. Of course, you can combine it with independent widgets for particular needs, e.g. trees or other UI components, but the same can be said for any other framework.
angular + Angular UI. While Angular is backed by Google, it's being radically revamped in the upcoming 2.0 version, and "users will need to get to grips with a new kind of architecture. It's also been confirmed that there will be no migration path from Angular 1.X to 2.0". Moreover, the consensus seems to be that Angular 2 won't really be ready for use until a year or two from now. Angular UI has relatively few widgets (no trees, for example).
DojoToolkit and their powerful Dijit set of widgets. Completely open-sourced and actively developed on GitHub, but development is now (Nov 2018) focused on the new dojo.io framework, which has very few basic widgets. BSD/AFL license. Development started in 2004 and the Dojo Foundation is being sponsored by IBM, Google, and others - see Wikipedia. 7500 questions here on SO.
Themes look desktop-oriented and dated - see the theme tester in dijit. The official theme previewer is broken and only shows "Claro". A Bootstrap theme exists, which looks a lot like Bootstrap, but doesn't use Bootstrap classes. In Jan 2015, I started a thread on building a Material Design theme for Dojo, which got quite popular within the first hours. However, there are questions regarding building that theme for the current Dojo 1.10 vs. the next Dojo 2.0. The response to that thread shows an active and wide community, covering many time zones.
Unfortunately, Dojo has fallen out of popularity and fewer companies appear to use it, despite having (had?) a strong foothold in the enterprise world. In 2009-2012, its learning curve was steep and the documentation needed improvements; while the documentation has substantially improved, it's unclear how easy it is to pick up Dojo nowadays.
With a Material Design theme, Dojo (2.0?) might be the killer UI components framework.
Enyo - front-end library aimed at mobile and TV apps (e.g. large touch-friendly controls). Developed by LG Electronix and Apache-licensed on GitHub.
The radical Cappuccino - Objective-J (a superset of JavaScript) instead of HTML+CSS+DOM
Mochaui, MooTools UI Library User Interface Library. <300 GitHub stars.
CrossUI - cross-browser JS framework to develop and package the exactly same code and UI into Web Apps, Native Desktop Apps (Windows, OS X, Linux) and Mobile Apps (iOS, Android, Windows Phone, BlackBerry). Open sourced LGPL3. Featured RAD tool (form builder etc.). The UI looks desktop-, not web-oriented. Actively developed, small community. No presence on GitHub.
ZinoUI - simple widgets. The DataTable, for instance, doesn't even support sorting.
Wijmo - good-looking commercial widgets, with old (jQuery UI) widgets open-sourced on GitHub (their development stopped in 2013). Developed by ComponentOne, a division of GrapeCity. See Wijmo Complete vs. Open.
CxJS - commercial JS framework based on React, Babel and webpack offering form elements, form validation, advanced grid control, navigational elements, tooltips, overlays, charts, routing, layout support, themes, culture dependent formatting and more.
Widgets - Demo Apps - Examples - GitHub
SproutCore - developed by Apple for web applications with native performance, handling large data sets on the client. Powers iCloud.com. Not intended for widgets.
Wakanda: aimed at business/enterprise web apps - see What is Wakanda?. Architecture:
Wakanda Application Framework (datasource layer + browser-based interface widgets) that helps with browser and device compatibility across desktop and mobile
Wakanda is highly integrated, includes a ton of features out of the box, but has a very small GitHub community and SO presence.
Servoy - "a cross platform frontend development and deployment environment for SQL databases". Boasts a "full WYSIWIG (What You See Is What You Get) UI designer for HTML5 with built-in data-binding to back-end services", responsive design, support for HTML6 Web Components, Websockets and mobile platforms. Written in Java and generates JavaScript code using various JavaBeans.
SmartClient/SmartGWT - mobile and cross-browser HTML5 UI components combined with a Java server. Aimed at building powerful business apps - see demos.
Vaadin - full-stack Java/GWT + JavaScript/HTML3 web app framework
Backbase - portal software
Shiny - front-end library on top R, with visualization, layout and control widgets
ZKOSS: Java+jQuery+Bootstrap framework for building enterprise web and mobile apps.
These libraries don't implement complex widgets such as tables with sorting/filtering, autocompletes, or trees.
Foundation for Apps - responsive front-end framework on top of AngularJS; more of a grid/layout/navigation library
UI Kit - similar to Bootstrap, with fewer widgets, but with official off-canvas.
Using the canvas elements allows for complete control over the UI, and great cross-browser compatibility, but comes at the cost of missing native browser functionality, e.g. page search via Ctrl/Cmd+F.
This is another method I use because changing DropDownSyle
to DropDownList
makes it look 3D and sometimes its just plain ugly.
You can prevent user input by handling the KeyPress
event of the ComboBox like this.
private void ComboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = true;
}
I used to be irked by this problem; and I used to have a macro-cum-wrapper-function solution just like in Talonmies and Jared's answers, but, honestly? It makes using the CUDA Runtime API even more ugly and C-like.
So I've approached this in a different and more fundamental way. For a sample of the result, here's part of the CUDA vectorAdd
sample - with complete error checking of every runtime API call:
// (... prepare host-side buffers here ...)
auto current_device = cuda::device::current::get();
auto d_A = cuda::memory::device::make_unique<float[]>(current_device, numElements);
auto d_B = cuda::memory::device::make_unique<float[]>(current_device, numElements);
auto d_C = cuda::memory::device::make_unique<float[]>(current_device, numElements);
cuda::memory::copy(d_A.get(), h_A.get(), size);
cuda::memory::copy(d_B.get(), h_B.get(), size);
// (... prepare a launch configuration here... )
cuda::launch(vectorAdd, launch_config,
d_A.get(), d_B.get(), d_C.get(), numElements
);
cuda::memory::copy(h_C.get(), d_C.get(), size);
// (... verify results here...)
Again - all potential errors are checked , and an exception if an error occurred (caveat: If the kernel caused some error after launch, it will be caught after the attempt to copy the result, not before; to ensure the kernel was successful you would need to check for error between the launch and the copy with a cuda::outstanding_error::ensure_none()
command).
The code above uses my
Thin Modern-C++ wrappers for the CUDA Runtime API library (Github)
Note that the exceptions carry both a string explanation and the CUDA runtime API status code after the failing call.
A few links to how CUDA errors are automagically checked with these wrappers:
All other answer are correct, but remember that if you cast double to int you will loss decimal value.. so 2.9 double become 2 int.
You can use Math.round(double)
function or simply do :
(int)(yourDoubleValue + 0.5d)
On the Nexus 4 people this seems to make the color go grey.
ActionBar bar = getActionBar(); // or MainActivity.getInstance().getActionBar()
bar.setBackgroundDrawable(new ColorDrawable(0xff00DDED));
bar.setDisplayShowTitleEnabled(false); // required to force redraw, without, gray color
bar.setDisplayShowTitleEnabled(true);
(all credit to this post, but it is buried in the comments, so I wanted to surface it here) https://stackoverflow.com/a/17198657/1022454
you can run this small php
code
<?php
phpinfo();
?>
Copy the whole output page, paste it in this link. Then analyze. It will show if Xdebug is installed or not. And it will give instructions to complete the installation.
Zxing is an excellent library to perform Qr code scanning and generation. The following implementation uses Zxing library to scan the QR code image Don't forget to add following dependency in the build.gradle
implementation 'me.dm7.barcodescanner:zxing:1.9'
Code scanner activity:
public class QrCodeScanner extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private ZXingScannerView mScannerView;
@Override
public void onCreate(Bundle state) {
super.onCreate(state);
// Programmatically initialize the scanner view
mScannerView = new ZXingScannerView(this);
// Set the scanner view as the content view
setContentView(mScannerView);
}
@Override
public void onResume() {
super.onResume();
// Register ourselves as a handler for scan results.
mScannerView.setResultHandler(this);
// Start camera on resume
mScannerView.startCamera();
}
@Override
public void onPause() {
super.onPause();
// Stop camera on pause
mScannerView.stopCamera();
}
@Override
public void handleResult(Result rawResult) {
// Do something with the result here
// Prints scan results
Logger.verbose("result", rawResult.getText());
// Prints the scan format (qrcode, pdf417 etc.)
Logger.verbose("result", rawResult.getBarcodeFormat().toString());
//If you would like to resume scanning, call this method below:
//mScannerView.resumeCameraPreview(this);
Intent intent = new Intent();
intent.putExtra(AppConstants.KEY_QR_CODE, rawResult.getText());
setResult(RESULT_OK, intent);
finish();
}
}
To get the full path use:
readlink -f relative/path/to/file
To get the directory of a file:
dirname relative/path/to/file
You can also combine the two:
dirname $(readlink -f relative/path/to/file)
If readlink -f
is not available on your system you can use this*:
function myreadlink() {
(
cd "$(dirname $1)" # or cd "${1%/*}"
echo "$PWD/$(basename $1)" # or echo "$PWD/${1##*/}"
)
}
Note that if you only need to move to a directory of a file specified as a relative path, you don't need to know the absolute path, a relative path is perfectly legal, so just use:
cd $(dirname relative/path/to/file)
if you wish to go back (while the script is running) to the original path, use pushd
instead of cd
, and popd
when you are done.
* While myreadlink
above is good enough in the context of this question, it has some limitation relative to the readlink
tool suggested above. For example it doesn't correctly follow a link to a file with different basename
.
Try using:
string ap = c.Request["AP"];
That reads from the cookies, form, query string or server variables.
Alternatively:
string ap = c.Request.Form["AP"];
to just read from the form's data.
A similar option to what was posted above by janderson would be so simply use the .GetAttribute method in selenium 2. Using this, you can grab any item that has a specific value or label that you are looking for. This can be used to determine if an element has a label, style, value, etc. A common way to do this is to loop through the items in the drop down until you find the one that you want and select it. In C#
int items = driver.FindElement(By.XPath("//path_to_drop_Down")).Count();
for(int i = 1; i <= items; i++)
{
string value = driver.FindElement(By.XPath("//path_to_drop_Down/option["+i+"]")).GetAttribute("Value1");
if(value.Conatains("Label_I_am_Looking_for"))
{
driver.FindElement(By.XPath("//path_to_drop_Down/option["+i+"]")).Click();
//Clicked on the index of the that has your label / value
}
}
For me it was because of no SSH key on the machine. Check the SSH key locally:
$ cat ~/.ssh/id_rsa.pub
This is your SSH key. Add it to your SSH keys in the repository.
In gitlab go to
profile settings -> SSH Keys
and add the key
There is no show
event in js - you need to bind your button either to the click
event:
$('#id').on('click', function (e) {
//your awesome code here
})
Mind that if your button is inside a form
, you may prefer to bind the whole form to the submit
event.
maybe problem with margin?
width:auto;
padding: 0px;
margin: 0px
I would like to argue one point - that you cannot augment the original assembly - using Mono.Cecil you can inject [InternalsVisibleTo(...)]
to the 3pty assembly. Note there might be legal implications - you're messing with 3pty assembly and technical implications - if the assembly has strong name you either need to strip it or re-sign it with different key.
Install-Package Mono.Cecil
And the code like:
static readonly string[] s_toInject = {
// alternatively "MyAssembly, PublicKey=0024000004800000... etc."
"MyAssembly"
};
static void Main(string[] args) {
const string THIRD_PARTY_ASSEMBLY_PATH = @"c:\folder\ThirdPartyAssembly.dll";
var parameters = new ReaderParameters();
var asm = ModuleDefinition.ReadModule(INPUT_PATH, parameters);
foreach (var toInject in s_toInject) {
var ca = new CustomAttribute(
asm.Import(typeof(InternalsVisibleToAttribute).GetConstructor(new[] {
typeof(string)})));
ca.ConstructorArguments.Add(new CustomAttributeArgument(asm.TypeSystem.String, toInject));
asm.Assembly.CustomAttributes.Add(ca);
}
asm.Write(@"c:\folder-modified\ThirdPartyAssembly.dll");
// note if the assembly is strongly-signed you need to resign it like
// asm.Write(@"c:\folder-modified\ThirdPartyAssembly.dll", new WriterParameters {
// StrongNameKeyPair = new StrongNameKeyPair(File.ReadAllBytes(@"c:\MyKey.snk"))
// });
}
You can't, and you shouldn't.
Every other approach / alternative will only cause really bad user engagement.
That's my opinion.
Consider if instead it was:
class RectangularRoom(object):
def __init__(self, width, height):
pass
def cleanTileAtPosition(self, pos):
pass
def isTileCleaned(self, m, n):
pass
and you subclass and forget to tell it how to isTileCleaned()
or, perhaps more likely, typo it as isTileCLeaned()
. Then in your code, you'll get a None
when you call it.
None
valid output? Who knows. raise NotImplmentedError
forces you to implement it, as it will throw an exception when you try to run it until you do so. This removes a lot of silent errors. It's similar to why a bare except is almost never a good idea: because people make mistakes and this makes sure they aren't swept under the rug.
Note: Using an abstract base class, as other answers have mentioned, is better still, as then the errors are frontloaded and the program won't run until you implement them (with NotImplementedError, it will only throw an exception if actually called).
You can also use Gson for this scenario.
Gson gson = new Gson();
NameList nameList = gson.fromJson(data, NameList.class);
List<Name> list = nameList.getList();
Your NameList class could look like:
class NameList{
List<Name> list;
//getter and setter
}
So, with Perl 5.20, the new answer is:
foreach my $key (keys $ad_grp_ref->%*) {
(which has the advantage of transparently working with more complicated expressions:
foreach my $key (keys $ad_grp_obj[3]->get_ref()->%*) {
etc.)
See perlref for the full documentation.
Note: in Perl version 5.20 and 5.22, this syntax is considered experimental, so you need
use feature 'postderef';
no warnings 'experimental::postderef';
at the top of any file that uses it. Perl 5.24 and later don't require any pragmas for this feature.
would this work?
cat requirements.txt | while read x; do conda install "$x" -p ./lib ;done
or
conda install --file requirements.txt -p ./lib
check this form validation extension library can help you to validate files, with current form validation when you validate upload field it treat as input filed where value is empty have look on this really good extension for form validation library
Xcode 9.0 • Swift 4.0
import UIKit
class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var filterButton: UIButton!
@IBOutlet weak var saveButton: UIButton!
let destinationUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
.appendingPathComponent("filteredImage.png")
let imagePicker = UIImagePickerController()
let messageFrame = UIView()
var activityIndicator = UIActivityIndicatorView()
var strLabel = UILabel()
let effectView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
func activityIndicator(_ title: String) {
strLabel.removeFromSuperview()
activityIndicator.removeFromSuperview()
effectView.removeFromSuperview()
strLabel = UILabel(frame: CGRect(x: 50, y: 0, width: 160, height: 46))
strLabel.text = title
strLabel.font = .systemFont(ofSize: 14, weight: .medium)
strLabel.textColor = UIColor(white: 0.9, alpha: 0.7)
effectView.frame = CGRect(x: view.frame.midX - strLabel.frame.width/2, y: view.frame.midY - strLabel.frame.height/2 , width: 160, height: 46)
effectView.layer.cornerRadius = 15
effectView.layer.masksToBounds = true
activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .white)
activityIndicator.frame = CGRect(x: 0, y: 0, width: 46, height: 46)
activityIndicator.startAnimating()
effectView.contentView.addSubview(activityIndicator)
effectView.contentView.addSubview(strLabel)
view.addSubview(effectView)
}
func saveImage() {
do {
try imageView.image?.data?.write(to: destinationUrl, options: .atomic)
print("file saved")
} catch {
print(error)
}
}
func applyFilterToImage() {
imageView.image = imageView.image?.applying(contrast: 1.5)
}
override func viewDidLoad() {
super.viewDidLoad()
guard let url = URL(string: "https://upload.wikimedia.org/wikipedia/commons/a/a8/VST_images_the_Lagoon_Nebula.jpg"), let data = try? Data(contentsOf: url), let image = UIImage(data: data) else { return }
view.backgroundColor = UIColor(white: 0, alpha: 1)
imageView.image = image
}
@IBAction func startSavingImage(_ sender: AnyObject) {
saveButton.isEnabled = false
filterButton.isEnabled = false
activityIndicator("Saving Image")
DispatchQueue.main.async {
self.saveImage()
DispatchQueue.main.async {
self.effectView.removeFromSuperview()
self.saveButton.isEnabled = true
self.filterButton.isEnabled = true
}
}
}
@IBAction func filterAction(_ sender: AnyObject) {
filterButton.isEnabled = false
saveButton.isEnabled = false
activityIndicator("Applying Filter")
DispatchQueue.main.async {
self.applyFilterToImage()
DispatchQueue.main.async {
self.effectView.removeFromSuperview()
self.filterButton.isEnabled = true
self.saveButton.isEnabled = true
}
}
}
@IBAction func cameraAction(_ sender: AnyObject) {
if UIImagePickerController.isSourceTypeAvailable(.camera) {
imagePicker.delegate = self
imagePicker.sourceType = .camera
present(imagePicker, animated: true)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [AnyHashable: Any]!) {
dismiss(animated: true, completion: nil)
imageView.image = image
}
}
extension Data {
var image: UIImage? { return UIImage(data: self) }
}
extension UIImage {
var data: Data? { return UIImagePNGRepresentation(self) }
func applying(contrast value: NSNumber) -> UIImage? {
guard let ciImage = CIImage(image: self)?.applyingFilter("CIColorControls", withInputParameters: [kCIInputContrastKey: value]) else { return nil }
UIGraphicsBeginImageContextWithOptions(size, false, scale)
defer { UIGraphicsEndImageContext() }
UIImage(ciImage: ciImage).draw(in: CGRect(origin: .zero, size: size))
return UIGraphicsGetImageFromCurrentImageContext()
}
}
self.tableView.tableHeaderView = segmentedControl;
If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.
The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identical object.
So the difference are :
1- CopyTo require to have a destination array when Clone return a new array.
2- CopyTo let you specify an index (if required) to the destination array.
Edit:
Remove the wrong example.
as simple as:
tmpHM.each{ key, value ->
doSomethingWithKeyAndValue key, value
}
to keep this question up to date:
here is an approach i'd choose over the regex function using the ES6 spread operator.
function trimByChar(string, character) {
const first = [...string].findIndex(char => char !== character);
const last = [...string].reverse().findIndex(char => char !== character);
return string.substring(first, string.length - last);
}
Improved version after @fabian 's comment (can handle strings containing the same character only)
function trimByChar1(string, character) {
const arr = Array.from(string);
const first = arr.findIndex(char => char !== character);
const last = arr.reverse().findIndex(char => char !== character);
return (first === -1 && last === -1) ? '' : string.substring(first, string.length - last);
}
_x000D_
I had a similar problem and ended up using parse_url
and parse_str
, which as long as the URL in the parameter is correctly url encoded (which it definitely should) allows you to access both all the parameters of the actual URL, as well as the parameters of the encoded URL in the query parameter, like so:
$get_url = "http://google.com/?var=234&key=234";
$my_url = "http://localhost/test.php?id=" . urlencode($get_url);
function so_5645412_url_params($url) {
$url_comps = parse_url($url);
$query = $url_comps['query'];
$args = array();
parse_str($query, $args);
return $args;
}
$my_url_args = so_5645412_url_params($my_url); // Array ( [id] => http://google.com/?var=234&key=234 )
$get_url_args = so_5645412_url_params($my_url_args['id']); // Array ( [var] => 234, [key] => 234 )
Try running git status
on the file. It will print an error if it's not tracked by git
PS$> git status foo.txt
error: pathspec 'foo.txt' did not match any file(s) known to git.
Think more about what you are installing and navigate Gemfile folder, then try using sudo bundle install
put below tag in web.config file in configuration node
<connectionStrings>
<add name="NameOFConnectionString" connectionString="Data Source=Server;Initial Catalog=DatabaseName;User ID=User;Password=Pwd"
providerName="System.Data.SqlClient" />
then you can use above connectionstring, e.g.
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["NameOFConnectionString"].ToString();
you can do:
<div style="float: left;"></div>
or
<div style="display: inline;"></div>
Either one will cause the divs to tile horizontally.
"using MyNamespace" works in MVC3 RTM. Hope this helps.
In my case problem was at context.xml file of my project.
The following from context.xml causes the java.lang.AbstractMethodError, since we didn't show the datasource factory.
<Resource name="jdbc/myoracle"
auth="Container"
type="javax.sql.DataSource"
driverClassName="oracle.jdbc.OracleDriver"
url="jdbc:oracle:thin:@(DESCRIPTION = ... "
username="****" password="****" maxActive="10" maxIdle="1"
maxWait="-1" removeAbandoned="true"/>
Simpy adding factory="org.apache.tomcat.jdbc.pool.DataSourceFactory" solved the issue:
<Resource name="jdbc/myoracle"
auth="Container"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory" type="javax.sql.DataSource"
driverClassName="oracle.jdbc.OracleDriver"
url="jdbc:oracle:thin:@(DESCRIPTION = ... "
username="****" password="****" maxActive="10" maxIdle="1"
maxWait="-1" removeAbandoned="true"/>
To make sure I reproduced the issue several times by removing factory="org.apache.tomcat.jdbc.pool.DataSourceFactory" from Resource
There are a few problems with your code:
def MyThread ( threading.thread ):
If you really want to do this with only functions, you have two options:
With threading:
import threading
def MyThread1():
pass
def MyThread2():
pass
t1 = threading.Thread(target=MyThread1, args=[])
t2 = threading.Thread(target=MyThread2, args=[])
t1.start()
t2.start()
With thread:
import thread
def MyThread1():
pass
def MyThread2():
pass
thread.start_new_thread(MyThread1, ())
thread.start_new_thread(MyThread2, ())
Doc for thread.start_new_thread
type-specific formatting
can be used as well:
t = datetime.datetime(2012, 2, 23, 0, 0)
"{:%m/%d/%Y}".format(t)
Output:
'02/23/2012'
As an alternative representation you could use
[in] '%s' % hex(15)
[out]'0xf'
Using position: sticky
on th
will do the trick.
Note: if you use position: sticky
on thead
or tr
, it won't work.
While you could try these settings in config file
<system.web>
<httpRuntime requestPathInvalidCharacters="" requestValidationMode="2.0" />
<pages validateRequest="false" />
</system.web>
I would avoid using characters like '&' in URL path replacing them with underscores.
THE C WAY
You can use gets
function found in cstdio(stdio.h in c):
#include<cstdio>
int main(){
char name[256];
gets(name); // for input
puts(name);// for printing
}
THE C++ WAY
gets
is removed in c++11.
[Recommended]:You can use getline(cin,name) which is in string.h
or cin.getline(name,256) which is in iostream
itself.
#include<iostream>
#include<string>
using namespace std;
int main(){
char name1[256];
string name2;
cin.getline(name1,256); // for input
getline(cin,name2); // for input
cout<<name1<<"\n"<<name2;// for printing
}
From FOR /?
help doc:
FOR %variable IN (set) DO command [command-parameters]
%variable Specifies a single letter replaceable parameter.
(set) Specifies a set of one or more files. Wildcards may be used.
command Specifies the command to carry out for each file.
command-parameters
Specifies parameters or switches for the specified command.
To use the FOR command in a batch program, specify %%variable instead
of %variable. Variable names are case sensitive, so %i is different
from %I.
If Command Extensions are enabled, the following additional
forms of the FOR command are supported:
FOR /D %variable IN (set) DO command [command-parameters]
If set contains wildcards, then specifies to match against directory
names instead of file names.
FOR /R [[drive:]path] %variable IN (set) DO command [command-parameters]
Walks the directory tree rooted at [drive:]path, executing the FOR
statement in each directory of the tree. If no directory
specification is specified after /R then the current directory is
assumed. If set is just a single period (.) character then it
will just enumerate the directory tree.
FOR /L %variable IN (start,step,end) DO command [command-parameters]
The set is a sequence of numbers from start to end, by step amount.
So (1,1,5) would generate the sequence 1 2 3 4 5 and (5,-1,1) would
generate the sequence (5 4 3 2 1)
If your app is written in TypeScript, try
(global as any).logger = // ...
or
Object.assign(global, { logger: // ... })
However, I will do it only when React Native's __DEV__
in testing environment.
In the future, this problem will be solved by flexbox. Right now the browser support is dismal, but it is supported in one form or another in all current browsers.
Browser support: http://caniuse.com/flexbox
.vertically_aligned {
/* older webkit */
display: -webkit-box;
-webkit-box-align: center;
-webkit-justify-content: center;
/* older firefox */
display: -moz-box;
-moz-box-align: center;
-moz-box-pack: center;
/* IE10*/
display: -ms-flexbox;
-ms-flex-align: center;
-ms-flex-pack: center;
/* newer webkit */
display: -webkit-flex;
-webkit-align-items: center;
-webkit-box-pack: center;
/* Standard Form - IE 11+, FF 22+, Chrome 29+, Opera 17+ */
display: flex;
align-items: center;
justify-content: center;
}
Background on Flexbox: http://css-tricks.com/snippets/css/a-guide-to-flexbox/
Use reindex
to get all columns you need. It'll preserve the ones that are already there and put in empty columns otherwise.
p = p.reindex(columns=['1Sun', '2Mon', '3Tue', '4Wed', '5Thu', '6Fri', '7Sat'])
So, your entire code example should look like this:
df = pd.read_csv(CsvFileName)
p = df.pivot_table(index=['Hour'], columns='DOW', values='Changes', aggfunc=np.mean).round(0)
p.fillna(0, inplace=True)
columns = ["1Sun", "2Mon", "3Tue", "4Wed", "5Thu", "6Fri", "7Sat"]
p = p.reindex(columns=columns)
p[columns] = p[columns].astype(int)
DATE_ADD
works correctly. 1 January plus 6 months is 1 July, just like 1 January plus 1 month is 1 of February.
Between operation is inclusive. So, you are getting everything up to, and including, 1 July. (see also MySQL "between" clause not inclusive?)
What you need to do is subtract 1 day or use < operator instead of between.
Since Oracle 9i there are two ways or declaring a directory for use with UTL_FILE.
The older way is to set the INIT.ORA parameter UTL_FILE_DIR. We have to restart the database for a change to take affect. The value can like any other PATH variable; it accepts wildcards. Using this approach means passing the directory path...
UTL_FILE.FOPEN('c:\temp', 'vineet.txt', 'W');
The alternative approach is to declare a directory object.
create or replace directory temp_dir as 'C:\temp'
/
grant read, write on directory temp_dir to vineet
/
Directory objects require the exact file path, and don't accept wildcards. In this approach we pass the directory object name...
UTL_FILE.FOPEN('TEMP_DIR', 'vineet.txt', 'W');
The UTL_FILE_DIR is deprecated because it is inherently insecure - all users have access to all the OS directories specified in the path, whereas read and write privileges can de granted discretely to individual users. Also, with Directory objects we can be add, remove or change directories without bouncing the database.
In either case, the oracle
OS user must have read and/or write privileges on the OS directory. In case it isn't obvious, this means the directory must be visible from the database server. So we cannot use either approach to expose a directory on our local PC to a process running on a remote database server. Files must be uploaded to the database server, or a shared network drive.
If the oracle
OS user does not have the appropriate privileges on the OS directory, or if the path specified in the database does not match to an actual path, the program will hurl this exception:
ORA-29283: invalid file operation
ORA-06512: at "SYS.UTL_FILE", line 536
ORA-29283: invalid file operation
ORA-06512: at line 7
The OERR text for this error is pretty clear:
29283 - "invalid file operation"
*Cause: An attempt was made to read from a file or directory that does
not exist, or file or directory access was denied by the
operating system.
*Action: Verify file and directory access privileges on the file system,
and if reading, verify that the file exists.
Well, basically what I found is that you can declare the array, but when you set it vba shows you an error.
So I put an special sub to declare global variables and arrays, something like:
Global example(10) As Variant
Sub set_values()
example(1) = 1
example(2) = 1
example(3) = 1
example(4) = 1
example(5) = 1
example(6) = 1
example(7) = 1
example(8) = 1
example(9) = 1
example(10) = 1
End Sub
And whenever I want to use the array, I call the sub first, just in case
call set_values
Msgbox example(5)
Perhaps is not the most correct way, but I hope it works for you
This is how I use it:
runOnUiThread(new Runnable() {
@Override
public void run() {
//Do something on UiThread
}
});
you may add an interceptor .
myModule.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('noCacheInterceptor');
}]).factory('noCacheInterceptor', function () {
return {
request: function (config) {
console.log(config.method);
console.log(config.url);
if(config.method=='GET'){
var separator = config.url.indexOf('?') === -1 ? '?' : '&';
config.url = config.url+separator+'noCache=' + new Date().getTime();
}
console.log(config.method);
console.log(config.url);
return config;
}
};
});
you should remove console.log lines after verifying.
I used this and works for me.
function arrayBufferToBase64( buffer ) {
var binary = '';
var bytes = new Uint8Array( buffer );
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode( bytes[ i ] );
}
return window.btoa( binary );
}
function base64ToArrayBuffer(base64) {
var binary_string = window.atob(base64);
var len = binary_string.length;
var bytes = new Uint8Array( len );
for (var i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
return bytes.buffer;
}
Sounds like you're looking to simulate the IE6 box model. You could use the CSS 3 property box-sizing: border-box to achieve this. This is supported by IE8, but for Firefox you would need to use -moz-box-sizing
and for Safari/Chrome, use -webkit-box-sizing
.
IE6 already computes the height wrong, so you're good in that browser, but I'm not sure about IE7, I think it will compute the height the same in quirks mode.
You can try git difftool
, it is designed to do this stuff.
First, you need to config diff tool to vimdiff
git config diff.tool vimdiff
Then, when you want to diff, just use git difftool
instead of git diff
. It will work as you expect.
Practice
<form name=myform>
<input type=button value="Try it now"
onClick="if(confirm('Format the hard disk?'))
alert('You are very brave!');
else alert('A wise decision!')">
</form>
Web Original:
the file is a native DLL which means you can't add it to a .NET project via Add Reference... you can use it via DllImport (see http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.dllimportattribute.aspx)
Please note that for the sake of simplicity I have made reference to only the first code snippet i.e.,
// Create an anonymous implementation of OnClickListener
private OnClickListener mCorkyListener = new OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
}
};
protected void onCreate(Bundle savedValues) {
...
// Capture our button from layout
Button button = (Button)findViewById(R.id.corky);
// Register the onClick listener with the implementation above
button.setOnClickListener(mCorkyListener);
...
}
setOnClickListener(View.OnClickListener l)
is a public method of View class. Button class extends the View class and can therefore call setOnClickListener(View.OnClickListener l)
method.
setOnClickListener registers a callback to be invoked when the view (button in your case) is clicked. This answers should answer your first two questions:
1. Where does setOnClickListener
fit in the above logic?
Ans. It registers a callback when the button is clicked. (Explained in detail in the next paragraph).
2. Which one actually listens to the button click?
Ans. setOnClickListener
method is the one that actually listens to the button click.
When I say it registers a callback to be invoked, what I mean is it will run the View.OnClickListener l
that is the input parameter for the method. In your case, it will be mCorkyListener
mentioned in button.setOnClickListener(mCorkyListener);
which will then execute the method onClick(View v)
mentioned within
// Create an anonymous implementation of OnClickListener
private OnClickListener mCorkyListener = new OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
}
};
Moving on further, OnClickListener
is an Interface definition for a callback to be invoked when a view (button in your case) is clicked. Simply saying, when you click that button, the methods within mCorkyListener
(because it is an implementation of OnClickListener
) are executed. But, OnClickListener
has just one method which is OnClick(View v)
. Therefore, whatever action that needs to be performed on clicking the button must be coded within this method.
Now that you know what setOnClickListener
and OnClickListener
mean, I'm sure you'll be able to differentiate between the two yourself. The third term View.OnClickListener
is actually OnClickListener
itself. The only reason you have View.
preceding it is because of the difference in the import
statment in the beginning of the program. If you have only import android.view.View;
as the import statement you will have to use View.OnClickListener
. If you mention either of these import statements:
import android.view.View.*;
or import android.view.View.OnClickListener;
you can skip the View.
and simply use OnClickListener
.
The next link will bring you to a great tutorial, that helped me a lot!
I nearly used everything in that article to create the SQLite database for my own C# Application.
Don't forget to download the SQLite.dll, and add it as a reference to your project. This can be done using NuGet and by adding the dll manually.
After you added the reference, refer to the dll from your code using the following line on top of your class:
using System.Data.SQLite;
You can find the dll's here:
You can find the NuGet way here:
Up next is the create script. Creating a database file:
SQLiteConnection.CreateFile("MyDatabase.sqlite");
SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
m_dbConnection.Open();
string sql = "create table highscores (name varchar(20), score int)";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
sql = "insert into highscores (name, score) values ('Me', 9001)";
command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
m_dbConnection.Close();
After you created a create script in C#, I think you might want to add rollback transactions, it is safer and it will keep your database from failing, because the data will be committed at the end in one big piece as an atomic operation to the database and not in little pieces, where it could fail at 5th of 10 queries for example.
Example on how to use transactions:
using (TransactionScope tran = new TransactionScope())
{
//Insert create script here.
//Indicates that creating the SQLiteDatabase went succesfully, so the database can be committed.
tran.Complete();
}
/*Fully Opaque*/
.class-name {
opacity:1.0;
}
/*Translucent*/
.class-name {
opacity:0.5;
}
/*Transparent*/
.class-name {
opacity:0;
}
/*or you can use a transparent rgba value like this*/
.class-name{
background-color: rgba(255, 242, 0, 0.7);
}
/*Note - Opacity value can be anything between 0 to 1;
Eg(0.1,0.8)etc */
I just published this module because I needed this functionality.
https://www.npmjs.org/package/filendir
It works like a wrapper around Node.js fs methods. So you can use it exactly the same way you would with fs.writeFile
and fs.writeFileSync
(both async and synchronous writes)
It's hacky but if you're using GFM or some other MD syntax which supports building tables with pipes you can use the column alignment features:
|| <!-- empty table header -->
|:--:| <!-- table header/body separator with center formatting -->
| I'm centered! | <!-- cell gets column's alignment -->
This works in marked.
max(may$Ozone, na.rm = TRUE)
Without $Ozone
it will filter in the whole data frame, this can be learned in the swirl library.
I'm studying this course on Coursera too ~
Hi all i have created two overload methods for finding nth occurrence of char and for text with less complexity without navigating through loop ,which increase performance of your application.
public static int NthIndexOf(string text, char searchChar, int nthindex)
{
int index = -1;
try
{
var takeCount = text.TakeWhile(x => (nthindex -= (x == searchChar ? 1 : 0)) > 0).Count();
if (takeCount < text.Length) index = takeCount;
}
catch { }
return index;
}
public static int NthIndexOf(string text, string searchText, int nthindex)
{
int index = -1;
try
{
Match m = Regex.Match(text, "((" + searchText + ").*?){" + nthindex + "}");
if (m.Success) index = m.Groups[2].Captures[nthindex - 1].Index;
}
catch { }
return index;
}
Your action method considers model type asList<string>
. But, in your view you are waiting for IEnumerable<Standings.Models.Teams>
.
You can solve this problem with changing the model in your view to List<string>
.
But, the best approach would be to return IEnumerable<Standings.Models.Teams>
as a model from your action method. Then you haven't to change model type in your view.
But, in my opinion your models are not correctly implemented. I suggest you to change it as:
public class Team
{
public int Position { get; set; }
public string HomeGround {get; set;}
public string NickName {get; set;}
public int Founded { get; set; }
public string Name { get; set; }
}
Then you must change your action method as:
public ActionResult Index()
{
var model = new List<Team>();
model.Add(new Team { Name = "MU"});
model.Add(new Team { Name = "Chelsea"});
...
return View(model);
}
And, your view:
@model IEnumerable<Standings.Models.Team>
@{
ViewBag.Title = "Standings";
}
@foreach (var item in Model)
{
<div>
@item.Name
<hr />
</div>
}
If you can re-structure your code so that you do not need to postback, then you can use this code in the PreRender event of the button:
protected void MyButton_OnPreRender(object sender, EventArgs e)
{
string URL = "~/MyPage.aspx";
URL = Page.ResolveClientUrl(URL);
MyButton.OnClientClick = "window.open('" + URL + "'); return false;";
}
Using SSMS, I made sure the user had connect permissions on both the database and ReportServer.
On the specific database being queried, under properties, I mapped their credentials and enabled datareader and public permissions. Also, as others have stated-I made sure there were no denyread/denywrite boxes selected.
I did not want to enable db ownership when for their reports since they only needed to have select permissions.
If you are using custom TableViewCells, the generic
[self.tableView reloadData];
does not effectively answer this question unless you leave the current view and come back. Neither does the first answer.
To successfully reload your first table view cell without switching views, use the following code:
//For iOS 5 and later
- (void)reloadTopCell {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
NSArray *indexPaths = [[NSArray alloc] initWithObjects:indexPath, nil];
[self.tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];
}
Insert the following refresh method which calls to the above method so you can custom reload only the top cell (or the entire table view if you wish):
- (void)refresh:(UIRefreshControl *)refreshControl {
//call to the method which will perform the function
[self reloadTopCell];
//finish refreshing
[refreshControl endRefreshing];
}
Now that you have that sorted, inside of your viewDidLoad
add the following:
//refresh table view
UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
[refreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged];
[self.tableView addSubview:refreshControl];
You now have a custom refresh table feature that will reload the top cell. To reload the entire table, add the
[self.tableView reloadData];
to your new refresh method.
If you wish to reload the data every time you switch views, implement the method:
//ensure that it reloads the table view data when switching to this view
- (void) viewWillAppear:(BOOL)animated {
[self.tableView reloadData];
}
At the risk of being years late and off topic - and notwithstanding @Marc's excellent insight, in Swift it looks like:
let basename = NSURL(string: "path/to/file.ext")?.URLByDeletingPathExtension?.lastPathComponent
A working example for OSX (tested right now on Catalina 10.15). Not portable to linux/windows obviously. Probably it will be usefull to somebody.
In the "Mew-exception" string you can use backtrace and/or backtrace_symbols functions
#include <stdexcept>
#include <typeinfo>
#include <dlfcn.h>
extern "C" void __cxa_throw(void *thrown_object, std::type_info *tinfo, void (*dest)(void *));
static void (*__cxa_throw_orig)(void *thrown_object, std::type_info *tinfo, void (*dest)(void *));
extern "C" void luna_cxa_throw(void *thrown_object, std::type_info *tinfo, void (*dest)(void *))
{
printf("Mew-exception you can catch your backtrace here!");
__cxa_throw_orig(thrown_object, tinfo, dest);
}
//__attribute__ ((used))
//__attribute__ ((section ("__DATA,__interpose")))
static struct replace_pair_t {
void *replacement, *replacee;
} replace_pair = { (void*)luna_cxa_throw, (void*)__cxa_throw };
extern "C" const struct mach_header __dso_handle;
extern "C" void dyld_dynamic_interpose(const struct mach_header*,
const replace_pair_t replacements[],
size_t count);
int fn()
{
int a = 10; ++a;
throw std::runtime_error("Mew!");
}
int main(int argc, const char * argv[]) {
__cxa_throw_orig = (void (*)(void *thrown_object, std::type_info *tinfo, void (*dest)(void *)))dlsym(RTLD_DEFAULT, "__cxa_throw");
dyld_dynamic_interpose(&__dso_handle, &replace_pair, 1);
fn();
return 0;
}
If you use the procedural style, you have to provide both a connection and a string:
$name = mysqli_real_escape_string($conn, $name);
Only the object oriented version can be done with just a string:
$name = $link->real_escape_string($name);
The documentation should hopefully make this clear.
It looks OK apart from the space in your ID attribute, which is not valid, and the fact that you're replacing the value of your input before checking the selection.
function textbox()_x000D_
{_x000D_
var ctl = document.getElementById('Javascript_example');_x000D_
var startPos = ctl.selectionStart;_x000D_
var endPos = ctl.selectionEnd;_x000D_
alert(startPos + ", " + endPos);_x000D_
}
_x000D_
<input id="Javascript_example" name="one" type="text" value="Javascript example" onclick="textbox()">
_x000D_
Also, if you're supporting IE <= 8 you need to be aware that those browsers do not support selectionStart
and selectionEnd
.
I had this problem after changing the Application's Default namespace in the Properties dialog.
The ./Views/Web.Config contained a reference to the old namespace
Wikipedia has a quite good explanation: http://en.wikipedia.org/wiki/Middleware
It starts with
Middleware is computer software that connects software components or applications. The software consists of a set of services that allows multiple processes running on one or more machines to interact.
What is Middleware gives a few examples.
Your Promise is pending, complete it by
userToken.then(function(result){
console.log(result)
})
after your remaining code.
All this code does is that .then()
completes your promise & captures the end result in result variable & print result in console.
Keep in mind, you cannot store the result in global variable.
Hope that explanation might help you.
This is the code that I've found to run the fastest so far. I ran it on 109015 byte arrays of length 32, in 23ms. I was running it on a VM so it'll probably run faster on bare metal.
public static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
public static char[] encodeHex( final byte[] data ){
final int l = data.length;
final char[] out = new char[l<<1];
for( int i=0,j=0; i<l; i++ ){
out[j++] = HEX_DIGITS[(0xF0 & data[i]) >>> 4];
out[j++] = HEX_DIGITS[0x0F & data[i]];
}
return out;
}
Then you can just do
String s = new String( encodeHex(myByteArray) );
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main (){
int pid;
int status;
printf("Parent: %d\n", getpid());
pid = fork();
if (pid == 0){
printf("Child %d\n", getpid());
sleep(2);
exit(EXIT_SUCCESS);
}
//Comment from here to...
//Parent waits process pid (child)
waitpid(pid, &status, 0);
//Option is 0 since I check it later
if (WIFSIGNALED(status)){
printf("Error\n");
}
else if (WEXITSTATUS(status)){
printf("Exited Normally\n");
}
//To Here and see the difference
printf("Parent: %d\n", getpid());
return 0;
}
Indeed rather use ExecutorService
instead of Timer
, here's an SSCCE:
package com.stackoverflow.q2275443;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class Test {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new Task());
try {
System.out.println("Started..");
System.out.println(future.get(3, TimeUnit.SECONDS));
System.out.println("Finished!");
} catch (TimeoutException e) {
future.cancel(true);
System.out.println("Terminated!");
}
executor.shutdownNow();
}
}
class Task implements Callable<String> {
@Override
public String call() throws Exception {
Thread.sleep(4000); // Just to demo a long running task of 4 seconds.
return "Ready!";
}
}
Play a bit with the timeout
argument in Future#get()
method, e.g. increase it to 5 and you'll see that the thread finishes. You can intercept the timeout in the catch (TimeoutException e)
block.
Update: to clarify a conceptual misunderstanding, the sleep()
is not required. It is just used for SSCCE/demonstration purposes. Just do your long running task right there in place of sleep()
. Inside your long running task, you should be checking if the thread is not interrupted as follows:
while (!Thread.interrupted()) {
// Do your long running task here.
}
One might consider adding this line to ~/.bash_profile
(or similar) in order to can quickly get the current UTC both as current time and as seconds since the epoch.
alias utc='date -u && date -u +%s'
If you want to open inside the app itself instead of leaving the app you can import SafariServices and work it out.
import UIKit
import SafariServices
let url = URL(string: "https://www.google.com")
let vc = SFSafariViewController(url: url!)
present(vc, animated: true, completion: nil)
My suggestions :
For setting the values in the number, use constructors. Do not use like the methods you have used above like :
public void setNumber(double fnum, double snum){ this.fn = fnum; this.sn = snum; }
Constructors exists to initialize the objects.This is their job and they are pretty good at it.
Getters for members of Calculate class seem in place. But setters are not. Getters and setters serves as one important block in the bridge of efficient programming with java. Put setters for fnum and snum as well
In the main class, create a Calculate object using the new operator and the constructor in place.
Call the getAnswer() method with the created Calculate object.
Rest of the code looks fine to me. Be modular. You could read your program in a much better way.
Here is my modular piece of code. Two files : Main.java & Calculate.java
public class Calculate {
private double fn;
private double sn;
private char op;
public double getFn() {
return fn;
}
public void setFn(double fn) {
this.fn = fn;
}
public double getSn() {
return sn;
}
public void setSn(double sn) {
this.sn = sn;
}
public char getOp() {
return op;
}
public void setOp(char op) {
this.op = op;
}
public Calculate(double fn, double sn, char op) {
this.fn = fn;
this.sn = sn;
this.op = op;
}
public void getAnswer(){
double ans;
switch (getOp()){
case '+':
ans = add(getFn(), getSn());
ansOutput(ans);
break;
case '-':
ans = sub (getFn(), getSn());
ansOutput(ans);
break;
case '*':
ans = mul (getFn(), getSn());
ansOutput(ans);
break;
case '/':
ans = div (getFn(), getSn());
ansOutput(ans);
break;
default:
System.out.println("--------------------------");
System.out.println("Invalid choice of operator");
System.out.println("--------------------------");
}
}
public static double add(double x,double y){
return x + y;
}
public static double sub(double x, double y){
return x - y;
}
public static double mul(double x, double y){
return x * y;
}
public static double div(double x, double y){
return x / y;
}
public static void ansOutput(double x){
System.out.println("----------- -------");
System.out.printf("the answer is %.2f\n", x);
System.out.println("-------------------");
}
}
public class Main {
public static void main(String args[])
{
Calculate obj = new Calculate(1,2,'+');
obj.getAnswer();
}
}
Try:
<div style="@(Model.booleanVariable ? "display:block" : "display:none")">Some links</div>
Use the "Display" style attribute with your bool model attribute to define the div's visibility.
The dataset in ss.csv
contains some columns I am interested in:
ss_ = spark.read.csv("ss.csv", header= True,
inferSchema = True)
ss_.columns
['Reporting Area', 'MMWR Year', 'MMWR Week', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Current week', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Current week, flag', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Previous 52 weeks Med', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Previous 52 weeks Med, flag', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Previous 52 weeks Max', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Previous 52 weeks Max, flag', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Cum 2018', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Cum 2018, flag', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Cum 2017', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Cum 2017, flag', 'Shiga toxin-producing Escherichia coli, Current week', 'Shiga toxin-producing Escherichia coli, Current week, flag', 'Shiga toxin-producing Escherichia coli, Previous 52 weeks Med', 'Shiga toxin-producing Escherichia coli, Previous 52 weeks Med, flag', 'Shiga toxin-producing Escherichia coli, Previous 52 weeks Max', 'Shiga toxin-producing Escherichia coli, Previous 52 weeks Max, flag', 'Shiga toxin-producing Escherichia coli, Cum 2018', 'Shiga toxin-producing Escherichia coli, Cum 2018, flag', 'Shiga toxin-producing Escherichia coli, Cum 2017', 'Shiga toxin-producing Escherichia coli, Cum 2017, flag', 'Shigellosis, Current week', 'Shigellosis, Current week, flag', 'Shigellosis, Previous 52 weeks Med', 'Shigellosis, Previous 52 weeks Med, flag', 'Shigellosis, Previous 52 weeks Max', 'Shigellosis, Previous 52 weeks Max, flag', 'Shigellosis, Cum 2018', 'Shigellosis, Cum 2018, flag', 'Shigellosis, Cum 2017', 'Shigellosis, Cum 2017, flag']
but I only need a few:
columns_lambda = lambda k: k.endswith(', Current week') or k == 'Reporting Area' or k == 'MMWR Year' or k == 'MMWR Week'
The filter returns the list of desired columns, list is evaluated:
sss = filter(columns_lambda, ss_.columns)
to_keep = list(sss)
the list of desired columns is unpacked as arguments to dataframe select function that return dataset containing only columns in the list:
dfss = ss_.select(*to_keep)
dfss.columns
The result:
['Reporting Area',
'MMWR Year',
'MMWR Week',
'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Current week',
'Shiga toxin-producing Escherichia coli, Current week',
'Shigellosis, Current week']
The df.select()
has a complementary pair: http://spark.apache.org/docs/2.4.1/api/python/pyspark.sql.html#pyspark.sql.DataFrame.drop
to drop the list of columns.
Current working version as of Oct 2020, updated to use maven-antrun-plugin 3.0.0.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<id>prepare</id>
<phase>package</phase>
<configuration>
<target>
<unzip src="target/shaded-jar/shade-test.jar"
dest="target/unpacked-shade/"/>
</target>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
Always use double quotes when using a variable inside a string and backslash any other double quotes except the starting and ending ones. You could also use the brackets like below so it's easier to find your variables inside the strings and make them look cleaner.
$var = 'my variable';
echo "I love ${var}";
or
$var = 'my variable';
echo "I love {$var}";
Above would return the following: I love my variable
I think it depends on what you mean by refresh. Do you mean that the GUI display should be refreshed, or do you mean that the child views should be refreshed such that you can programatically call getChildAt(int) and get the view corresponding to what is in the Adapter.
If you want the GUI display refreshed, then call notifyDataSetChanged() on the adapter. The GUI will be refreshed when next redrawn.
If you want to be able to call getChildAt(int) and get a view that reflects what is what is in the adapter, then call to layoutChildren(). This will cause the child view to be reconstructed from the adapter data.
I ran into this problem today and this was the trick I did, which worked for me:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("DAOMANAGER");
EntityManagerem = emf.createEntityManager();
org.hibernate.Session session = ((EntityManagerImpl) em).getSession();
java.sql.Connection connectionObj = session.connection();
Though not the best way but does the job.
This is a fair few years later, but the Facebook Graph API Explorer now has a little info symbol next to the access token that allows you to access the access token tool app, and extend the API token for a couple of months. Might be helpful during development.
xs:boolean
is predefined with regard to what kind of input it accepts. If you need something different, you have to define your own enumeration:
<xs:simpleType name="my:boolean">
<xs:restriction base="xs:string">
<xs:enumeration value="True"/>
<xs:enumeration value="False"/>
</xs:restriction>
</xs:simpleType>
Solution is to change Delimiter.
Content of the csv file -> Note .. Also space and , in value
Values are 6 Dutch word aap,noot,mies,Piet, Gijs, Jan
Col1;Col2;Col3
a,ap;noo,t;mi es
P,iet;G ,ijs;Ja ,n
$csv = Import-Csv C:\TejaCopy.csv -Delimiter ';'
Answer:
Write-Host $csv
@{Col1=a,ap; Col2=noo,t; Col3=mi es} @{Col1=P,iet; Col2=G ,ijs; Col3=Ja ,n}
It is possible to read a CSV file and use other Delimiter to separate each column.
It worked for my script :-)
Try adding the drive letter:
include_path='.;c:\xampplite\php\pear\PEAR'
also verify that PEAR.php is actually there, it might be in \php\ instead:
include_path='.;c:\xampplite\php'
by splitting with newlines.
for line in wallop_of_a_string_with_many_lines.split('\n'):
#do_something..
if you iterate over a string, you are iterating char by char in that string, not by line.
>>>string = 'abc'
>>>for line in string:
print line
a
b
c
URL-encoded payload must be provided on the body
parameter of the http.NewRequest(method, urlStr string, body io.Reader)
method, as a type that implements io.Reader
interface.
Based on the sample code:
package main
import (
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
)
func main() {
apiUrl := "https://api.com"
resource := "/user/"
data := url.Values{}
data.Set("name", "foo")
data.Set("surname", "bar")
u, _ := url.ParseRequestURI(apiUrl)
u.Path = resource
urlStr := u.String() // "https://api.com/user/"
client := &http.Client{}
r, _ := http.NewRequest(http.MethodPost, urlStr, strings.NewReader(data.Encode())) // URL-encoded payload
r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
resp, _ := client.Do(r)
fmt.Println(resp.Status)
}
resp.Status
is 200 OK
this way.
it's simple, use the "-B" option to add .h files' dir to search path.
E.g. g++ -B /header_file.h your.cpp -o bin/your_command
$ file=${$(basename $file_path)%.*}
You probably have a mixture of spaces and tabs in your original source file. Replace all the tabs with four spaces (or vice versa) and you should see the problem straight away.
Your code as pasted into your question doesn't have this problem, but I guess your editor (or your web browser, or Stack Overflow itself...) could have done the tabs-to-spaces conversion without your knowledge.
I've been watching Douglas Crockford's video on this and his explanation for not using increment and decrement is that
Firstly arrays in JavaScript are dynamically sized and so, forgive me if I'm wrong, it is not possible to break the bounds of an array and access data that shouldn't be accessed using this method in JavaScript.
Secondly, should we avoid things that are complicated, surely the problem is not that we have this facility but the problem is that there are developers out there that claim to do JavaScript but don't know how these operators work?? It is simple enough. value++, give me the current value and after the expression add one to it, ++value, increment the value before giving me it.
Expressions like a ++ + ++ b, are simple to work out if you just remember the above.
var a = 1, b = 1, c;
c = a ++ + ++ b;
// c = 1 + 2 = 3;
// a = 2 (equals two after the expression is finished);
// b = 2;
I suppose you've just got to remember who has to read through the code, if you have a team that knows JS inside out then you don't need to worry. If not then comment it, write it differently, etc. Do what you got to do. I don't think increment and decrement is inherently bad or bug generating, or vulnerability creating, maybe just less readable depending on your audience.
Btw, I think Douglas Crockford is a legend anyway, but I think he's caused a lot of scare over an operator that didn't deserve it.
I live to be proven wrong though...
Please note I'm a beginner. If My solution is wrong, please feel free to correct and/or let me know. I may learn something new too.
My solution:
Change the downloadPath accordingly to where you want your file to be saved. Feel free to use the absolute path too for your usage.
Save the below as downloadFile.py.
Usage: python downloadFile.py url-of-the-file-to-download new-file-name.extension
Remember to add an extension!
Example usage: python downloadFile.py http://www.google.co.uk google.html
import requests
import sys
import os
def downloadFile(url, fileName):
with open(fileName, "wb") as file:
response = requests.get(url)
file.write(response.content)
scriptPath = sys.path[0]
downloadPath = os.path.join(scriptPath, '../Downloads/')
url = sys.argv[1]
fileName = sys.argv[2]
print('path of the script: ' + scriptPath)
print('downloading file to: ' + downloadPath)
downloadFile(url, downloadPath + fileName)
print('file downloaded...')
print('exiting program...')
You can use this library:
https://github.com/kmfish/MultiTypeListViewAdapter (written by me)
Setup adapter:
adapter = new BaseRecyclerAdapter();
adapter.registerDataAndItem(TextModel.class, LineListItem1.class);
adapter.registerDataAndItem(ImageModel.class, LineListItem2.class);
adapter.registerDataAndItem(AbsModel.class, AbsLineItem.class);
For each line item:
public class LineListItem1 extends BaseListItem<TextModel, LineListItem1.OnItem1ClickListener> {
TextView tvName;
TextView tvDesc;
@Override
public int onGetLayoutRes() {
return R.layout.list_item1;
}
@Override
public void bindViews(View convertView) {
Log.d("item1", "bindViews:" + convertView);
tvName = (TextView) convertView.findViewById(R.id.text_name);
tvDesc = (TextView) convertView.findViewById(R.id.text_desc);
tvName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (null != attachInfo) {
attachInfo.onNameClick(getData());
}
}
});
tvDesc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (null != attachInfo) {
attachInfo.onDescClick(getData());
}
}
});
}
@Override
public void updateView(TextModel model, int pos) {
if (null != model) {
Log.d("item1", "updateView model:" + model + "pos:" + pos);
tvName.setText(model.getName());
tvDesc.setText(model.getDesc());
}
}
public interface OnItem1ClickListener {
void onNameClick(TextModel model);
void onDescClick(TextModel model);
}
}
Use the following syntax:
ALTER TABLE your_table
MODIFY COLUMN column1 datatype,
MODIFY COLUMN column2 datatype,
... ... ... ... ...
... ... ... ... ...
Based on that, your ALTER
command should be:
ALTER TABLE webstore.Store
MODIFY COLUMN ShortName VARCHAR(100),
MODIFY COLUMN UrlShort VARCHAR(100)
Note that:
MODIFY
statements.MODIFY
statements for two separate columns.This is the standard format of the MODIFY
statement for an ALTER
command on multiple columns in a MySQL table.
Take a look at the following: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html and Alter multiple columns in a single statement
Hello I was searching for a solution to reverse sorting a two dimensional numpy array, and I couldn't find anything that worked, but I think I have stumbled on a solution which I am uploading just in case anyone is in the same boat.
x=np.sort(array)
y=np.fliplr(x)
np.sort sorts ascending which is not what you want, but the command fliplr flips the rows left to right! Seems to work!
Hope it helps you out!
I guess it's similar to the suggest about -np.sort(-a) above but I was put off going for that by comment that it doesn't always work. Perhaps my solution won't always work either however I have tested it with a few arrays and seems to be OK.
You can just substract two date objects.
var d1 = new Date(); //"now"
var d2 = new Date("2011/02/01") // some date
var diff = Math.abs(d1-d2); // difference in milliseconds
Most answers are using iloc
which is good for selection by position.
If you need selection-by-label loc
would be more convenient.
For getting a value explicitly (equiv to deprecated df.get_value('a','A'))
# this is also equivalent to df1.at['a','A'] In [55]: df1.loc['a', 'A'] Out[55]: 0.13200317033032932
Update:
Short answer - You should almost always be using the utf8mb4
charset and utf8mb4_unicode_ci
collation.
To alter database:
ALTER DATABASE dbname CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
See:
Aaron's comment on this answer How to make MySQL handle UTF-8 properly
What's the difference between utf8_general_ci and utf8_unicode_ci
Conversion guide: https://dev.mysql.com/doc/refman/5.5/en/charset-unicode-conversion.html
Original Answer:
MySQL 4.1 and above has a default character set of UTF-8. You can verify this in your my.cnf
file, remember to set both client and server (default-character-set
and character-set-server
).
If you have existing data that you wish to convert to UTF-8, dump your database, and import it back as UTF-8 making sure:
SET NAMES utf8
before you query/insert into the databaseDEFAULT CHARSET=utf8
when creating new tablesmy.cnf
). remember any languages you use (such as PHP) must be UTF-8 as well. Some versions of PHP will use their own MySQL client library, which may not be UTF-8 aware.If you do want to migrate existing data remember to backup first! Lots of weird choping of data can happen when things don't go as planned!
Some resources:
We can use [(ngModel)] in following way and have a value selection variable radioSelected
app.component.html
<div class="text-center mt-5">
<h4>Selected value is {{radioSel.name}}</h4>
<div>
<ul class="list-group">
<li class="list-group-item" *ngFor="let item of itemsList">
<input type="radio" [(ngModel)]="radioSelected" name="list_name" value="{{item.value}}" (change)="onItemChange(item)"/>
{{item.name}}
</li>
</ul>
</div>
<h5>{{radioSelectedString}}</h5>
</div>
app.component.ts
import {Item} from '../app/item';
import {ITEMS} from '../app/mock-data';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
radioSel:any;
radioSelected:string;
radioSelectedString:string;
itemsList: Item[] = ITEMS;
constructor() {
this.itemsList = ITEMS;
//Selecting Default Radio item here
this.radioSelected = "item_3";
this.getSelecteditem();
}
// Get row item from array
getSelecteditem(){
this.radioSel = ITEMS.find(Item => Item.value === this.radioSelected);
this.radioSelectedString = JSON.stringify(this.radioSel);
}
// Radio Change Event
onItemChange(item){
this.getSelecteditem();
}
}
Sample Data for Listing
export const ITEMS: Item[] = [
{
name:'Item 1',
value:'item_1'
},
{
name:'Item 2',
value:'item_2'
},
{
name:'Item 3',
value:'item_3'
},
{
name:'Item 4',
value:'item_4'
},
{
name:'Item 5',
value:'item_5'
}
];
You can't do it in HTML. You can in CSS. Create a new CSS file and write:
p {
font-size: (some number);
}
If that doesn't work make sure you don't have any "pre" tags, which make your code a bit smaller.
Good point that view is appeared if it's already in window hierarchy stack. thus we can extend our classes for this functionality.
extension UIViewController {
var isViewAppeared: Bool { viewIfLoaded?.isAppeared == true }
}
extension UIView {
var isAppeared: Bool { window != nil }
}
You need to say math.sqrt
when you use it. Or, do from math import sqrt
.
Hmm, I just read your question more thoroughly.... How are you importing math
? I just tried import math
and then math.sqrt
which worked perfectly. Are you doing something like import math as m
? If so, then you have to prefix the function with m
(or whatever name you used after as
).
pow
is working because there are two versions: an always available version in __builtin__
, and another version in math
.
You need to use the name of your form, as well as ng-disabled: Here's a demo on Plunker
<form name="myForm">
<input name="myText" type="text" ng-model="mytext" required />
<button ng-disabled="myForm.$invalid">Save</button>
</form>
If you use the Oracle native data provider rather than the Microsoft driver then you can get at all field types
Dim cn As New Oracle.DataAccess.Client.OracleConnection
Dim cm As New Oracle.DataAccess.Client.OracleCommand
Dim dr As Oracle.DataAccess.Client.OracleDataReader
The connection string does not require a Provider value so you would use something like:
"Data Source=myOracle;UserID=Me;Password=secret"
Open the connection:
cn.ConnectionString = "Data Source=myOracle;UserID=Me;Password=secret"
cn.Open()
Attach the command and set the Sql statement
cm.Connection = cn
cm.CommandText = strCommand
Set the Fetch size. I use 4000 because it's as big as a varchar can be
cm.InitialLONGFetchSize = 4000
Start the reader and loop through the records/columns
dr = cm.ExecuteReader
Do while dr.read()
strMyLongString = dr(i)
Loop
You can be more specific with the read, eg dr.GetOracleString(i) dr.GetOracleClob(i) etc. if you first identify the data type in the column. If you're reading a LONG datatype then the simple dr(i)
or dr.GetOracleString(i)
works fine. The key is to ensure that the InitialLONGFetchSize is big enough for the datatype. Note also that the native driver does not support CommandBehavior.SequentialAccess
for the data reader but you don't need it and also, the LONG field does not even have to be the last field in the select statement.
Do you have to use window.open
? What about using window.location="http://example.com"
?
Azure Data Studio with Postgres addin is the tool of choice to manage postgres databases for me. Check it out. https://docs.microsoft.com/en-us/sql/azure-data-studio/quickstart-postgres?view=sql-server-ver15
XmlDocument doc = new XmlDocument();
doc.Load("MonFichierXML.xml");
XmlNode node = doc.SelectSingleNode("Magasin");
XmlNodeList prop = node.SelectNodes("Items");
foreach (XmlNode item in prop)
{
items Temp = new items();
Temp.AssignInfo(item);
lstitems.Add(Temp);
}
You Don't need to close the wrapped reader/writer.
If you've taken a look at the docs (Reader.close()
,Writer.close()
), You'll see that in Reader.close()
it says:
Closes the stream and releases any system resources associated with it.
Which just says that it "releases any system resources associated with it". Even though it doesn't confirm.. it gives you a nudge to start looking deeper. and if you go to Writer.close()
it only states that it closes itself.
In such cases, we refer to OpenJDK to take a look at the source code.
At BufferedWriter Line 265 you'll see out.close()
. So it's not closing itself.. It's something else. If you search the class for occurences of "out
" you'll notice that in the constructor at Line 87 that out
is the writer the class wraps where it calls another constructor and then assigning out
parameter to it's own out
variable..
So.. What about others? You can see similar code at BufferedReader Line 514, BufferedInputStream Line 468 and InputStreamReader Line 199. Others i don't know but this should be enough to assume that they do.
The way of dknaack does not work for me, I found this solution as well:
@Html.DropDownList("Chapters", ViewBag.Chapters as SelectList,
"Select chapter", new { @onchange = "location = this.value;" })
where
@Html.DropDownList(controlName, ViewBag.property + cast, "Default value", @onchange event)
In the controller you can add:
DbModel db = new DbModel(); //entity model of Entity Framework
ViewBag.Chapters = new SelectList(db.T_Chapter, "Id", "Name");
You can use this function, which creates a tempfile in the filesystem and returns the path to the downloaded file if everything worked fine:
function getFileContents($url)
{
// Workaround: Save temp file
$img = tempnam(sys_get_temp_dir(), 'pdf-');
$img .= '.' . pathinfo($url, PATHINFO_EXTENSION);
$fp = fopen($img, 'w+');
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec($ch);
curl_close($ch);
fclose($fp);
return $result ? $img : false;
}
Java (at least 5 and 6, java 7 Paths solved most) has a problem with UNC and URI. Eclipse team wrapped it up here : http://wiki.eclipse.org/Eclipse/UNC_Paths
From java.io.File javadocs, the UNC prefix is "////", and java.net.URI handles file:////host/path (four slashes).
More details on why this happens and possible problems it causes in other URI and URL methods can be found in the list of bugs at the end of the link given above.
Using these informations, Eclipse team developed org.eclipse.core.runtime.URIUtil class, which source code can probably help out when dealing with UNC paths.
This is the most simple solution for me:
$tStamp = Get-Date -format yyyy_MM_dd_HHmmss
$tStamp = Get-Date (get-date).AddMonths(6).Date -Format yyyyMMdd
For compatibility and ease of use it's often better to use FIND to do this.
You must also consider if you would like to match case sensitively or case insensitively.
The method with 78 points (I believe I was referring to paxdiablo's post) will only match Case Sensitively, so you must put a separate check for every case variation for every possible iteration you may want to match.
( What a pain! At only 3 letters that means 9 different tests in order to accomplish the check! )
In addition, many times it is preferable to match command output, a variable in a loop, or the value of a pointer variable in your batch/CMD which is not as straight forward.
For these reasons this is a preferable alternative methodology:
Use: Find [/I] [/V] "Characters to Match"
[/I] (case Insensitive) [/V] (Must NOT contain the characters)
As Single Line:
ECHO.%Variable% | FIND /I "ABC">Nul && ( Echo.Found "ABC" ) || ( Echo.Did not find "ABC" )
Multi-line:
ECHO.%Variable%| FIND /I "ABC">Nul && (
Echo.Found "ABC"
) || (
Echo.Did not find "ABC"
)
As mentioned this is great for things which are not in variables which allow string substitution as well:
FOR %A IN (
"Some long string with Spaces does not contain the expected string"
oihu AljB
lojkAbCk
Something_Else
"Going to evaluate this entire string for ABC as well!"
) DO (
ECHO.%~A| FIND /I "ABC">Nul && (
Echo.Found "ABC" in "%A"
) || ( Echo.Did not find "ABC" )
)
Output From a command:
NLTest | FIND /I "ABC">Nul && ( Echo.Found "ABC" ) || ( Echo.Did not find "ABC" )
As you can see this is the superior way to handle the check for multiple reasons.
A modern ES6 approach. Select the form with any method you like. Use the spread operator to convert HTMLFormControlsCollection to an Array, then the forEach
method is available. [...form.elements].forEach
Update: Array.from
is a nicer alternative to spread Array.from(form.elements)
it's slightly clearer behaviour.
An example below iterates over every input in the form. You can filter out certain input types by checking input.type != "submit"
const forms = document.querySelectorAll('form');
const form = forms[0];
Array.from(form.elements).forEach((input) => {
console.log(input);
});
_x000D_
<div>
<h1>Input Form Selection</h1>
<form>
<label>
Foo
<input type="text" placeholder="Foo" name="Foo" />
</label>
<label>
Password
<input type="password" placeholder="Password" />
</label>
<label>
Foo
<input type="text" placeholder="Bar" name="Bar" />
</label>
<span>Ts & Cs</span>
<input type="hidden" name="_id" />
<input type="submit" name="_id" />
</form>
</div>
_x000D_
Use Windows Terminal and configure a starting directory.
Partial settings.json
:
{
// Make changes here to the cmd.exe profile.
"guid": "{0caa0dad-35be-5f56-a8ff-afceeeaa6101}",
"name": "Command Prompt",
"commandline": "cmd.exe",
"hidden": false,
"startingDirectory": "C:\\DEV"
},
I had the same error. My issue was using the wrong parameter name when binding.
Notice :tokenHash in the query, but :token_hash when binding. Fixing one or the other resolves the error in this instance.
// Prepare DB connection
$sql = 'INSERT INTO rememberedlogins (token_hash,user_id,expires_at)
VALUES (:tokenHash,:user_id,:expires_at)';
$db = static::getDB();
$stmt = $db->prepare($sql);
// Bind values
$stmt->bindValue(':token_hash',$hashed_token,PDO::PARAM_STR);
It allows you to compute correlation coefficients of >2 data sets, e.g.
>>> from numpy import *
>>> a = array([1,2,3,4,6,7,8,9])
>>> b = array([2,4,6,8,10,12,13,15])
>>> c = array([-1,-2,-2,-3,-4,-6,-7,-8])
>>> corrcoef([a,b,c])
array([[ 1. , 0.99535001, -0.9805214 ],
[ 0.99535001, 1. , -0.97172394],
[-0.9805214 , -0.97172394, 1. ]])
Here we can get the correlation coefficient of a,b (0.995), a,c (-0.981) and b,c (-0.972) at once. The two-data-set case is just a special case of N-data-set class. And probably it's better to keep the same return type. Since the "one value" can be obtained simply with
>>> corrcoef(a,b)[1,0]
0.99535001355530017
there's no big reason to create the special case.
In my case it was because the file was minified with wrong scope. Use Array!
app.controller('StoreController', ['$http', function($http) {
...
}]);
Coffee syntax:
app.controller 'StoreController', Array '$http', ($http) ->
...
I had a similar issue, but in my case it turned out that I used case insensitive collation - utf8_general_ci
.
Thus, when I tried to insert two strings which were different in a case-sensitive comparison, but the same in the case-insensitive one, MySQL fired the error and I couldn't understand what a problem, because I used a case-sensitive search.
The solution is to change the collation of a table, e.g. I used utf8_bin
which is case-sensitive (or utf8_general_cs
should be appropriate one too).
Or you can use a data file to put many person objects in to a list or array. You do need to use the System.IO for this. And you need a data file which contains all the information about the objects.
A method for it would look something like this:
static void ReadFile()
{
using(StreamWriter writer = new StreamWriter(@"Data.csv"))
{
string line = null;
line = reader.ReadLine();
while(null!= (line = reader.ReadLine())
{
string[] values = line.Split(',');
string name = values[0];
int age = int.Parse(values[1]);
}
Person person = new Person(name, age);
}
}
You can pass your json Input as a POST request along with authorization header in this way
public static JSONObject getHttpConn(String json){
JSONObject jsonObject=null;
try {
HttpPost httpPost=new HttpPost("http://google.com/");
org.apache.http.client.HttpClient client = HttpClientBuilder.create().build();
StringEntity stringEntity=new StringEntity("d="+json);
httpPost.addHeader("content-type", "application/x-www-form-urlencoded");
String authorization="test:test@123";
String encodedAuth = "Basic " + Base64.encode(authorization.getBytes());
httpPost.addHeader("Authorization", security.get("Authorization"));
httpPost.setEntity(stringEntity);
HttpResponse reponse=client.execute(httpPost);
InputStream inputStream=reponse.getEntity().getContent();
String jsonResponse=IOUtils.toString(inputStream);
jsonObject=JSONObject.fromObject(jsonResponse);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonObject;
}
This Method will return a json response.In same way you can use GET method
$(':text').attr("disabled", "disabled");
sets all textbox to disabled mode.
You can do in another way like giving each textbox id. By doing this code weight will be more and performance issue will be there.
So better have $(':text').attr("disabled", "disabled");
approach.
SimpleDateFormat dateFormat = new SimpleDateFormat( "LLLL", Locale.getDefault() );
dateFormat.format( date );
For some languages (e.g. Russian) this is the only correct way to get the stand-alone month names.
This is what you get, if you use getDisplayName
from the Calendar
or DateFormatSymbols
for January:
?????? (which is correct for a complete date string: "10 ??????, 2014")
but in case of a stand-alone month name you would expect:
??????
Something to note here. We had the same issue with Windows VM's running on an ESXi host. The time sync was turned on in VMWare Tools on the guest, but the guest clocks were consistently off (by about 30 seconds) from the host clock. The ESXi host was configured to get time updates from an internal time server.
It turns out we had the Internet Time setting turned on in the Windows VM's (Control Panel > Date and Time > Internet Time tab) so the guest was getting time updates from two places and the internet time was winning. We turned that off and now the guest clocks are good, getting their time exclusively from the ESXi host.
The accepted answer (its image) is wrong, at least now in QT5. Instead you should assign a layout to the root object/widget (pointing to the aforementioned image, it should be the MainWindow
instead of centralWidget
). Also note that you must have at least one QObject
created beneath it for this to work. Do this and your ui will become responsive to window resizing.
You should use the ARG
directive in your Dockerfile which is meant for this purpose.
The
ARG
instruction defines a variable that users can pass at build-time to the builder with the docker build command using the--build-arg <varname>=<value>
flag.
So your Dockerfile will have this line:
ARG request_domain
or if you'd prefer a default value:
ARG request_domain=127.0.0.1
Now you can reference this variable inside your Dockerfile:
ENV request_domain=$request_domain
then you will build your container like so:
$ docker build --build-arg request_domain=mydomain Dockerfile
Note 1: Your image will not build if you have referenced an ARG
in your Dockerfile but excluded it in --build-arg
.
Note 2: If a user specifies a build argument that was not defined in the Dockerfile, the build outputs a warning:
[Warning] One or more build-args [foo] were not consumed.
I have solved a similar problem by first importing the text into an excel spreadsheet, then using the Substitute function to replace both the single and double quotes as required by SQL Server, eg. SUBSTITUTE(SUBSTITUTE(A1, "'", "''"), """", "\""")
In my case, I had many rows (each a line of data to be cleaned then inserted) and had the spreadsheet automatically generate insert queries for the text once the substitution had been done eg. ="INSERT INTO [dbo].[tablename] ([textcolumn]) VALUES ('" & SUBSTITUTE(SUBSTITUTE(A1, "'", "''"), """", "\""") & "')"
I hope that helps.
Why don't you disable the button and enable it after you finish the event?
<input type="button" id="xx" onclick="checkEnableSubmit('true');yourFunction();">
<script type="text/javascript">
function checkEnableSubmit(status) {
document.getElementById("xx").disabled = status;
}
function yourFunction(){
//add your functionality
checkEnableSubmit('false');
}
</script>
Happy coding !!!
I recently needed to do this for a project and I ended up using IronPython to do it. You can declare an instance of the engine, and then pass any valid python expression and get the result. If you're just doing simple math expressions, then it would suffice. My code ended up looking similar to:
IronPython.Hosting.PythonEngine pythonEngine = new IronPython.Hosting.PythonEngine();
string expression = "3*(2+4)";
double result = pythonEngine.EvaluateAs<double>(expression);
You'd probably not want to create the engine for each expression. You also need a reference to IronPython.dll
Just append an empty string to the end. It forces Excel to see it for what it is.
For example:
=IFERROR(1/1/INDEX(A,B,C) & "","")
From w3schools.com: Made compatible with Firefox Sept, 2016
<input type="text" onfocusout="myFunction()">
In case you're using a UITabBarController
:
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.tabBarController?.navigationItem.hidesBackButton = true
}
You should always use "throw;" to rethrow the exceptions in .NET,
Refer this, http://weblogs.asp.net/bhouse/archive/2004/11/30/272297.aspx
Basically MSIL (CIL) has two instructions - "throw" and "rethrow":
Basically I can see the reason why "throw ex" overrides the stack trace.
Use Console.KeyAvailable
so that you only call ReadKey
when you know it won't block:
Console.WriteLine("Press ESC to stop");
do {
while (! Console.KeyAvailable) {
// Do something
}
} while (Console.ReadKey(true).Key != ConsoleKey.Escape);
The -B
switch to make, whose long form is --always-make
, tells make
to disregard timestamps and make the specified targets. This may defeat the purpose of using make, but it may be what you need.
urllib went through some changes in Python3 and can now be imported from the parse submodule
>>> from urllib.parse import quote
>>> quote('"')
'%22'
I'm not sure that I fully understand the question, but from the title of your question, I'm guessing that what you're looking for is pager.setCurrentItem( num )
. That allows you to programatically switch to another page within the ViewPager
.
I'd need to see a stack trace from logcat to be more specific if this is not the problem.
Clone Temporary Table Structure to New Physical Table in SQL Server
we will see how to Clone Temporary Table Structure to New Physical Table in SQL Server.This is applicable for both Azure SQL db and on-premises.
Demo SQL Script
IF OBJECT_ID('TempDB..#TempTable') IS NOT NULL
DROP TABLE #TempTable;
SELECT 1 AS ID,'Arul' AS Names
INTO
#TempTable;
SELECT * FROM #TempTable;
METHOD 1
SELECT * INTO TempTable1 FROM #TempTable WHERE 1=0;
EXEC SP_HELP TempTable1;
METHOD 2
SELECT TOP 0 * INTO TempTable1 FROM #TempTable;
EXEC SP_HELP TempTable1;
When you make a POST request, you have to encode the data that forms the body of the request in some way.
HTML forms provide three methods of encoding.
application/x-www-form-urlencoded
(the default)multipart/form-data
text/plain
Work was being done on adding application/json
, but that has been abandoned.
(Other encodings are possible with HTTP requests generated using other means than an HTML form submission. JSON is a common format for use with web services and some still use SOAP.)
The specifics of the formats don't matter to most developers. The important points are:
text/plain
.When you are writing client-side code:
multipart/form-data
when your form includes any <input type="file">
elementsmultipart/form-data
or application/x-www-form-urlencoded
but application/x-www-form-urlencoded
will be more efficientWhen you are writing server-side code:
Most (such as Perl's CGI->param
or the one exposed by PHP's $_POST
superglobal) will take care of the differences for you. Don't bother trying to parse the raw input received by the server.
Sometimes you will find a library that can't handle both formats. Node.js's most popular library for handling form data is body-parser which cannot handle multipart requests (but has documentation which recommends some alternatives which can).
If you are writing (or debugging) a library for parsing or generating the raw data, then you need to start worrying about the format. You might also want to know about it for interest's sake.
application/x-www-form-urlencoded
is more or less the same as a query string on the end of the URL.
multipart/form-data
is significantly more complicated but it allows entire files to be included in the data. An example of the result can be found in the HTML 4 specification.
text/plain
is introduced by HTML 5 and is useful only for debugging — from the spec: They are not reliably interpretable by computer — and I'd argue that the others combined with tools (like the Network Panel in the developer tools of most browsers) are better for that).
Simply replace message parameter passed in clientSocket.sendto(message,(serverName, serverPort))
to clientSocket.sendto(message.encode(),(serverName, serverPort))
. Then you would successfully run in in python3
try using discount.toFixed(2);
Set 'center_horizontal' and 'center_vertical' or just 'center' of the layout_gravity attribute of the widget
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MovieActivity"
android:id="@+id/mainContainerMovie"
>
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#3a3f51b5"
/>
<ProgressBar
android:id="@+id/movieprogressbar"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal" />
</FrameLayout>
Expanding on brettdj's answer, in order to parse disjoint embedded digits into separate numbers:
Sub TestNumList()
Dim NumList As Variant 'Array
NumList = GetNums("34d1fgd43g1 dg5d999gdg2076")
Dim i As Integer
For i = LBound(NumList) To UBound(NumList)
MsgBox i + 1 & ": " & NumList(i)
Next i
End Sub
Function GetNums(ByVal strIn As String) As Variant 'Array of numeric strings
Dim RegExpObj As Object
Dim NumStr As String
Set RegExpObj = CreateObject("vbscript.regexp")
With RegExpObj
.Global = True
.Pattern = "[^\d]+"
NumStr = .Replace(strIn, " ")
End With
GetNums = Split(Trim(NumStr), " ")
End Function
On OSX Snow Leopard
launchctl unload /System/Library/LaunchDaemons/org.mysql.mysqld.plist
A really nicer way would be creating a class (or classes) for the exceptions.
Something like:
class ConfigurationError : public std::exception {
public:
ConfigurationError();
};
class ConfigurationLoadError : public ConfigurationError {
public:
ConfigurationLoadError(std::string & filename);
};
The reason is that exceptions are much more preferable than just transferring a string. Providing different classes for the errors, you give developers a chance to handle a particular error in a corresponded way (not just display an error message). People catching your exception can be as specific as they need if you use a hierarchy.
a) One may need to know the specific reason
} catch (const ConfigurationLoadError & ex) {
// ...
} catch (const ConfigurationError & ex) {
a) another does not want to know details
} catch (const std::exception & ex) {
You can find some inspiration on this topic in https://books.google.ru/books?id=6tjfmnKhT24C Chapter 9
Also, you can provide a custom message too, but be careful - it is not safe to compose a message with either std::string
or std::stringstream
or any other way which can cause an exception.
Generally, there is no difference whether you allocate memory (work with strings in C++ manner) in the constructor of the exception or just before throwing - std::bad_alloc
exception can be thrown before the one which you really want.
So, a buffer allocated on the stack (like in Maxim's answer) is a safer way.
It is explained very well at http://www.boost.org/community/error_handling.html
So, the nicer way would be a specific type of the exception and be avoiding composing the formatted string (at least when throwing).
I think COALESCE
function partially similar to the isnull
, but try it.
Why don't you go for null handling functions through application programs, it is better alternative.
You can easily do this
const shopId = new URLSearchParams(window.location.search).get('shop_id');
console.log(shopId);
The reason it is throwing that exception is because you have the argument rb
, which opens the file in binary mode. Change that to r
, which will by default open the file in text mode.
Your code:
import csv
ifile = open('sample.csv', "rb")
read = csv.reader(ifile)
for row in read :
print (row)
New code:
import csv
ifile = open('sample.csv', "r")
read = csv.reader(ifile)
for row in read :
print (row)
Reason : your ID is not able to find the .project file. This happens in git commit where many time people don't push .project file
Solution : If you have maven install then use following stapes
Enjoy!
In new version Android
private void getWifiInfo(Context context) {
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
Network[] networks = connManager.getAllNetworks();
if(networks == null || networks.length == 0)
return;
for( int i = 0; i < networks.length; i++) {
Network ntk = networks[i];
NetworkInfo ntkInfo = connManager.getNetworkInfo(ntk);
if (ntkInfo.getType() == ConnectivityManager.TYPE_WIFI && ntkInfo.isConnected() ) {
final WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
final WifiInfo connectionInfo = wifiManager.getConnectionInfo();
if (connectionInfo != null) {
// add some code here
}
}
}
}
and add premission too
This works:
df['date'].dt.year
Now:
df['year'] = df['date'].dt.year
df['month'] = df['date'].dt.month
gives this data frame:
date Count year month
0 2010-06-30 525 2010 6
1 2010-07-30 136 2010 7
2 2010-08-31 125 2010 8
3 2010-09-30 84 2010 9
4 2010-10-29 4469 2010 10
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="btn-group btn-block">_x000D_
<button type="button" data-toggle="dropdown" class="btn btn-default btn-xs btn-block dropdown-toggle">Actions <span class="caret"></span>_x000D_
<span class="sr-only">Toggle Dropdown</span></button><ul role="menu" class="dropdown-menu"><li><a href="#">Action one</a></li><li class="divider"></li><li><a href="#" >Action Two</a></li></ul></div>
_x000D_
Note that if you are using a virtual environment (as in shared hosting) then you must adjust your path to python, e.g: /home/user/mypython/bin/python ./cgi-bin/test.py
The simplest way to extract data from a DataTable
when you have multiple data types (not just strings) is to use the Field<T>
extension method available in the System.Data.DataSetExtensions
assembly.
var id = row.Field<int>("ID"); // extract and parse int
var name = row.Field<string>("Name"); // extract string
From MSDN, the Field<T>
method:
Provides strongly-typed access to each of the column values in the DataRow.
This means that when you specify the type it will validate and unbox the object.
For example:
// iterate over the rows of the datatable
foreach (var row in table.AsEnumerable()) // AsEnumerable() returns IEnumerable<DataRow>
{
var id = row.Field<int>("ID"); // int
var name = row.Field<string>("Name"); // string
var orderValue = row.Field<decimal>("OrderValue"); // decimal
var interestRate = row.Field<double>("InterestRate"); // double
var isActive = row.Field<bool>("Active"); // bool
var orderDate = row.Field<DateTime>("OrderDate"); // DateTime
}
It also supports nullable types:
DateTime? date = row.Field<DateTime?>("DateColumn");
This can simplify extracting data from DataTable
as it removes the need to explicitly convert or parse the object into the correct types.
pass
in Python basically does nothing, but unlike a comment it is not ignored by interpreter. So you can take advantage of it in a lot of places by making it a place holder:
1: Can be used in class
class TestClass:
pass
2: Can be use in loop and conditional statements:
if (something == true): # used in conditional statement
pass
while (some condition is true): # user is not sure about the body of the loop
pass
3: Can be used in function :
def testFunction(args): # programmer wants to implement the body of the function later
pass
pass
is mostly used when programmer does not want to give implementation at the moment but still wants to create a certain class/function/conditional statement which can be used later on. Since the Python interpreter does not allow for blank or unimplemented class/function/conditional statement it gives an error:
IndentationError: expected an indented block
pass
can be used in such scenarios.
The root of the problem is that you are unknowingly using the Frame
class from the ttk
package rather than from the tkinter
package. The one from ttk
does not support the background option.
This is the main reason why you shouldn't do global imports -- you can overwrite the definition of classes and commands.
I recommend doing imports like this:
import tkinter as tk
import ttk
Then you prefix the widgets with either tk
or ttk
:
f1 = tk.Frame(..., bg=..., fg=...)
f2 = ttk.Frame(..., style=...)
It then becomes instantly obvious which widget you are using, at the expense of just a tiny bit more typing. If you had done this, this error in your code would never have happened.
Try to complete cmake process with following libs:
sudo apt-get install cmake libblkid-dev e2fslibs-dev libboost-all-dev libaudit-dev
The package BBmisc
now contains the function capitalizeStrings
.
library("BBmisc")
capitalizeStrings(c("the taIl", "wags The dOg", "That Looks fuNny!")
, all.words = TRUE, lower.back = TRUE)
[1] "The Tail" "Wags The Dog" "That Looks Funny!"
json = " { \"success\" : false, \"errors\": { \"text\" : \"??????!\" } }";
return new MemoryStream(Encoding.UTF8.GetBytes(json));
The issue is with the facebook cache and solution is to refresh the facebook cache by going to the link. https://developers.facebook.com/tools/debug/og/object/
and pressing the button "Fetch New Scrape information".
Hope it helps
I think this will do what you need:
var uri = new Uri(hreflink);
var filename = uri.Segments.Last();
UTC
is definitely a valid timezone. It is simply an abbreviation for Coordinated Universal Time. In addition, remember that date_default_timezone_set
accepts one of the following values:
$timezones=array(
"America/Adak",
"America/Argentina/Buenos_Aires",
"America/Argentina/La_Rioja",
"America/Argentina/San_Luis",
"America/Atikokan",
"America/Belem",
"America/Boise",
"America/Caracas",
"America/Chihuahua",
"America/Cuiaba",
"America/Denver",
"America/El_Salvador",
"America/Godthab",
"America/Guatemala",
"America/Hermosillo",
"America/Indiana/Tell_City",
"America/Inuvik",
"America/Kentucky/Louisville",
"America/Lima",
"America/Managua",
"America/Mazatlan",
"America/Mexico_City",
"America/Montreal",
"America/Nome",
"America/Ojinaga",
"America/Port-au-Prince",
"America/Rainy_River",
"America/Rio_Branco",
"America/Santo_Domingo",
"America/St_Barthelemy",
"America/St_Vincent",
"America/Tijuana",
"America/Whitehorse",
"America/Anchorage",
"America/Argentina/Catamarca",
"America/Argentina/Mendoza",
"America/Argentina/Tucuman",
"America/Atka",
"America/Belize",
"America/Buenos_Aires",
"America/Catamarca",
"America/Coral_Harbour",
"America/Curacao",
"America/Detroit",
"America/Ensenada",
"America/Goose_Bay",
"America/Guayaquil",
"America/Indiana/Indianapolis",
"America/Indiana/Vevay",
"America/Iqaluit",
"America/Kentucky/Monticello",
"America/Los_Angeles",
"America/Manaus",
"America/Mendoza",
"America/Miquelon",
"America/Montserrat",
"America/Noronha",
"America/Panama",
"America/Port_of_Spain",
"America/Rankin_Inlet",
"America/Rosario",
"America/Sao_Paulo",
"America/St_Johns",
"America/Swift_Current",
"America/Toronto",
"America/Winnipeg",
"America/Anguilla",
"America/Argentina/ComodRivadavia",
"America/Argentina/Rio_Gallegos",
"America/Argentina/Ushuaia",
"America/Bahia",
"America/Blanc-Sablon",
"America/Cambridge_Bay",
"America/Cayenne",
"America/Cordoba",
"America/Danmarkshavn",
"America/Dominica",
"America/Fort_Wayne",
"America/Grand_Turk",
"America/Guyana",
"America/Indiana/Knox",
"America/Indiana/Vincennes",
"America/Jamaica",
"America/Knox_IN",
"America/Louisville",
"America/Marigot",
"America/Menominee",
"America/Moncton",
"America/Nassau",
"America/North_Dakota/Beulah",
"America/Pangnirtung",
"America/Porto_Acre",
"America/Recife",
"America/Santa_Isabel",
"America/Scoresbysund",
"America/St_Kitts",
"America/Tegucigalpa",
"America/Tortola",
"America/Yakutat",
"America/Antigua",
"America/Argentina/Cordoba",
"America/Argentina/Salta",
"America/Aruba",
"America/Bahia_Banderas",
"America/Boa_Vista",
"America/Campo_Grande",
"America/Cayman",
"America/Costa_Rica",
"America/Dawson",
"America/Edmonton",
"America/Fortaleza",
"America/Grenada",
"America/Halifax",
"America/Indiana/Marengo",
"America/Indiana/Winamac",
"America/Jujuy",
"America/Kralendijk",
"America/Lower_Princes",
"America/Martinique",
"America/Merida",
"America/Monterrey",
"America/New_York",
"America/North_Dakota/Center",
"America/Paramaribo",
"America/Porto_Velho",
"America/Regina",
"America/Santarem",
"America/Shiprock",
"America/St_Lucia",
"America/Thule",
"America/Vancouver",
"America/Yellowknife",
"America/Araguaina",
"America/Argentina/Jujuy",
"America/Argentina/San_Juan",
"America/Asuncion",
"America/Barbados",
"America/Bogota",
"America/Cancun",
"America/Chicago",
"America/Creston",
"America/Dawson_Creek",
"America/Eirunepe",
"America/Glace_Bay",
"America/Guadeloupe",
"America/Havana",
"America/Indiana/Petersburg",
"America/Indianapolis",
"America/Juneau",
"America/La_Paz",
"America/Maceio",
"America/Matamoros",
"America/Metlakatla",
"America/Montevideo",
"America/Nipigon",
"America/North_Dakota/New_Salem",
"America/Phoenix",
"America/Puerto_Rico",
"America/Resolute",
"America/Santiago",
"America/Sitka",
"America/St_Thomas",
"America/Thunder_Bay",
"America/Virgin",
"Indian/Antananarivo",
"Indian/Kerguelen",
"Indian/Reunion",
"Australia/ACT",
"Australia/Currie",
"Australia/Lindeman",
"Australia/Perth",
"Australia/Victoria",
"Europe/Amsterdam",
"Europe/Berlin",
"Europe/Chisinau",
"Europe/Helsinki",
"Europe/Kiev",
"Europe/Madrid",
"Europe/Moscow",
"Europe/Prague",
"Europe/Sarajevo",
"Europe/Tallinn",
"Europe/Vatican",
"Europe/Zagreb",
"Pacific/Apia",
"Pacific/Efate",
"Pacific/Galapagos",
"Pacific/Johnston",
"Pacific/Marquesas",
"Pacific/Noumea",
"Pacific/Ponape",
"Pacific/Tahiti",
"Pacific/Wallis",
"Indian/Chagos",
"Indian/Mahe",
"Australia/Adelaide",
"Australia/Darwin",
"Australia/Lord_Howe",
"Australia/Queensland",
"Australia/West",
"Europe/Andorra",
"Europe/Bratislava",
"Europe/Copenhagen",
"Europe/Isle_of_Man",
"Europe/Lisbon",
"Europe/Malta",
"Europe/Nicosia",
"Europe/Riga",
"Europe/Simferopol",
"Europe/Tirane",
"Europe/Vienna",
"Europe/Zaporozhye",
"Pacific/Auckland",
"Pacific/Enderbury",
"Pacific/Gambier",
"Pacific/Kiritimati",
"Pacific/Midway",
"Pacific/Pago_Pago",
"Pacific/Port_Moresby",
"Pacific/Tarawa",
"Pacific/Yap",
"Africa/Abidjan",
"Africa/Asmera",
"Africa/Blantyre",
"Africa/Ceuta",
"Africa/Douala",
"Africa/Johannesburg",
"Africa/Kinshasa",
"Africa/Lubumbashi",
"Africa/Mbabane",
"Africa/Niamey",
"Africa/Timbuktu",
"Africa/Accra",
"Africa/Bamako",
"Africa/Brazzaville",
"Africa/Conakry",
"Africa/El_Aaiun",
"Africa/Juba",
"Africa/Lagos",
"Africa/Lusaka",
"Africa/Mogadishu",
"Africa/Nouakchott",
"Africa/Tripoli",
"Africa/Addis_Ababa",
"Africa/Bangui",
"Africa/Bujumbura",
"Africa/Dakar",
"Africa/Freetown",
"Africa/Kampala",
"Africa/Libreville",
"Africa/Malabo",
"Africa/Monrovia",
"Africa/Ouagadougou",
"Africa/Tunis",
"Africa/Algiers",
"Africa/Banjul",
"Africa/Cairo",
"Africa/Dar_es_Salaam",
"Africa/Gaborone",
"Africa/Khartoum",
"Africa/Lome",
"Africa/Maputo",
"Africa/Nairobi",
"Africa/Porto-Novo",
"Africa/Windhoek",
"Africa/Asmara",
"Africa/Bissau",
"Africa/Casablanca",
"Africa/Djibouti",
"Africa/Harare",
"Africa/Kigali",
"Africa/Luanda",
"Africa/Maseru",
"Africa/Ndjamena",
"Africa/Sao_Tome",
"Atlantic/Azores",
"Atlantic/Faroe",
"Atlantic/St_Helena",
"Atlantic/Bermuda",
"Atlantic/Jan_Mayen",
"Atlantic/Stanley",
"Atlantic/Canary",
"Atlantic/Madeira",
"Atlantic/Cape_Verde",
"Atlantic/Reykjavik",
"Atlantic/Faeroe",
"Atlantic/South_Georgia",
"Asia/Aden",
"Asia/Aqtobe",
"Asia/Baku",
"Asia/Calcutta",
"Asia/Dacca",
"Asia/Dushanbe",
"Asia/Hong_Kong",
"Asia/Jayapura",
"Asia/Kashgar",
"Asia/Kuala_Lumpur",
"Asia/Magadan",
"Asia/Novokuznetsk",
"Asia/Pontianak",
"Asia/Riyadh",
"Asia/Shanghai",
"Asia/Tehran",
"Asia/Ujung_Pandang",
"Asia/Vladivostok",
"Asia/Almaty",
"Asia/Ashgabat",
"Asia/Bangkok",
"Asia/Choibalsan",
"Asia/Damascus",
"Asia/Gaza",
"Asia/Hovd",
"Asia/Jerusalem",
"Asia/Kathmandu",
"Asia/Kuching",
"Asia/Makassar",
"Asia/Novosibirsk",
"Asia/Pyongyang",
"Asia/Saigon",
"Asia/Singapore",
"Asia/Tel_Aviv",
"Asia/Ulaanbaatar",
"Asia/Yakutsk",
"Asia/Amman",
"Asia/Ashkhabad",
"Asia/Beirut",
"Asia/Chongqing",
"Asia/Dhaka",
"Asia/Harbin",
"Asia/Irkutsk",
"Asia/Kabul",
"Asia/Katmandu",
"Asia/Kuwait",
"Asia/Manila",
"Asia/Omsk",
"Asia/Qatar",
"Asia/Sakhalin",
"Asia/Taipei",
"Asia/Thimbu",
"Asia/Ulan_Bator",
"Asia/Yekaterinburg",
"Asia/Anadyr",
"Asia/Baghdad",
"Asia/Bishkek",
"Asia/Chungking",
"Asia/Dili",
"Asia/Hebron",
"Asia/Istanbul",
"Asia/Kamchatka",
"Asia/Kolkata",
"Asia/Macao",
"Asia/Muscat",
"Asia/Oral",
"Asia/Qyzylorda",
"Asia/Samarkand",
"Asia/Tashkent",
"Asia/Thimphu",
"Asia/Urumqi",
"Asia/Yerevan",
"Asia/Aqtau",
"Asia/Bahrain",
"Asia/Brunei",
"Asia/Colombo",
"Asia/Dubai",
"Asia/Ho_Chi_Minh",
"Asia/Jakarta",
"Asia/Karachi",
"Asia/Krasnoyarsk",
"Asia/Macau",
"Asia/Nicosia",
"Asia/Phnom_Penh",
"Asia/Rangoon",
"Asia/Seoul",
"Asia/Tbilisi",
"Asia/Tokyo",
"Asia/Vientiane",
"Australia/Canberra",
"Australia/LHI",
"Australia/NSW",
"Australia/Tasmania",
"Australia/Broken_Hill",
"Australia/Hobart",
"Australia/North",
"Australia/Sydney",
"Pacific/Chuuk",
"Pacific/Fiji",
"Pacific/Guam",
"Pacific/Kwajalein",
"Pacific/Niue",
"Pacific/Pitcairn",
"Pacific/Saipan",
"Pacific/Truk",
"Pacific/Chatham",
"Pacific/Fakaofo",
"Pacific/Guadalcanal",
"Pacific/Kosrae",
"Pacific/Nauru",
"Pacific/Palau",
"Pacific/Rarotonga",
"Pacific/Tongatapu",
"Pacific/Easter",
"Pacific/Funafuti",
"Pacific/Honolulu",
"Pacific/Majuro",
"Pacific/Norfolk",
"Pacific/Pohnpei",
"Pacific/Samoa",
"Pacific/Wake",
"Antarctica/Casey",
"Antarctica/McMurdo",
"Antarctica/Vostok",
"Antarctica/Davis",
"Antarctica/Palmer",
"Antarctica/DumontDUrville",
"Antarctica/Rothera",
"Antarctica/Macquarie",
"Antarctica/South_Pole",
"Antarctica/Mawson",
"Antarctica/Syowa",
"Arctic/Longyearbyen",
"Europe/Athens",
"Europe/Brussels",
"Europe/Dublin",
"Europe/Istanbul",
"Europe/Ljubljana",
"Europe/Mariehamn",
"Europe/Oslo",
"Europe/Rome",
"Europe/Skopje",
"Europe/Tiraspol",
"Europe/Vilnius",
"Europe/Zurich",
"Europe/Belfast",
"Europe/Bucharest",
"Europe/Gibraltar",
"Europe/Jersey",
"Europe/London",
"Europe/Minsk",
"Europe/Paris",
"Europe/Samara",
"Europe/Sofia",
"Europe/Uzhgorod",
"Europe/Volgograd",
"Europe/Belgrade",
"Europe/Budapest",
"Europe/Guernsey",
"Europe/Kaliningrad",
"Europe/Luxembourg",
"Europe/Monaco",
"Europe/Podgorica",
"Europe/San_Marino",
"Europe/Stockholm",
"Europe/Vaduz",
"Europe/Warsaw",
"Indian/Cocos",
"Indian/Mauritius",
"Indian/Christmas",
"Indian/Maldives",
"Indian/Comoro",
"Indian/Mayotte",
"Australia/Brisbane",
"Australia/Eucla",
"Australia/Melbourne",
"Australia/South",
"Australia/Yancowinna",
);
Timezones in PHP at http://www.php.net/manual/en/timezones.php
It's because there is no long
in javascript.
You can use "tilde" operator to do it:
import cv2
image = cv2.imread("img.png")
image = ~image
cv2.imwrite("img_inv.png",image)
This is because the "tilde" operator (also known as unary operator) works doing a complement dependent on the type of object
for example for integers, its formula is:
x + (~x) = -1
but in this case, opencv use an "uint8 numpy array object" for its images so its range is from 0 to 255
so if we apply this operator to an "uint8 numpy array object" like this:
import numpy as np
x1 = np.array([25,255,10], np.uint8) #for example
x2 = ~x1
print (x2)
we will have as a result:
[230 0 245]
because its formula is:
x2 = 255 - x1
and that is exactly what we want to do to solve the problem.
Gestures are those subtle motions to trigger interactions between the touch screen and the user. It lasts for the time between the first touch on the screen to the point when the last finger leaves the surface.
Android provides us with a class called GestureDetector using which we can detect common gestures like tapping down and up, swiping vertically and horizontally (fling), long and short press, double taps, etc. and attach listeners to them.
Make our Activity class implement GestureDetector.OnDoubleTapListener (for double tap gesture detection) and GestureDetector.OnGestureListener interfaces and implement all the abstract methods.For more info. you may visit https://developer.android.com/training/gestures/detector.html . Courtesy
For Demo Test.GestureDetectorDemo