Try following these steps:
Using only "native" Windows utilities, try the following, where "516" is the process ID that you want the image name for:
for /f "delims=," %a in ( 'tasklist /fi "PID eq 516" /nh /fo:csv' ) do ( echo %~a )
for /f %a in ( 'tasklist /fi "PID eq 516" ^| findstr "516"' ) do ( echo %a )
Or you could use wmic (the Windows Management Instrumentation Command-line tool) and get the full path to the executable:
wmic process where processId=516 get name
wmic process where processId=516 get ExecutablePath
Or you could download Microsoft PsTools, or specifically download just the pslist utility, and use PsList:
for /f %a in ( 'pslist 516 ^| findstr "516"' ) do ( echo %a )
if ([statusString isEqualToString:@"Wrong"]) {
// do something
}
Move your code inside of the src
folder. Once it's there, it'll be compiled on-the-fly every time it's saved.
IntelliJ only recognizes files in specific locations as part of the project - namely, anything inside of a blue folder is specifically considered to be source code.
Also - while I can't see all of your source code - be sure that it's proper Java syntax, with a class declared the same as the file and that it has a main
method (specifically public static void main(String[] args)
). IntelliJ won't run code without a main
method (rather, it can't - neither it nor Java would know where to start).
Used a modified version of Jason's answer:
public string ProcessMyDataItem(object myValue)
{
if (myValue.ToString().Length < 1)
{
return "0 value";
}
return myValue.ToString();
}
Here is an example on how to center an object vertically with jQuery:
var div= $('#div_SomeDivYouWantToAdjust');
div.css("top", ($(window).height() - div.height())/2 + 'px');
But you could easily change that to whatever your needs are.
Simplest solution: The Oracle client is not installed on the remote server where the SSIS package is being executed.
Slightly less simple solution: The Oracle client is installed on the remote server, but in the wrong bit-count for the SSIS installation. For example, if the 64-bit Oracle client is installed but SSIS is being executed with the 32-bit dtexec
executable, SSIS will not be able to find the Oracle client.
The solution in this case would be to install the 32-bit Oracle client side-by-side with the 64-bit client.
I've recently found that blanks in the name of the redirect file will cause the "ambiguous redirect" message.
For example if you redirect to application$(date +%Y%m%d%k%M%S).log
and you specify the wrong formatting characters, the redirect will fail before 10 AM for example. If however, you used application$(date +%Y%m%d%H%M%S).log
it would succeed. This is because the %k
format yields ' 9'
for 9AM where %H
yields '09'
for 9AM.
echo $(date +%Y%m%d%k%M%S)
gives 20140626 95138
echo $(date +%Y%m%d%H%M%S)
gives 20140626095138
The erroneous date might give something like:
echo "a" > myapp20140626 95138.log
where the following is what would be desired:
echo "a" > myapp20140626095138.log
It looks like Microsoft has deprecated lots of calls which use buffers to improve code security. However, the solutions they're providing aren't portable. Anyway, if you aren't interested in using the secure version of their calls (like fopen_s), you need to place a definition of _CRT_SECURE_NO_DEPRECATE before your included header files. For example:
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
The preprocessor directive can also be added to your project settings to effect it on all the files under the project. To do this add _CRT_SECURE_NO_DEPRECATE to Project Properties -> Configuration Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions.
The first <img />
is invalid - src
is a required attribute. data-src
is an attribute than can be leveraged by, say, JavaScript, but has no presentational meaning.
First of all, this what is written in documentation. I think it is one of your class fields, not the main one - and how you want deserialiser to construct it back w/o parameterless construction ?
I think there is a workaround to make constructor private.
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.
Simple way on macOS e.g. installed via homebrew
$ ls -l $(which kafka-topics)
/usr/local/bin/kafka-topics -> ../Cellar/kafka/0.11.0.1/bin/kafka-topics
I know this is really old but I think the solutions looked too complicated. Try this in VB:
Public Function HexToInt(sHEX as String) as long
Dim iLen as Integer
Dim i as Integer
Dim SumValue as Long
Dim iVal as long
Dim AscVal as long
iLen = Len(sHEX)
For i = 1 to Len(sHEX)
AscVal = Asc(UCase(Mid$(sHEX, i, 1)))
If AscVal >= 48 And AscVal <= 57 Then
iVal = AscVal - 48
ElseIf AscVal >= 65 And AscVal <= 70 Then
iVal = AscVal - 55
End If
SumValue = SumValue + iVal * 16 ^ (iLen- i)
Next i
HexToInt = SumValue
End Function
You need to move the pointer to the first row, before asking for data:
result.beforeFirst();
result.next();
String foundType = result.getString(1);
In Visual Studio Express 2013 for web it's hidden away in View > Other Windows > Toolbox.
You could try this below.
string url = "http://localhost:1302/TESTERS/Default6.aspx";
string fileName = System.IO.Path.GetFileName(url);
Hope this helps.
You can do this with simple paths (w/0) querystrings etc.
Granted probably overly complex and probably not performant, but I wanted to use reduce
for the fun of it.
"/foo/bar/"
.split(path.sep)
.filter(x => x !== "")
.reduce((_, part, i, arr) => {
if (i == arr.length - 1) return part;
}, "");
Follow these steps:
steps updated as on 13th July 2020 Thank You: Rahul Daksh
As the previous answers saids, try to move the state to a top component and modify the state through callbacks passed to it's children.
In case that you really need to access to a child state that is declared as a functional component (hooks) you can declare a ref in the parent component, then pass it as a ref attribute to the child but you need to use React.forwardRef and then the hook useImperativeHandle to declare a function you can call in the parent component.
Take a look at the following example:
const Parent = () => {
const myRef = useRef();
return <Child ref={myRef} />;
}
const Child = React.forwardRef((props, ref) => {
const [myState, setMyState] = useState('This is my state!');
useImperativeHandle(ref, () => ({getMyState: () => {return myState}}), [myState]);
})
Then you should be able to get myState in the Parent component by calling:
myRef.current.getMyState();
Inside of VBS you can access parameters with
Wscript.Arguments(0)
Wscript.Arguments(1)
and so on. The number of parameter:
Wscript.Arguments.Count
Your annotations look fine. Here are the things to check:
make sure the annotation is javax.persistence.Entity
, and not org.hibernate.annotations.Entity
. The former makes the entity detectable. The latter is just an addition.
if you are manually listing your entities (in persistence.xml, in hibernate.cfg.xml, or when configuring your session factory), then make sure you have also listed the ScopeTopic
entity
make sure you don't have multiple ScopeTopic
classes in different packages, and you've imported the wrong one.
Here is an easier way :
import numpy as np
twoD = np.array([[]*m]*n)
For initializing all cells with any 'x' value use :
twoD = np.array([[x]*m]*n
Based on my Comment here is one way to get what you want done:
Start byt selecting any cell in your range and Press Ctrl + T
This will give you this pop up:
make sure the Where is your table text is correct and click ok you will now have:
Now If you add a column header in D it will automatically be added to the table all the way to the last row:
Now If you enter a formula into this column:
After you enter it, the formula will be auto filled all the way to last row:
Now if you add a new row at the next row under your table:
Once entered it will be resized to the width of your table and all columns with formulas will be added also:
Hope this solves your problem!
I had to split a list for feature extraction in two parts lt,lc:
ltexts = ((df4.ix[0:,[3,7]]).values).tolist()
random.shuffle(ltexts)
featsets = [(act_features((lt)),lc)
for lc, lt in ltexts]
def act_features(atext):
features = {}
for word in nltk.word_tokenize(atext):
features['cont({})'.format(word.lower())]=True
return features
I received the same error after a reinstall of the OS on my developer mac and upgrading to xcode 7.3.
First, since length
always returns a non-negative number,
if ( length $name )
and
if ( length $name > 0 )
are equivalent.
If you are OK with replacing an undefined value with an empty string, you can use Perl 5.10's //=
operator which assigns the RHS to the LHS unless the LHS is defined:
#!/usr/bin/perl
use feature qw( say );
use strict; use warnings;
my $name;
say 'nonempty' if length($name //= '');
say "'$name'";
Note the absence of warnings about an uninitialized variable as $name
is assigned the empty string if it is undefined.
However, if you do not want to depend on 5.10 being installed, use the functions provided by Scalar::MoreUtils. For example, the above can be written as:
#!/usr/bin/perl
use strict; use warnings;
use Scalar::MoreUtils qw( define );
my $name;
print "nonempty\n" if length($name = define $name);
print "'$name'\n";
If you don't want to clobber $name
, use default
.
Will this be simpler for handling the day boundary case? :)
TimeSpan start = TimeSpan.Parse("22:00"); // 10 PM
TimeSpan end = TimeSpan.Parse("02:00"); // 2 AM
TimeSpan now = DateTime.Now.TimeOfDay;
bool bMatched = now.TimeOfDay >= start.TimeOfDay &&
now.TimeOfDay < end.TimeOfDay;
// Handle the boundary case of switching the day across mid-night
if (end < start)
bMatched = !bMatched;
if(bMatched)
{
// match found, current time is between start and end
}
else
{
// otherwise ...
}
Old Answer (July 2016):
You can't directly debug Chrome for iOS due to restrictions on the published WKWebView
apps, but there are a few options already discussed in other SO threads:
If you can reproduce the issue in Safari as well, then use Remote Debugging with Safari Web Inspector. This would be the easiest approach.
WeInRe allows some simple debugging, using a simple client-server model. It's not fully featured, but it may well be enough for your problem. See instructions on set up here.
You could try and create a simple WKWebView
browser app (some instructions here), or look for an existing one on GitHub. Since Chrome uses the same rendering engine, you could debug using that, as it will be close to what Chrome produces.
There's a "bug" opened up for WebKit: Allow Web Inspector usage for release builds of WKWebView. If and when we get an API to WKWebView
, Chrome for iOS would be debuggable.
Update January 2018:
Since my answer back in 2016, some work has been done to improve things.
There is a recent project called RemoteDebug iOS WebKit Adapter, by some of the Microsoft team. It's an adapter that handles the API differences between Webkit Remote Debugging Protocol and Chrome Debugging Protocol, and this allows you to debug iOS WebViews in any app that supports the protocol - Chrome DevTools, VS Code etc.
Check out the getting started guide in the repo, which is quite detailed.
If you are interesting, you can read up on the background and architecture here.
Spring uses dependency injection to populate the specific value when it finds the @Value annotation. However, instead of handing the value to the instance variable, it's handed to the implicit setter instead. This setter then handles the population of our NAME_STATIC value.
@RestController
//or if you want to declare some specific use of the properties file then use
//@Configuration
//@PropertySource({"classpath:application-${youeEnvironment}.properties"})
public class PropertyController {
@Value("${name}")//not necessary
private String name;//not necessary
private static String NAME_STATIC;
@Value("${name}")
public void setNameStatic(String name){
PropertyController.NAME_STATIC = name;
}
}
diff
can not only compare two files, it can, by using the -r
option, walk entire directory trees, recursively checking differences between subdirectories and files that occur at comparable points in each tree.
$ man diff
...
-r --recursive
Recursively compare any subdirectories found.
...
I think you have to write each object to an own File or you have to split the one when reading it. You may also try to serialize your list and retrieve that when deserializing.
There is a Hidden
helper alongside HiddenFor
which lets you set the value.
@Html.Hidden("RequiredProperty", "default")
EDIT Based on the edit you've made to the question, you could do this, but I believe you're moving into territory where it will be cheaper and more effective, in the long run, to fight for making the code change. As has been said, even by yourself, the controller or view model should be setting the default.
This code:
<ul>
@{
var stacks = new System.Diagnostics.StackTrace().GetFrames();
foreach (var frame in stacks)
{
<li>@frame.GetMethod().Name - @frame.GetMethod().DeclaringType</li>
}
}
</ul>
Will give output like this:
Execute - ASP._Page_Views_ViewDirectoryX__SubView_cshtml
ExecutePageHierarchy - System.Web.WebPages.WebPageBase
ExecutePageHierarchy - System.Web.Mvc.WebViewPage
ExecutePageHierarchy - System.Web.WebPages.WebPageBase
RenderView - System.Web.Mvc.RazorView
Render - System.Web.Mvc.BuildManagerCompiledView
RenderPartialInternal - System.Web.Mvc.HtmlHelper
RenderPartial - System.Web.Mvc.Html.RenderPartialExtensions
Execute - ASP._Page_Views_ViewDirectoryY__MainView_cshtml
So assuming the MVC framework will always go through the same stack, you can grab var frame = stacks[8];
and use the declaring type to determine who your parent view is, and then use that determination to set (or not) the default value. You could also walk the stack instead of directly grabbing [8]
which would be safer but even less efficient.
you can use sync storage that is easier to use than async storage. this library is great that uses async storage to save data asynchronously and uses memory to load and save data instantly synchronously, so we save data async to memory and use in app sync, so this is great.
import SyncStorage from 'sync-storage';
SyncStorage.set('foo', 'bar');
const result = SyncStorage.get('foo');
console.log(result); // 'bar'
If you don't want to make service then you can do like this.
var scope = angular.element("#another ctrl scope element id.").scope();
scope.plean_assign = some_value;
The fastest way to do file I/O from C# is to use the Windows ReadFile and WriteFile functions. I have written a C# class that encapsulates this capability as well as a benchmarking program that looks at differnet I/O methods, including BinaryReader and BinaryWriter. See my blog post at:
http://designingefficientsoftware.wordpress.com/2011/03/03/efficient-file-io-from-csharp/
I have had a similar problem, turns out we don't need hooks to do these, we can make an conditional render and it will still work fine.
<Button
type="submit"
disabled={
name === "" || email === "" || password === "" ? true : false
}
fullWidth
variant="contained"
color="primary"
className={classes.submit}>
SignUP
</Button>
Use:
import color
class Color(color.Color):
...
If this were Python 2.x, you would also want to derive color.Color
from object
, to make it a new-style class:
class Color(object):
...
This is not necessary in Python 3.x.
Use -d
(full list of file tests)
if (-d "cgi-bin") {
# directory called cgi-bin exists
}
elsif (-e "cgi-bin") {
# cgi-bin exists but is not a directory
}
else {
# nothing called cgi-bin exists
}
As a note, -e
doesn't distinguish between files and directories. To check if something exists and is a plain file, use -f
.
Django Mail Templated is a feature-rich Django application to send emails with Django template system.
Installation:
pip install django-mail-templated
Configuration:
INSTALLED_APPS = (
...
'mail_templated'
)
Template:
{% block subject %}
Hello {{ user.name }}
{% endblock %}
{% block body %}
{{ user.name }}, this is the plain text part.
{% endblock %}
Python:
from mail_templated import send_mail
send_mail('email/hello.tpl', {'user': user}, from_email, [user.email])
More info: https://github.com/artemrizhov/django-mail-templated
You override __hash__
if you want special hash-semantics, and __cmp__
or __eq__
in order to make your class usable as a key. Objects who compare equal need to have the same hash value.
Python expects __hash__
to return an integer, returning Banana()
is not recommended :)
User defined classes have __hash__
by default that calls id(self)
, as you noted.
There is some extra tips from the documentation.:
Classes which inherit a
__hash__()
method from a parent class but change the meaning of__cmp__()
or__eq__()
such that the hash value returned is no longer appropriate (e.g. by switching to a value-based concept of equality instead of the default identity based equality) can explicitly flag themselves as being unhashable by setting__hash__ = None
in the class definition. Doing so means that not only will instances of the class raise an appropriate TypeError when a program attempts to retrieve their hash value, but they will also be correctly identified as unhashable when checkingisinstance(obj, collections.Hashable)
(unlike classes which define their own__hash__()
to explicitly raise TypeError).
#alertlist li:hover:after,#alertlist li.selected:after
{
position:absolute;
top: 0;
right:-10px;
bottom:0;
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
border-left: 10px solid #303030;
content: "";
}?
git rev-parse
is an ancillary plumbing
command primarily used for manipulation.
One common usage of git rev-parse
is to print the SHA1 hashes given a revision specifier. In addition, it has various options to format this output such as --short
for printing a shorter unique SHA1.
There are other use cases as well (in scripts and other tools built on top of git) that I've used for:
--verify
to verify that the specified object is a valid git object.--git-dir
for displaying the abs/relative path of the the .git
directory.--is-inside-git-dir
or within a work-tree using --is-inside-work-tree
--is-bare-repository
--branches
), tags (--tags
) and the refs can also be filtered based on the remote (using --remote
)--parse-opt
to normalize arguments in a script (kind of similar to getopt
) and print an output string that can be used with eval
Massage
just implies that it is possible to convert the info from one form into another i.e. a transformation command. These are some quick examples I can think of:
A..B
for git log
or git diff
into the equivalent arguments for the underlying plumbing command as B ^A
It's been more than 10 years and not sure if anyone still finding this question or answer relevant.
But a quick workaround is just to wrap the asp control
within a html container
<div id="myElement" style="display: inline-block">
<asp:TextBox ID="textBox1" runat="server"></asp:TextBox>
</div>
Whenever the Javascript Event
is triggered, if it needs to be an event by the asp control
, just wrap the asp control
around the div
container.
<div id="testG">
<asp:Button ID="Button2" runat="server" CssClass="btn" Text="Activate" />
</div>
The jQuery Code is below:
$(document).ready(function () {
$("#testG").click(function () {
$("#myElement").css("display", "none");
});
});
I had a directory of files that I wanted to check. I created an Excel macro to determine ANSI vs. UTF-8. This worked for me.
Sub GetTextFileEncoding()
Dim sFile As String
Dim sPath As String
Dim sTextLine As String
Dim iRow As Integer
'Set Defaults and Initial Values
iRow = 1
sPath = "C:textfiles\"
sFile = Dir(sPath & "*.txt")
Do While Len(sFile) > 0
'Get FileType
'Debug.Print sFile & " - " & FileEncodeType(sPath & sFile)
'Show on Excel Worksheet
Cells(iRow, 1).Value = sFile
Cells(iRow, 2).Value = FileEncodeType(sPath & sFile)
'Get next file
sFile = Dir
'Increment Row
iRow = iRow + 1
Loop
End Sub
Function FileEncodeType(sFile As String) As String
Dim bEF As Boolean
Dim bBB As Boolean
Dim bBF As Boolean
bEF = False
bBB = False
bBF = False
Open sFile For Input As #1
If Not EOF(1) Then
'Read first line
Line Input #1, textline
'Debug.Print textline
For i = 1 To 3
'Debug.Print Asc(Mid(textline, i, 1)) & " - " & Mid(textline, i, 1)
Select Case i
Case 1
If Asc(Mid(textline, i, 1)) = 239 Then
bEF = True
End If
Case 2
If Asc(Mid(textline, i, 1)) = 187 Then
bBB = True
End If
Case 3
If Asc(Mid(textline, i, 1)) = 191 Then
bBF = True
End If
Case 4
End Select
Next
End If
Close #1
If bEF And bBB And bBF Then
FileEncodeType = "UTF-8"
Else
FileEncodeType = "ANSI"
End If
End Function
RedirectMatch
uses a regular expression that is matched against the URL path. And your regular expression /contact.php
just means any URL path that contains /contact.php
but not just any URL path that is exactly /contact.php
. So use the anchors for the start and end of the string (^
and $)
:
RedirectMatch 301 ^/contact\.php$ /contact-us.php
What I saw above is complicate.....
Here is some code can refer to.
$("#box").on({
mousedown:function(e)
{
dragging = true;
dragX = e.clientX - $(this).position().left;
//To calculate the distance between the cursor pointer and box
dragY = e.clientY - $(this).position().top;
},
mouseup:function(){dragging = false;},
//If not set this on/off,the move will continue forever
mousemove:function(e)
{
if(dragging)
$(this).offset({top:e.clientY-dragY,left:e.clientX-dragX});
}
})
dragging,dragX,dragY may place as the global variable.
It's a simple show about this issue,but there is some bug about this method.
If it's your need now,here's the Example here.
Public Function _
CreateTextArrayFromSourceTexts(ParamArray SourceTexts() As Variant) As String()
ReDim TargetTextArray(0 To UBound(SourceTexts)) As String
For SourceTextsCellNumber = 0 To UBound(SourceTexts)
TargetTextArray(SourceTextsCellNumber) = SourceTexts(SourceTextsCellNumber)
Next SourceTextsCellNumber
CreateTextArrayFromSourceTexts = TargetTextArray
End Function
Example:
Dim TT() As String
TT = CreateTextArrayFromSourceTexts("hi", "bye", "hi", "bcd", "bYe")
Result:
TT(0)="hi"
TT(1)="bye"
TT(2)="hi"
TT(3)="bcd"
TT(4)="bYe"
Enjoy!
Edit: I removed the duplicatedtexts deleting feature and made the code smaller and easier to use.
I guess you are using an old version of hibernate. You can download the latest version, 5.2, from here.
I was getting the same error, and found out the problem was that during the publish to Azure, my web.config file was modified so this following line ended up like this:
<aspNetCore processPath="bin\IISSupport\VSIISExeLauncher.exe" arguments="-argFile IISExeLauncherArgs.txt" forwardWindowsAuthToken="false" stdoutLogEnabled="false" startupTimeLimit="3600" requestTimeout="23:00:00" />
The problem for Production are the contents of the arguments: "-argFile IISExeLauncherArgs.txt"
It seems like this issue is going to be addressed in the next .NET Core SDK (currently in preview), but for now, the workaround is to add this block to the .csproj file:
<Target Name="bug_242_workaround" AfterTargets="_TransformWebConfig">
<Exec Command="powershell "(Get-Content '$(PublishDir)Web.config').replace(' -argFile IISExeLauncherArgs.txt', '') | Set-Content '$(PublishDir)Web.config'"" />
</Target>
This will modify the web.config and remove the problematic part for publishing.
Reference: https://github.com/aspnet/websdk/issues/242
Hope it helps.
A couple of issues
>
in -exec
without something like bash -c '... > ...'
. Though the >
will overwrite the file, so you want to redirect the entire find
anyway rather than each -exec
. +30
is older
than 30 days, -30
would be modified in last 30 days.-exec
really isn't needed, you could list everything with various -printf
options. Something like below should work
find . -type f -mtime -30 -exec ls -l {} \; > last30days.txt
Example with -printf
find . -type f -mtime -30 -printf "%M %u %g %TR %TD %p\n" > last30days.txt
This will list files in format "permissions owner group time date filename". -printf
is generally preferable to -exec
in cases where you don't have to do anything complicated. This is because it will run faster as a result of not having to execute subshells for each -exec
. Depending on the version of find
, you may also be able to use -ls
, which has a similar format to above.
iostream doesn't know it's at the end of the file until it tries to read that first character past the end of the file.
The sample code at cplusplus.com says to do it like this: (But you shouldn't actually do it this way)
while (is.good()) // loop while extraction from file is possible
{
c = is.get(); // get character from file
if (is.good())
cout << c;
}
A better idiom is to move the read into the loop condition, like so:
(You can do this with all istream
read operations that return *this
, including the >>
operator)
char c;
while(is.get(c))
cout << c;
The DoEvents does allow the user to click around or type and trigger other events, and background threads are a better approach.
However, there are still cases where you may run into issues that require flushing event messages. I ran into a problem where the RichTextBox control was ignoring the ScrollToCaret() method when the control had messages in queue to process.
The following code blocks all user input while executing DoEvents:
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace Integrative.Desktop.Common
{
static class NativeMethods
{
#region Block input
[DllImport("user32.dll", EntryPoint = "BlockInput")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool BlockInput([MarshalAs(UnmanagedType.Bool)] bool fBlockIt);
public static void HoldUser()
{
BlockInput(true);
}
public static void ReleaseUser()
{
BlockInput(false);
}
public static void DoEventsBlockingInput()
{
HoldUser();
Application.DoEvents();
ReleaseUser();
}
#endregion
}
}
There are several ways to do it. The subplots
method creates the figure along with the subplots that are then stored in the ax
array. For example:
import matplotlib.pyplot as plt
x = range(10)
y = range(10)
fig, ax = plt.subplots(nrows=2, ncols=2)
for row in ax:
for col in row:
col.plot(x, y)
plt.show()
However, something like this will also work, it's not so "clean" though since you are creating a figure with subplots and then add on top of them:
fig = plt.figure()
plt.subplot(2, 2, 1)
plt.plot(x, y)
plt.subplot(2, 2, 2)
plt.plot(x, y)
plt.subplot(2, 2, 3)
plt.plot(x, y)
plt.subplot(2, 2, 4)
plt.plot(x, y)
plt.show()
This worked for me:
SELECT *
FROM your_table
WHERE id IN (
SELECT MAX(id)
FROM your_table
GROUP BY name
);
for(var a=1;a<8;a++){
var o="";
for(var b=1;b<=a;b++){
o +="#";
}
debug(o);
}
Try above code.
Output:
--> #
--> ##
--> ###
--> ####
--> #####
--> ######
In my case 'await' never finished because of exception while executing the request, e.g. server not responding, etc. Surround it with try..catch to identify what happened, it'll also complete your 'await' gracefully.
public async Task<Stuff> GetStuff(string id)
{
string path = $"/api/v2/stuff/{id}";
try
{
HttpResponseMessage response = await client.GetAsync(path);
if (response.StatusCode == HttpStatusCode.OK)
{
string json = await response.Content.ReadAsStringAsync();
return JsonUtility.FromJson<Stuff>(json);
}
else
{
Debug.LogError($"Could not retrieve stuff {id}");
}
}
catch (Exception exception)
{
Debug.LogError($"Exception when retrieving stuff {exception}");
}
return null;
}
As stated in the other answer, width: auto doesn't work due to the width being generated by the input's size attribute, which cannot be set to "auto" or anything similar.
There are a few workarounds you can use to cause it to play nicely with the box model, but nothing fantastic as far as I know.
First you can set the padding in the field using percentages, making sure that the width adds up to 100%, e.g.:
input {
width: 98%;
padding: 1%;
}
Another thing you might try is using absolute positioning, with left and right set to 0. Using this markup:
<fieldset>
<input type="text" />
</fieldset>
And this CSS:
fieldset {
position: relative;
}
input {
position: absolute;
left: 0;
right: 0;
}
This absolute positioning will cause the input to fill the parent fieldset horizontally, regardless of the input's padding or margin. However a huge downside of this is that you now have to deal with the height of the fieldset, which will be 0 unless you set it. If your inputs are all the same height this will work for you, simply set the fieldset's height to whatever the input's height should be.
Other than this there are some JS solutions, but I don't like applying basic styling with JS.
You can use this :
$this->db->select('*');
$this->db->from('mytable');
$this->db->where(name,'Joe');
$bind = array('boss', 'active');
$this->db->where_in('status', $bind);
Quick and dirty, and store it in a variable:
USER=somebody
USER_HOME="$(echo -n $(bash -c "cd ~${USER} && pwd"))"
You mistyped the set
command – you missed the backslash after C:
. It should be:
C:\>set path=C:\Program Files (x86)\Java\jdk1.7.0\bin
Combining various answers :
In MySQL 5.5, DEFAULT CURRENT_TIMESTAMP
and ON UPDATE CURRENT_TIMESTAMP
cannot be added on DATETIME
but only on TIMESTAMP
.
Rules:
1) at most one TIMESTAMP
column per table could be automatically (or manually[My addition]) initialized or updated to the current date and time. (MySQL Docs).
So only one TIMESTAMP
can have CURRENT_TIMESTAMP
in DEFAULT
or ON UPDATE
clause
2) The first NOT NULL
TIMESTAMP
column without an explicit DEFAULT
value like created_date timestamp default '0000-00-00 00:00:00'
will be implicitly given a DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
and hence subsequent TIMESTAMP
columns cannot be given CURRENT_TIMESTAMP
on DEFAULT
or ON UPDATE
clause
CREATE TABLE `address` (
`id` int(9) NOT NULL AUTO_INCREMENT,
`village` int(11) DEFAULT NULL,
`created_date` timestamp default '0000-00-00 00:00:00',
-- Since explicit DEFAULT value that is not CURRENT_TIMESTAMP is assigned for a NOT NULL column,
-- implicit DEFAULT CURRENT_TIMESTAMP is avoided.
-- So it allows us to set ON UPDATE CURRENT_TIMESTAMP on 'updated_date' column.
-- How does setting DEFAULT to '0000-00-00 00:00:00' instead of CURRENT_TIMESTAMP help?
-- It is just a temporary value.
-- On INSERT of explicit NULL into the column inserts current timestamp.
-- `created_date` timestamp not null default '0000-00-00 00:00:00', // same as above
-- `created_date` timestamp null default '0000-00-00 00:00:00',
-- inserting 'null' explicitly in INSERT statement inserts null (Ignoring the column inserts the default value)!
-- Remember we need current timestamp on insert of 'null'. So this won't work.
-- `created_date` timestamp null , // always inserts null. Equally useless as above.
-- `created_date` timestamp default 0, // alternative to '0000-00-00 00:00:00'
-- `created_date` timestamp,
-- first 'not null' timestamp column without 'default' value.
-- So implicitly adds DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP.
-- Hence cannot add 'ON UPDATE CURRENT_TIMESTAMP' on 'updated_date' column.
`updated_date` timestamp null on update current_timestamp,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=132 DEFAULT CHARSET=utf8;
INSERT INTO address (village,created_date) VALUES (100,null);
mysql> select * from address;
+-----+---------+---------------------+--------------+
| id | village | created_date | updated_date |
+-----+---------+---------------------+--------------+
| 132 | 100 | 2017-02-18 04:04:00 | NULL |
+-----+---------+---------------------+--------------+
1 row in set (0.00 sec)
UPDATE address SET village=101 WHERE village=100;
mysql> select * from address;
+-----+---------+---------------------+---------------------+
| id | village | created_date | updated_date |
+-----+---------+---------------------+---------------------+
| 132 | 101 | 2017-02-18 04:04:00 | 2017-02-18 04:06:14 |
+-----+---------+---------------------+---------------------+
1 row in set (0.00 sec)
Other option (But updated_date
is the first column):
CREATE TABLE `address` (
`id` int(9) NOT NULL AUTO_INCREMENT,
`village` int(11) DEFAULT NULL,
`updated_date` timestamp null on update current_timestamp,
`created_date` timestamp not null ,
-- implicit default is '0000-00-00 00:00:00' from 2nd timestamp onwards
-- `created_date` timestamp not null default '0000-00-00 00:00:00'
-- `created_date` timestamp
-- `created_date` timestamp default '0000-00-00 00:00:00'
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=132 DEFAULT CHARSET=utf8;
#similar {
float:left;
width:200px;
background:#000;
clear:both;
}
A different approach, because in my case I needed to also check whether it contained certain words (like 'test' in this example), not characters alone:
input_string = 'abc test'
input_string_test = input_string
allowed_list = ['a', 'b', 'c', 'test', ' ']
for allowed_list_item in allowed_list:
input_string_test = input_string_test.replace(allowed_list_item, '')
if not input_string_test:
# test passed
So, the allowed strings (char or word) are cut from the input string. If the input string only contained strings that were allowed, it should leave an empty string and therefore should pass if not input_string
.
How can you tell string
is a reference type? I'm not sure that it matters how it is implemented. Strings in C# are immutable precisely so that you don't have to worry about this issue.
I would like to add my comments. When you choose a ready engine, such as jBPM, Activity and others (there are plenty of them), then you have to spend some time learning the system itself, this may not be an easy task. Especially, when you need only to automate small piece of code.
Then, when an issue occurs you have to deal with the vendor's support, which is not as speedy as you would imagine. Even pay for some consultancy.
And, last, a most important reason, you have to develop in the ecosystem of the engine. Although, the vendors tend to say that their system are flexible to be incorporated into any systems, this may not be case. Eventually you end up re-writing your application to match with the BPM ecosystem.
both your conditions are the same:
if(s < f) { calc = f - s; n = s; }else if(f > s){ calc = s - f; n = f; }
so
if(s < f)
and
}else if(f > s){
are the same
change to
}else if(f < s){
Annotations are a form of metadata (data about data) added to a Java source file. They are largely used by frameworks to simplify the integration of client code. A couple of real world examples off the top of my head:
JUnit 4 - you add the @Test
annotation to each test method you want the JUnit runner to run. There are also additional annotations to do with setting up testing (like @Before
and @BeforeClass
). All these are processed by the JUnit runner, which runs the tests accordingly. You could say it's an replacement for XML configuration, but annotations are sometimes more powerful (they can use reflection, for example) and also they are closer to the code they are referencing to (the @Test
annotation is right before the test method, so the purpose of that method is clear - serves as documentation as well). XML configuration on the other hand can be more complex and can include much more data than annotations can.
Terracotta - uses both annotations and XML configuration files. For example, the @Root
annotation tells the Terracotta runtime that the annotated field is a root and its memory should be shared between VM instances. The XML configuration file is used to configure the server and tell it which classes to instrument.
Google Guice - an example would be the @Inject
annotation, which when applied to a constructor makes the Guice runtime look for values for each parameter, based on the defined injectors. The @Inject
annotation would be quite hard to replicate using XML configuration files, and its proximity to the constructor it references to is quite useful (imagine having to search to a huge XML file to find all the dependency injections you have set up).
Hopefully I've given you a flavour of how annotations are used in different frameworks.
I guess to get full browser comparability disabled
should set by the value disabled
or get removed!
Here is a small plugin that I've just made:
(function($) {
$.fn.toggleDisabled = function() {
return this.each(function() {
var $this = $(this);
if ($this.attr('disabled')) $this.removeAttr('disabled');
else $this.attr('disabled', 'disabled');
});
};
})(jQuery);
EDIT: updated the example link/code to maintaining chainability!
EDIT 2:
Based on @lonesomeday comment, here's an enhanced version:
(function($) {
$.fn.toggleDisabled = function(){
return this.each(function(){
this.disabled = !this.disabled;
});
};
})(jQuery);
Try this statement:
exit 1
Replace 1
with appropriate error codes. See also Exit Codes With Special Meanings.
Barring the CSS solution. The fastest possible way is to hide it immediatly with a script.
<div id="hideme"></div>
<script type="text/javascript">
$("#hideme").hide();
</script>
In this case I would recommend the CSS solution by Vega. But if you need something more complex (like an animation) you can use this approach.
This has some complications (see comments below). If you want this piece of script to really run as fast as possible you can't use jQuery, use native JS only and defer loading of all other scripts.
Have a look at using DATEADD
something like
SELECT DATEADD(minute, -30, GETDATE())
This part of code worked fine for me:
WebRequest request = WebRequest.Create(url);
request.Method = WebRequestMethods.Http.Get;
NetworkCredential networkCredential = new NetworkCredential(logon, password); // logon in format "domain\username"
CredentialCache myCredentialCache = new CredentialCache {{new Uri(url), "Basic", networkCredential}};
request.PreAuthenticate = true;
request.Credentials = myCredentialCache;
using (WebResponse response = request.GetResponse())
{
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
using (Stream dataStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(dataStream))
{
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
}
}
}
Add this class to your project
import android.content.Context;
import android.provider.Settings;
import android.text.TextUtils;
import com.google.android.gms.ads.AdRequest;
import java.io.UnsupportedEncodingException;
public class AdsHelper {
public static AdRequest createRequest(Context context) {
AdRequest.Builder adRequest = new AdRequest.Builder();
adRequest.addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
if (BuildConfig.DEBUG) {
String deviceId = MD5(getDeviceId(context));
if (!TextUtils.isEmpty(deviceId)) {
adRequest.addTestDevice(deviceId.toUpperCase());
}
}
return adRequest.build();
}
private static String MD5(String md5) {
if (TextUtils.isEmpty(md5)) return null;
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
byte[] array = md.digest(md5.getBytes("UTF-8"));
StringBuilder sb = new StringBuilder();
for (byte anArray : array) {
sb.append(Integer.toHexString((anArray & 0xFF) | 0x100).substring(1, 3));
}
return sb.toString();
} catch (java.security.NoSuchAlgorithmException ignored) {
} catch(UnsupportedEncodingException ignored){
}
return null;
}
private static String getDeviceId(Context context) {
try {
return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
} catch (Exception e) {
return "";
}
}
}
Usage:
AdRequest adRequest = AdsHelper.createRequest(this);
You get this message when you've used async in your template, but are referring to an object that isn't an Observable.
So for examples sake, lets' say I had these properties in my class:
job:Job
job$:Observable<Job>
Then in my template, I refer to it this way:
{{job | async }}
instead of:
{{job$ | async }}
You wouldn't need the job:Job property if you use the async pipe, but it serves to illustrate a cause of the error.
If you have SQL Server installed there is also a menu option for finding local SSIS packages.
In the Start menu > All Programs > 'Microsoft Sql Server' there should be a menu option for 'Integration Services' > 'Execute Package Utility' (this is available if SSIS was included in your SQLserver installation).
When you open the Execute Package Utility, type your local sql server name in the 'Server Name' textbox and click on the Package button, you will see your saved package in the popup window. From here you can run your previously saved package
If you look at the down arrow in environment tab. The attached file can appear multiple times. You may need to highlight and run detach(filename)
several times until all cases are gone then attach(newfilename)
should have no output message.
As quick n dirty fix, this worked for me: Adding this 2 lines before the problematic import:
import sys
sys.path.append('C:\\Python27\\Lib\site-packages')
Swift 4.2 solution (taking 4.0 answer and updating for new enums to compile)
extension UIView {
func fadeTransition(_ duration:CFTimeInterval) {
let animation = CATransition()
animation.timingFunction = CAMediaTimingFunction(name:
CAMediaTimingFunctionName.easeInEaseOut)
animation.type = CATransitionType.fade
animation.duration = duration
layer.add(animation, forKey: CATransitionType.fade.rawValue)
}
}
func updateLabel() {
myLabel.fadeTransition(0.4)
myLabel.text = "Hello World"
}
Put this in the myhtml.html
file:
<!-- Import javascript -->
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<!-- Invoke a different javascript file called subscript.js -->
<script id="myscript" src="subscript.js" video_filename="foobar.mp4">/script>
In the same directory make a subscript.js
file and put this in there:
//Use jquery to look up the tag with the id of 'myscript' above. Get
//the attribute called video_filename, stuff it into variable filename.
var filename = $('#myscript').attr("video_filename");
//print filename out to screen.
document.write(filename);
Analyze Result:
Loading the myhtml.html page has 'foobar.mp4' print to screen. The variable called video_filename was passed from html to javascript. Javascript printed it to screen, and it appeared as embedded into the html in the parent.
jsfiddle proof that the above works:
<p id="text" onclick="func()">
Click on text to change
</p>
<script>
function func()
{
document.getElementById("text").style.color="red";
document.getElementById("text").style.font="calibri";
}
</script>
Functions that might be helpful:
open("file").read()
which reads the contents of the whole file at once'string'.splitlines()
which separates lines from each other (and discards empty lines)By using len() and those functions you could accomplish what you're doing.
JavaScript Code
//this function is used to fire click event
function eventFire(el, etype){
if (el.fireEvent) {
el.fireEvent('on' + etype);
} else {
var evObj = document.createEvent('Events');
evObj.initEvent(etype, true, false);
el.dispatchEvent(evObj);
}
}
function showPdf(){
eventFire(document.getElementById('picToClick'), 'click');
}
HTML Code
<img id="picToClick" data-toggle="modal" data-target="#pdfModal" src="img/Adobe-icon.png" ng-hide="1===1">
<button onclick="showPdf()">Click me</button>
You may use sshfs
:
$ sshfs user@ip:/<remote-path> <local-mount-path>
$ docker save <image-id> > <local-mount-path>/myImage.tar
First off I should point out that css animations would probably work best if you are doing this a lot but I ended getting the desired effect by wrapping .scrollLeft inside .animate
$('.swipeRight').click(function()
{
$('.swipeBox').animate( { scrollLeft: '+=460' }, 1000);
});
$('.swipeLeft').click(function()
{
$('.swipeBox').animate( { scrollLeft: '-=460' }, 1000);
});
The second parameter is speed, and you can also add a third parameter if you are using smooth scrolling of some sort.
Add extra transport to jquery for IE. ( Just add this code in your script at the end )
$.ajaxTransport("+*", function( options, originalOptions, jqXHR ) {
if(jQuery.browser.msie && window.XDomainRequest) {
var xdr;
return {
send: function( headers, completeCallback ) {
// Use Microsoft XDR
xdr = new XDomainRequest();
xdr.open("get", options.url);
xdr.onload = function() {
if(this.contentType.match(/\/xml/)){
var dom = new ActiveXObject("Microsoft.XMLDOM");
dom.async = false;
dom.loadXML(this.responseText);
completeCallback(200, "success", [dom]);
}else{
completeCallback(200, "success", [this.responseText]);
}
};
xdr.ontimeout = function(){
completeCallback(408, "error", ["The request timed out."]);
};
xdr.onerror = function(){
completeCallback(404, "error", ["The requested resource could not be found."]);
};
xdr.send();
},
abort: function() {
if(xdr)xdr.abort();
}
};
}
});
This solved my problem with Jquery $.ajax failing for Cross Domain AJAX request.
Cheers.
DEMO
In the content area you can provide whatever you want to display in it.
.black_overlay {_x000D_
display: none;_x000D_
position: absolute;_x000D_
top: 0%;_x000D_
left: 0%;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
background-color: black;_x000D_
z-index: 1001;_x000D_
-moz-opacity: 0.8;_x000D_
opacity: .80;_x000D_
filter: alpha(opacity=80);_x000D_
}_x000D_
.white_content {_x000D_
display: none;_x000D_
position: absolute;_x000D_
top: 25%;_x000D_
left: 25%;_x000D_
width: 50%;_x000D_
height: 50%;_x000D_
padding: 16px;_x000D_
border: 16px solid orange;_x000D_
background-color: white;_x000D_
z-index: 1002;_x000D_
overflow: auto;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<title>LIGHTBOX EXAMPLE</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<p>This is the main content. To display a lightbox click <a href="javascript:void(0)" onclick="document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'">here</a>_x000D_
</p>_x000D_
<div id="light" class="white_content">This is the lightbox content. <a href="javascript:void(0)" onclick="document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'">Close</a>_x000D_
</div>_x000D_
<div id="fade" class="black_overlay"></div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
You can use the connection string as follows and you only need to add your database name.
string connetionString = "Data Source=.;Initial Catalog=DB name;Integrated Security=True;MultipleActiveResultSets=True";
With jQuery, it is possible, however not using ajax.
function LoadPage(){
$.get('http://a_site.com/a_page.html', function(data) {
$('#siteloader').html(data);
});
}
And then place onload="LoadPage()"
in the body tag.
Although if you follow this route, a php version might be better:
echo htmlspecialchars(file_get_contents("some URL"));
What you could also have a look at is the exposed method Application->loadEnvironmentFrom($file)
I needed one application to run on multiple subdomains. So in bootstrap/app.php
I added something like:
$envFile = '.env';
// change $envFile conditionally here
$app->loadEnvironmentFrom($envFile);
In Xcode 9 there is a new "Actual Size" option. In the Simulator to the Window menu and choose Scale > Actual Size to trigger it. This takes into account your current screen resolution to ensure the on-screen device matches the physical dimensions of a real device.
I found that "@RequestMapping produces=" and other configuration changes didn't help me. By the time you do resp.getWriter(), it is also too late to set the encoding on the writer.
Adding a header to the HttpServletResponse works.
@RequestMapping(value="/test", method=RequestMethod.POST)
public void test(HttpServletResponse resp) {
try {
resp.addHeader("content-type", "application/json; charset=utf-8");
PrintWriter w = resp.getWriter();
w.write("{\"name\" : \"µr µicron\"}");
w.flush();
w.close();
} catch (Exception e) {
e.printStackTrace();
}
}
%~dp0 expands to current directory path of the running batch file.
To get clear understanding, let's create a batch file in a directory.
C:\script\test.bat
with contents:
@echo off
echo %~dp0
When you run it from command prompt, you will see this result:
C:\script\
Well, note that the request contains binary data, so I'm not posting the request as such - instead, I've converted every non-printable-ascii character into a dot (".").
POST /cgi-bin/qtest HTTP/1.1
Host: aram
User-Agent: Mozilla/5.0 Gecko/2009042316 Firefox/3.0.10
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://aram/~martind/banner.htm
Content-Type: multipart/form-data; boundary=2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Length: 514
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile1"; filename="r.gif"
Content-Type: image/gif
GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile2"; filename="g.gif"
Content-Type: image/gif
GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile3"; filename="b.gif"
Content-Type: image/gif
GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f--
Note that every line (including the last one) is terminated by a \r\n sequence.
I found the smoothest way to achieve this was using Pageant as the SSH agent and plink.
You need to have a putty session configured for the hostname that is used in your remote.
You will also need plink.exe which can be downloaded from the same site as putty.
And you need Pageant running with your key loaded. I have a shortcut to pageant in my startup folder that loads my SSH key when I log in.
When you install git-scm you can then specify it to use tortoise/plink rather than OpenSSH.
The net effect is you can open git-bash whenever you like and push/pull without being challenged for passphrases.
Same applies with putty and WinSCP sessions when pageant has your key loaded. It makes life a hell of a lot easier (and secure).
var result = from cx in CustomerList
group cx by cx.GroupID into cxGroup
orderby cxGroup.Key
select cxGroup;
foreach (var cxGroup in result) {
Console.WriteLine(String.Format("GroupID = {0}", cxGroup.Key));
foreach (var cx in cxGroup) {
Console.WriteLine(String.Format("\tUserID = {0}, UserName = {1}, GroupID = {2}",
new object[] { cx.ID, cx.Name, cx.GroupID }));
}
}
Bubble Sort is not online (it cannot sort a stream of inputs without knowing how many items there will be) because it does not really keep track of a global maximum of the sorted elements. When an item is inserted you will need to start the bubbling from the very beginning
I discover very simple way to redirect Login Page When session end in MVC. I have already tested it and this works without problems.
In short, I catch session end in _Layout 1 minute before and make redirection.
I try to explain everything step by step.
If we want to session end 30 minute after and redirect to loginPage see this steps:
Change the web config like this (set 31 minute):
<system.web>
<sessionState timeout="31"></sessionState>
</system.web>
Add this JavaScript in _Layout
(when session end 1 minute before this code makes redirect, it makes count time after user last action, not first visit on site)
<script>
//session end
var sessionTimeoutWarning = @Session.Timeout- 1;
var sTimeout = parseInt(sessionTimeoutWarning) * 60 * 1000;
setTimeout('SessionEnd()', sTimeout);
function SessionEnd() {
window.location = "/Account/LogOff";
}
</script>
Here is my LogOff Action, which makes only LogOff and redirect LoginIn Page
public ActionResult LogOff()
{
Session["User"] = null; //it's my session variable
Session.Clear();
Session.Abandon();
FormsAuthentication.SignOut(); //you write this when you use FormsAuthentication
return RedirectToAction("Login", "Account");
}
I hope this is a very useful code for you.
function naturalCompare(a, b) {_x000D_
var ax = [], bx = [];_x000D_
_x000D_
a.replace(/(\d+)|(\D+)/g, function (_, $1, $2) { ax.push([$1 || Infinity, $2 || ""]) });_x000D_
b.replace(/(\d+)|(\D+)/g, function (_, $1, $2) { bx.push([$1 || Infinity, $2 || ""]) });_x000D_
_x000D_
while (ax.length && bx.length) {_x000D_
var an = ax.shift();_x000D_
var bn = bx.shift();_x000D_
var nn = (an[0] - bn[0]) || an[1].localeCompare(bn[1]);_x000D_
if (nn) return nn;_x000D_
}_x000D_
_x000D_
return ax.length - bx.length;_x000D_
}_x000D_
_x000D_
let builds = [ _x000D_
{ id: 1, name: 'Build 91'}, _x000D_
{ id: 2, name: 'Build 32' }, _x000D_
{ id: 3, name: 'Build 13' }, _x000D_
{ id: 4, name: 'Build 24' },_x000D_
{ id: 5, name: 'Build 5' },_x000D_
{ id: 6, name: 'Build 56' }_x000D_
]_x000D_
_x000D_
let sortedBuilds = builds.sort((n1, n2) => {_x000D_
return naturalCompare(n1.name, n2.name)_x000D_
})_x000D_
_x000D_
console.log('Sorted by name property')_x000D_
console.log(sortedBuilds)
_x000D_
Those classes are common extension points for Java UI designs. First off, realize that they don't necessarily have much to do with each other directly, so trying to find a relationship between them might be counterproductive.
JApplet - A base class that let's you write code that will run within the context of a browser, like for an interactive web page. This is cool and all but it brings limitations which is the price for it playing nice in the real world. Normally JApplet is used when you want to have your own UI in a web page. I've always wondered why people don't take advantage of applets to store state for a session so no database or cookies are needed.
JComponent - A base class for objects which intend to interact with Swing.
JFrame - Used to represent the stuff a window should have. This includes borders (resizeable y/n?), titlebar (App name or other message), controls (minimize/maximize allowed?), and event handlers for various system events like 'window close' (permit app to exit yet?).
JPanel - Generic class used to gather other elements together. This is more important with working with the visual layout or one of the provided layout managers e.g. gridbaglayout, etc. For example, you have a textbox that is bigger then the area you have reserved. Put the textbox in a scrolling pane and put that pane into a JPanel. Then when you place the JPanel, it will be more manageable in terms of layout.
string replace() function perfectly solves this problem:
string.replace(s, old, new[, maxreplace])
Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.
>>> u'longlongTESTstringTEST'.replace('TEST', '?', 1)
u'longlong?stringTEST'
I ran across this post today as I was running into the same issue and had the same problem of the javascript not running with the CDATA tags listed above. I corrected the CDATA tags to look like:
<script type="text/javascript">
//<![CDATA[
your javascript code here
//]]>
</script>
Then everything worked perfectly!
Below is an example of such a query:
INSERT INTO [93275].[93276].[93277].[93278] ( [Mobile Number], [Mobile Series], [Full Name], [Full Address], [Active Date], company ) IN 'I:\For Test\90-Mobile Series.accdb
SELECT [1].[Mobile Number], [1].[Mobile Series], [1].[Full Name], [1].[Full Address], [1].[Active Date], [1].[Company Name]
FROM 1
WHERE ((([1].[Mobile Series])="93275" Or ([1].[Mobile Series])="93276")) OR ((([1].[Mobile Series])="93277"));OR ((([1].[Mobile Series])="93278"));
I found this thread while trying to convert a list to the real value of the underlying int in terms of a C-style pointer, but none of the other answers appear to work for this case. I think the following solution works as intended and could be useful to others even though it doesn't necessarily answer the original question.
def listToInt(x, reverseBytes=False):
if reverseBytes:
x = x[::-1]
return reduce(lambda x,y: x*256+y, x)
listToInt([1, 249]) == 505
listToInt([249, 1], True) == 505
The primary value of this is to emulate the behavior of casting a byte array to another data type, e.g. uint16, which Python can't seem to do natively, on either a big or little endian system.
I had major trouble getting this to work in RCx releases of angular2. The Location package has moved, and running location.go() inside constructor() wont work. It needs to be ngOnInit() or later in the lifecycle. Here is some example code:
import {OnInit} from '@angular/core';
import {Location} from '@angular/common';
@Component({
selector: 'example-component',
templateUrl: 'xxx.html'
})
export class ExampleComponent implements OnInit
{
constructor( private location: Location )
{}
ngOnInit()
{
this.location.go( '/example;example_param=917' );
}
}
Here are the angular resources on the matter: https://angular.io/docs/ts/latest/api/common/index/Location-class.html https://angular.io/docs/ts/latest/api/common/index/LocationStrategy-class.html
You want to execute code where the id is not (1 or 2 or 3), but the OR operator does not distribute over id. The only way to say what you want is to say
the id is not 1, and the id is not 2, and the id is not 3.
which translates to
if (id !== 1 && id !== 2 && id !== 3)
or alternatively for something more pythonesque:
if (!(id in [,1,2,3]))
Please try this steps in git bash, It may help you.
CTRL + C
:qa!
The results from json.Unmarshal
(into var data interface{}
) do not directly match your Go type and variable declarations. For example,
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
)
type Tracks struct {
Toptracks []Toptracks_info
}
type Toptracks_info struct {
Track []Track_info
Attr []Attr_info
}
type Track_info struct {
Name string
Duration string
Listeners string
Mbid string
Url string
Streamable []Streamable_info
Artist []Artist_info
Attr []Track_attr_info
}
type Attr_info struct {
Country string
Page string
PerPage string
TotalPages string
Total string
}
type Streamable_info struct {
Text string
Fulltrack string
}
type Artist_info struct {
Name string
Mbid string
Url string
}
type Track_attr_info struct {
Rank string
}
func get_content() {
// json data
url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"
url += "&limit=1" // limit data for testing
res, err := http.Get(url)
if err != nil {
panic(err.Error())
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
panic(err.Error())
}
var data interface{} // TopTracks
err = json.Unmarshal(body, &data)
if err != nil {
panic(err.Error())
}
fmt.Printf("Results: %v\n", data)
os.Exit(0)
}
func main() {
get_content()
}
Output:
Results: map[toptracks:map[track:map[name:Get Lucky (feat. Pharrell Williams) listeners:1863 url:http://www.last.fm/music/Daft+Punk/_/Get+Lucky+(feat.+Pharrell+Williams) artist:map[name:Daft Punk mbid:056e4f3e-d505-4dad-8ec1-d04f521cbb56 url:http://www.last.fm/music/Daft+Punk] image:[map[#text:http://userserve-ak.last.fm/serve/34s/88137413.png size:small] map[#text:http://userserve-ak.last.fm/serve/64s/88137413.png size:medium] map[#text:http://userserve-ak.last.fm/serve/126/88137413.png size:large] map[#text:http://userserve-ak.last.fm/serve/300x300/88137413.png size:extralarge]] @attr:map[rank:1] duration:369 mbid: streamable:map[#text:1 fulltrack:0]] @attr:map[country:Netherlands page:1 perPage:1 totalPages:500 total:500]]]
I strongly suspect that's because of the network connection or the web server you're talking to - it's not BufferedReader
's fault. Try measuring this:
InputStream stream = conn.getInputStream();
byte[] buffer = new byte[1000];
// Start timing
while (stream.read(buffer) > 0)
{
}
// End timing
I think you'll find it's almost exactly the same time as when you're parsing the text.
Note that you should also give InputStreamReader
an appropriate encoding - the platform default encoding is almost certainly not what you should be using.
If you don't actually need a backup of the database dumped onto disk in a plain-text .sql script file format, you could connect pg_dump
and pg_restore
directly together over a pipe.
To drop and recreate tables, you could use the --clean
command-line option for pg_dump
to emit SQL commands to clean (drop) database objects prior to (the commands for) creating them. (This will not drop the whole database, just each table/sequence/index/etc. before recreating them.)
The above two would look something like this:
pg_dump -U username --clean | pg_restore -U username
From the Javadocs for setDisplayOrientation(int)
(Requires API level 9):
public static void setCameraDisplayOrientation(Activity activity,
int cameraId, android.hardware.Camera camera) {
android.hardware.Camera.CameraInfo info =
new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(cameraId, info);
int rotation = activity.getWindowManager().getDefaultDisplay()
.getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0: degrees = 0; break;
case Surface.ROTATION_90: degrees = 90; break;
case Surface.ROTATION_180: degrees = 180; break;
case Surface.ROTATION_270: degrees = 270; break;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
camera.setDisplayOrientation(result);
}
check this same effect with less code
$(".item").mouseover(function(){
$('.info').animate({ marginTop: '-50px' , opacity: 0.5 }, 1000);
});
You don't need to create a button. The facility exists by default.
Just right click on the arrow buttons on the bottom left hand corner of the Excel window. These are the arrow buttons which if you left click move left or right one worksheet.
If you right-click on these arrows Excel will pop up a dialogue with a list of worksheets from which you can click to set your chosen sheet active.
Here is a simple example that I tried to explain.
<div>
<div *ngIf="product"> <!--If "product" exists-->
<h2>Product Details</h2><hr>
<h4>Name: {{ product.name }}</h4>
<h5>Price: {{ product.price | currency }}</h5>
<p> Description: {{ product.description }}</p>
</div>
<div *ngIf="!product"> <!--If "product" not exists-->
*Product not found
</div>
</div>
Answer above is not suitable for complicate Linq expression. All you need is:
// set up the "main query"
var test = from p in _db.test select _db.test;
// if str1 is not null, add a where-condition
if(str1 != null)
{
test = test.Where(p => p.test == str);
}
There does not seem to be any standard immutable interface for dictionaries, so creating a wrapper seems like the only reasonable option, unfortunately.
Edit: Marc Gravell found the ILookup that I missed - that will allow you to at least avoid creating a new wrapper, although you still need to transform the Dictionary with .ToLookup().
If this is a need constrained to a specific scenario, you might be better off with a more business-logic-oriented interface:
interface IActiveUserCountProvider
{
int GetMaxForServer(string serverName);
}
For macOS Mojave , additional configuration was required, for compilers to find openssl you may need to set:
export LDFLAGS="-L/usr/local/opt/openssl/lib"
export CPPFLAGS="-I/usr/local/opt/openssl/include"
This method doesn't seem to work in my browser, and looking around indicates that the whole subject of specifying headers to a mailto
link/action is sparsely supported, but maybe this can help...
HTML:
<form id="fr1">
<input type="text" id="tb1" />
<input type="text" id="tb2" />
<input type="button" id="bt1" value="click" />
</form>
JavaScript (with jQuery):
$(document).ready(function() {
$('#bt1').click(function() {
$('#fr1').attr('action',
'mailto:[email protected]?subject=' +
$('#tb1').val() + '&body=' + $('#tb2').val());
$('#fr1').submit();
});
});
Notice what I'm doing here. The form itself has no action associated with it. And the submit button isn't really a submit
type, it's just a button
type. Using JavaScript, I'm binding to that button's click event, setting the form's action attribute, and then submitting the form.
It's working in so much as it submits the form to a mailto
action (my default mail program pops up and opens a new message to the specified address), but for me (Safari, Mail.app) it's not actually specifying the Subject or Body in the resulting message.
HTML isn't really a very good medium for doing this, as I'm sure others are pointing out while I type this. It's possible that this may work in some browsers and/or some mail clients. However, it's really not even a safe assumption anymore that users will have a fat mail client these days. I can't remember the last time I opened mine. HTML's mailto
is a bit of legacy functionality and, these days, it's really just as well that you perform the mail action on the server-side if possible.
This is a definitive un-answer: eliminating a tempting-but-wrong answer to help others navigate toward correct answers.
It might seem like debugging would highlight the problem. However, the only browser the problem occurs in is IE, and in IE you can only debug code that was part of the original document. For dynamically added code, the debugger just shows the body element as the current instruction, and IE claims the error happened on a huge line number.
Here's a sample web page that will demonstrate this problem in IE:
<html>
<head>
<title>javascript debug test</title>
</head>
<body onload="attachScript();">
<script type="text/javascript">
function attachScript() {
var s = document.createElement("script");
s.setAttribute("type", "text/javascript");
document.body.appendChild(s);
s.text = "var a = document.getElementById('nonexistent'); alert(a.tagName);"
}
</script>
</body>
This yielded for me the following error:
Line: 54654408
Error: Object required
Once you have put the values into the JSONObject then put the JSONObject into the JSONArray staright after.
Something like this maybe:
jsonObj.put("value1", 1);
jsonObj.put("value2", 900);
jsonObj.put("value3", 1368349);
jsonArray.put(jsonObj);
Then create new JSONObject, put the other values into it and add it to the JSONArray:
jsonObj.put("value1", 2);
jsonObj.put("value2", 1900);
jsonObj.put("value3", 136856);
jsonArray.put(jsonObj);
They serve the actual image inside CSS so there will be less HTTP requests per page.
coalesce
is supported in both Oracle and SQL Server and serves essentially the same function as nvl
and isnull
. (There are some important differences, coalesce
can take an arbitrary number of arguments, and returns the first non-null one. The return type for isnull
matches the type of the first argument, that is not true for coalesce
, at least on SQL Server.)
There is no i
in xpath is not entirely true. You can still use the count()
to find the index.
Consider the following page
<html>_x000D_
_x000D_
<head>_x000D_
<title>HTML Sample table</title>_x000D_
</head>_x000D_
_x000D_
<style>_x000D_
table, td, th {_x000D_
border: 1px solid black;_x000D_
font-size: 15px;_x000D_
font-family: Trebuchet MS, sans-serif;_x000D_
}_x000D_
table {_x000D_
border-collapse: collapse;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
th, td {_x000D_
text-align: left;_x000D_
padding: 8px;_x000D_
}_x000D_
_x000D_
tr:nth-child(even){background-color: #f2f2f2}_x000D_
_x000D_
th {_x000D_
background-color: #4CAF50;_x000D_
color: white;_x000D_
}_x000D_
</style>_x000D_
_x000D_
<body>_x000D_
<table>_x000D_
<thead>_x000D_
<tr>_x000D_
<th>Heading 1</th>_x000D_
<th>Heading 2</th>_x000D_
<th>Heading 3</th>_x000D_
<th>Heading 4</th>_x000D_
<th>Heading 5</th>_x000D_
<th>Heading 6</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>Data row 1 col 1</td>_x000D_
<td>Data row 1 col 2</td>_x000D_
<td>Data row 1 col 3</td>_x000D_
<td>Data row 1 col 4</td>_x000D_
<td>Data row 1 col 5</td>_x000D_
<td>Data row 1 col 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data row 2 col 1</td>_x000D_
<td>Data row 2 col 2</td>_x000D_
<td>Data row 2 col 3</td>_x000D_
<td>Data row 2 col 4</td>_x000D_
<td>Data row 2 col 5</td>_x000D_
<td>Data row 2 col 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data row 3 col 1</td>_x000D_
<td>Data row 3 col 2</td>_x000D_
<td>Data row 3 col 3</td>_x000D_
<td>Data row 3 col 4</td>_x000D_
<td>Data row 3 col 5</td>_x000D_
<td>Data row 3 col 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data row 4 col 1</td>_x000D_
<td>Data row 4 col 2</td>_x000D_
<td>Data row 4 col 3</td>_x000D_
<td>Data row 4 col 4</td>_x000D_
<td>Data row 4 col 5</td>_x000D_
<td>Data row 4 col 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data row 5 col 1</td>_x000D_
<td>Data row 5 col 2</td>_x000D_
<td>Data row 5 col 3</td>_x000D_
<td>Data row 5 col 4</td>_x000D_
<td>Data row 5 col 5</td>_x000D_
<td>Data row 5 col 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td><button>Modify</button></td>_x000D_
<td><button>Modify</button></td>_x000D_
<td><button>Modify</button></td>_x000D_
<td><button>Modify</button></td>_x000D_
<td><button>Modify</button></td>_x000D_
<td><button>Modify</button></td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
_x000D_
</br>_x000D_
_x000D_
<table>_x000D_
<thead>_x000D_
<tr>_x000D_
<th>Heading 7</th>_x000D_
<th>Heading 8</th>_x000D_
<th>Heading 9</th>_x000D_
<th>Heading 10</th>_x000D_
<th>Heading 11</th>_x000D_
<th>Heading 12</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>Data row 1 col 1</td>_x000D_
<td>Data row 1 col 2</td>_x000D_
<td>Data row 1 col 3</td>_x000D_
<td>Data row 1 col 4</td>_x000D_
<td>Data row 1 col 5</td>_x000D_
<td>Data row 1 col 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data row 2 col 1</td>_x000D_
<td>Data row 2 col 2</td>_x000D_
<td>Data row 2 col 3</td>_x000D_
<td>Data row 2 col 4</td>_x000D_
<td>Data row 2 col 5</td>_x000D_
<td>Data row 2 col 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data row 3 col 1</td>_x000D_
<td>Data row 3 col 2</td>_x000D_
<td>Data row 3 col 3</td>_x000D_
<td>Data row 3 col 4</td>_x000D_
<td>Data row 3 col 5</td>_x000D_
<td>Data row 3 col 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data row 4 col 1</td>_x000D_
<td>Data row 4 col 2</td>_x000D_
<td>Data row 4 col 3</td>_x000D_
<td>Data row 4 col 4</td>_x000D_
<td>Data row 4 col 5</td>_x000D_
<td>Data row 4 col 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data row 5 col 1</td>_x000D_
<td>Data row 5 col 2</td>_x000D_
<td>Data row 5 col 3</td>_x000D_
<td>Data row 5 col 4</td>_x000D_
<td>Data row 5 col 5</td>_x000D_
<td>Data row 5 col 6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td><button>Modify</button></td>_x000D_
<td><button>Modify</button></td>_x000D_
<td><button>Modify</button></td>_x000D_
<td><button>Modify</button></td>_x000D_
<td><button>Modify</button></td>_x000D_
<td><button>Modify</button></td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
The page has 2 tables and has 6 columns each with unique column names and 6 rows with variable data. The last row has the Modify
button in both the tables.
Assuming that the user has to select the 4th Modify
button from the first table based on the heading
Use the xpath //th[.='Heading 4']/ancestor::thead/following-sibling::tbody/tr/td[count(//tr/th[.='Heading 4']/preceding-sibling::th)+1]/button
The count()
operator comes in handy in situations like these.
Logic:
Modify
button using //th[.='Heading 4']
count(//tr/th[.='Heading 4']/preceding-sibling::th)+1
Note: Index starts at
0
Get the rows for the corresponding header using //th[.='Heading 4']/ancestor::thead/following-sibling::tbody/tr/td[count(//tr/th[.='Heading 4']/preceding-sibling::th)+1]
Get the Modify
button from the extracted node list using //th[.='Heading 4']/ancestor::thead/following-sibling::tbody/tr/td[count(//tr/th[.='Heading 4']/preceding-sibling::th)+1]/button
You can get it by XMLHttpRequest.responseText
in XMLHttpRequest.onreadystatechange
when XMLHttpRequest.readyState
equals to XMLHttpRequest.DONE
.
Here's an example (not compatible with IE6/7).
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
alert(xhr.responseText);
}
}
xhr.open('GET', 'http://example.com', true);
xhr.send(null);
For better crossbrowser compatibility, not only with IE6/7, but also to cover some browser-specific memory leaks or bugs, and also for less verbosity with firing ajaxical requests, you could use jQuery.
$.get('http://example.com', function(responseText) {
alert(responseText);
});
Note that you've to take the Same origin policy for JavaScript into account when not running at localhost. You may want to consider to create a proxy script at your domain.
i = 20
"%x" % i #=> "14"
In your case, you need to use Sprintf() for format string.
func Sprintf(format string, a ...interface{}) string
Sprintf formats according to a format specifier and returns the resulting string.
s := fmt.Sprintf("Good Morning, This is %s and I'm living here from last %d years ", "John", 20)
Your output will be :
Good Morning, This is John and I'm living here from last 20 years.
This is the easiest and simple way ever exist on the internet... First of all, add this permission to your manifest file...
"INTERNET"
"ACCESS_NETWORK_STATE"
add this in onCreate file of Activity..
getPublicIP();
Now Add this function to your MainActivity.class.
private void getPublicIP() {_x000D_
ArrayList<String> urls=new ArrayList<String>(); //to read each line_x000D_
_x000D_
new Thread(new Runnable(){_x000D_
public void run(){_x000D_
//TextView t; //to show the result, please declare and find it inside onCreate()_x000D_
_x000D_
try {_x000D_
// Create a URL for the desired page_x000D_
URL url = new URL("https://api.ipify.org/"); //My text file location_x000D_
//First open the connection_x000D_
HttpURLConnection conn=(HttpURLConnection) url.openConnection();_x000D_
conn.setConnectTimeout(60000); // timing out in a minute_x000D_
_x000D_
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));_x000D_
_x000D_
//t=(TextView)findViewById(R.id.TextView1); // ideally do this in onCreate()_x000D_
String str;_x000D_
while ((str = in.readLine()) != null) {_x000D_
urls.add(str);_x000D_
}_x000D_
in.close();_x000D_
} catch (Exception e) {_x000D_
Log.d("MyTag",e.toString());_x000D_
}_x000D_
_x000D_
//since we are in background thread, to post results we have to go back to ui thread. do the following for that_x000D_
_x000D_
PermissionsActivity.this.runOnUiThread(new Runnable(){_x000D_
public void run(){_x000D_
try {_x000D_
Toast.makeText(PermissionsActivity.this, "Public IP:"+urls.get(0), Toast.LENGTH_SHORT).show();_x000D_
}_x000D_
catch (Exception e){_x000D_
Toast.makeText(PermissionsActivity.this, "TurnOn wiffi to get public ip", Toast.LENGTH_SHORT).show();_x000D_
}_x000D_
}_x000D_
});_x000D_
_x000D_
}_x000D_
}).start();_x000D_
_x000D_
}
_x000D_
you can used:
$("#d").val(null).trigger("change");
It's very simple and work right! If use with reset button:
$('#btnReset').click(function() {
$("#d").val(null).trigger("change");
});
You can get a request parameter id using the expression:
<h:outputText value="#{param['id']}" />
Section 5.3.1.2 of the JSF 1.0 specification defines the objects that must be resolved by the variable resolver.
It mostly depends on how big n
is.
If n==0
, nothing beats option#1 :)
If n is very large, toArray(new String[n])
is faster.
You can refer to the following article: http://www.wellho.net/mouth/3934_Multiple-identical-keys-in-a-Python-dict-yes-you-can-.html
In a dict, if a key is an object, there are no duplicate problems.
For example:
class p(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
def __str__(self):
return self.name
d = {p('k'): 1, p('k'): 2}
To find all valid address list this is the code I have used
public static IEnumerable<string> GetAddresses()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
return (from ip in host.AddressList where ip.AddressFamily == AddressFamily.lo select ip.ToString()).ToList();
}
structure is collection of different data type where different type of data can reside in it and every one get its own block of memory
we usually used union when we sure that only one of the variable will be used at once and you want fully utilization of present memory because it get only one block of memory which is equal to the biggest type.
struct emp
{
char x;//1 byte
float y; //4 byte
} e;
total memory it get =>5 byte
union emp
{
char x;//1 byte
float y; //4 byte
} e;
total memory it get =4 byte
As mentioned you need to use obj.getTile()
But, in this case I think you are looking to use a Property.
public class Pin
{
private string title;
public Pin() { }
public setTitle(string title) {
this.title = title;
}
public String Title
{
get { return title; }
}
}
This will allow you to use
foreach (Pin obj in ClassListPin.pins)
{
string t = obj.Title;
}
Even if you could get it to work in one browser, there's no guarantee that it would work the same in all browsers. So while you might be able to get it to work some of the time, you certainly wouldn't be able to get it to work all of the time.
Try this. It worked for me
npm uninstall -g @angular/cli
npm cache verify
npm install -g @angular/cli@next
I came here, working with kitchen-CI and having problems with vagrant.
After (re-)moving the "~/.kitchen"-directory the kitchen converge
was successfull again
(eclipse-workspace)\.metadata\.plugins\org.eclipse.wst.server.core
and delete all tmp folders.What does the exclamation mark after the gem name in the 'DEPENDECIES' group mean?
The exclamation mark appears when the gem was installed using a source other than "https://rubygems.org".
Lambda expressions have a type of Action<parameters>
(in case they don't return a value) or Func<parameters,return>
(in case they have a return value). In your case you have two input parameters, and you need to return a value, so you should use:
Func<FullTimeJob, Student, FullTimeJob>
I've got two points to add. One, Hudson/Jenkins is all about the plugins. Plugin developers have moved to Jenkins and so should we, the users. Two, I am not personally a big fan of Oracle's products. In fact, I avoid them like the plague. For the money spent on licensing and hardware for an Oracle solution you can hire twice the engineering staff and still have some left over to buy beer every Friday :)
Even though I realise this is an old question, I'd like to suggest using the traceback
module to handle output of the exceptions.
Use traceback.print_exc()
to print the current exception to standard error, just like it would be printed if it remained uncaught, or traceback.format_exc()
to get the same output as a string. You can pass various arguments to either of those functions if you want to limit the output, or redirect the printing to a file-like object.
You can try using constructor.name
.
[].constructor.name
new RegExp().constructor.name
As with everything JavaScript, someone will eventually invariably point that this is somehow evil, so here is a link to an answer that covers this pretty well.
An alternative is to use Object.prototype.toString.call
Object.prototype.toString.call([])
Object.prototype.toString.call(/./)
If target column type is other than varchar/nvarchar like text, we need to cast the column value as string and then convert it as:
update URL_TABLE
set Parameters = REPLACE ( cast(Parameters as varchar(max)), 'india', 'bharat')
where URL_ID='150721_013359670'
I got this error when I added the service class. I was using Angular 9 Went for several solutions, nothing helped me to resolve this issue. If U tried everything make sure u added ng module reference in core lib inside service. See Img
Casting to an int
truncates the value. Adding 0.5
causes it to do proper rounding.
int y = (int)(x + 0.5);
See this script in Microsoft's developer archives: https://msdn.microsoft.com/en-us/library/ms537509%28v=vs.85%29.aspx
I have used this script in quite a few projects, never had any problems.
When you have changes on your working copy, from command line do:
git stash
This will stash your changes and clear your status report
git pull
This will pull changes from upstream branch. Make sure it says fast-forward in the report. If it doesn't, you are probably doing an unintended merge
git stash pop
This will apply stashed changes back to working copy and remove the changes from stash unless you have conflicts. In the case of conflict, they will stay in stash so you can start over if needed.
if you need to see what is in your stash
git stash list
this part :
"Your new price is: $"(float(price)
asks python to call this string:
"Your new price is: $"
just like you would a function:
function( some_args)
which will ALWAYS trigger the error:
TypeError: 'str' object is not callable
In case you don't have some id, e.g., mysite.com/something/9182301, you can use get_object_or_404
importing by from django.shortcuts import get_object_or_404
.
Use example:
def myFunc(request, my_pk):
my_var = get_object_or_404(CLASS_NAME, pk=my_pk)
String upToNCharacters = String.format("%."+ n +"s", str);
Awful if n
is a variable (so you must construct the format string), but pretty clear if a constant:
String upToNCharacters = String.format("%.10s", str);
rename your catalog, don't contain Decimal point & 0(zero).
like this, I solve it .
try removing the padding/margins from the body tag.
body{
padding:0px;
margin:0px;
}
run the following code in a .py file:
import sys
print(sys.version)
print(sys.executable)
You can use:
setx PATH "%PATH%;C:\\Something\\bin"
However, setx
will truncate the stored string to 1024 bytes, potentially corrupting the PATH.
/M
will change the PATH
in HKEY_LOCAL_MACHINE
instead of HKEY_CURRENT_USER
. In other words, a system variable, instead of the user's. For example:
SETX /M PATH "%PATH%;C:\your path with spaces"
You have to keep in mind, the new PATH is not visible in your current cmd.exe
.
But if you look in the registry or on a new cmd.exe
with "set p"
you can see the new value.
You can execute
git status -s
This will show modified files name and then by copying the interested file path you can see changes using git diff
git diff <filepath + filename>
In Swift 4 :
let alert=UIAlertController(title:"someAlert", message: "someMessage", preferredStyle:UIAlertControllerStyle.alert )
alert.addAction(UIAlertAction(title: "ok", style: UIAlertActionStyle.default, handler: {
_ in print("FOO ")
}))
present(alert, animated: true, completion: nil)
I also recommend httplib2 by Joe Gregario. I use this regularly instead of httplib in the standard lib.
If you are using Hibernate as a JPA implementation and you are not using Maven/Gradle, the easier way is to download whole bundle instead of jar file one by one.
Go http://hibernate.org/orm/downloads/ and download the latest library, extract the jar from the required
folder.
#splits string according to delimeters
'''
Let's make a function that can split a string
into list according the given delimeters.
example data: cat;dog:greff,snake/
example delimeters: ,;- /|:
'''
def string_to_splitted_array(data,delimeters):
#result list
res = []
# we will add chars into sub_str until
# reach a delimeter
sub_str = ''
for c in data: #iterate over data char by char
# if we reached a delimeter, we store the result
if c in delimeters:
# avoid empty strings
if len(sub_str)>0:
# looks like a valid string.
res.append(sub_str)
# reset sub_str to start over
sub_str = ''
else:
# c is not a deilmeter. then it is
# part of the string.
sub_str += c
# there may not be delimeter at end of data.
# if sub_str is not empty, we should att it to list.
if len(sub_str)>0:
res.append(sub_str)
# result is in res
return res
# test the function.
delimeters = ',;- /|:'
# read the csv data from console.
csv_string = input('csv string:')
#lets check if working.
splitted_array = string_to_splitted_array(csv_string,delimeters)
print(splitted_array)
As per RFC2368 which defines mailto:
, further reinforced by an example in RFC1738, it is explicitly stated that the only valid way to generate a line break is with %0D%0A
.
This also applies to all url schemes such as gopher, smtp, sdp, imap, ldap, etc..
Set a zero height table footer view (perhaps in your viewDidLoad
method), like so:
Swift:
tableView.tableFooterView = UIView()
Objective-C:
tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
Because the table thinks there is a footer to show, it doesn't display any cells beyond those you explicitly asked for.
Interface builder pro-tip:
If you are using a xib/Storyboard, you can just drag a UIView (with height 0pt) onto the bottom of the UITableView.
In JavaScript you can encode single quotes as "\x27" and double quotes as "\x22". Therefore, with this method you can, once you're inside the (double or single) quotes of a JavaScript string literal, use the \x27 \x22 with impunity without fear of any embedded quotes "breaking out" of your string.
\xXX is for chars < 127, and \uXXXX for Unicode, so armed with this knowledge you can create a robust JSEncode function for all characters that are out of the usual whitelist.
For example,
<a href="#" onclick="SelectSurveyItem('<% JSEncode(itemid) %>', '<% JSEncode(itemname) %>'); return false;">Select</a>
I'd use a timedelta
object.
from datetime import datetime, timedelta
...
period = timedelta(minutes=1)
next_time = datetime.now() + period
minutes = 0
while run == 'start':
if next_time <= datetime.now():
minutes += 1
next_time += period
I found the answer :)
Use JsonPath or XmlPath (in case you have XML) to get data from the response body.
In my case:
JsonPath jsonPath = new JsonPath(responseBody);
int user_id = jsonPath.getInt("user_id");
an extension to Adam's answer incase you need to prevend default, here is a work around:
$(document).on('DOMNodeRemoved', function(e){
if($(e.target).hasClass('my-elm') && !e.target.hasAttribute('is-clone')){
let clone = $(e.target).clone();
$(clone).attr('is-clone', ''); //allows the clone to be removed without triggering the function again
//you can do stuff to clone here (ex: add a fade animation)
$(clone).insertAfter(e.target);
setTimeout(() => {
//optional remove clone after 1 second
$(clone).remove();
}, 1000);
}
});
This example might help someone:
Note "origin
" is my alias for remote "What is on Github"
Note "mybranch
" is my alias for my branch "what is local" that I'm syncing with github
--your branch name is 'master' if you didn't create one. However, I'm using the different name mybranch
to show where the branch name parameter is used.
What exactly are my remote repos on github?
$ git remote -v
origin https://github.com/flipmcf/Playground.git (fetch)
origin https://github.com/flipmcf/Playground.git (push)
Add the "other github repository of the same code" - we call this a fork:
$ git remote add someOtherRepo https://github.com/otherUser/Playground.git
$git remote -v
origin https://github.com/flipmcf/Playground.git (fetch)
origin https://github.com/flipmcf/Playground.git (push)
someOtherRepo https://github.com/otherUser/Playground.git (push)
someOtherRepo https://github.com/otherUser/Playground.git (fetch)
make sure our local repo is up to date:
$ git fetch
Change some stuff locally. let's say file ./foo/bar.py
$ git status
# On branch mybranch
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# modified: foo/bar.py
Review my uncommitted changes
$ git diff mybranch
diff --git a/playground/foo/bar.py b/playground/foo/bar.py
index b4fb1be..516323b 100655
--- a/playground/foo/bar.py
+++ b/playground/foo/bar.py
@@ -1,27 +1,29 @@
- This line is wrong
+ This line is fixed now - yea!
+ And I added this line too.
Commit locally.
$ git commit foo/bar.py -m"I changed stuff"
[myfork 9f31ff7] I changed stuff
1 files changed, 2 insertions(+), 1 deletions(-)
Now, I'm different than my remote (on github)
$ git status
# On branch mybranch
# Your branch is ahead of 'origin/mybranch' by 1 commit.
#
nothing to commit (working directory clean)
Diff this with remote - your fork:
(this is frequently done with git diff master origin
)
$ git diff mybranch origin
diff --git a/playground/foo/bar.py b/playground/foo/bar.py
index 516323b..b4fb1be 100655
--- a/playground/foo/bar.py
+++ b/playground/foo/bar.py
@@ -1,27 +1,29 @@
- This line is wrong
+ This line is fixed now - yea!
+ And I added this line too.
(git push to apply these to remote)
How does my remote branch differ from the remote master branch?
$ git diff origin/mybranch origin/master
How does my local stuff differ from the remote master branch?
$ git diff origin/master
How does my stuff differ from someone else's fork, master branch of the same repo?
$git diff mybranch someOtherRepo/master
Another way of doing this would be using Aggregation. You should be able to achieve a similar result using a single query. Such as this:
Item.objects.values("contest").annotate(Count("id"))
I did not test this specific query, but this should output a count of the items for each value in contests as a dictionary.
Although it has been a while since this question was asked, I will post my answer hoping it helps somebody.
Disclaimer: I know this solution is not standard, but I think it works well.
import pandas as pd
import numpy as np
data = np.array([[10, 2, 10, 10],
[10, 3, 60, 100],
[np.nan] * 4,
[10, 22, 280, 250]]).T
idx = pd.date_range('20150131', end='20150203')
df = pd.DataFrame(data=data, columns=list('ABCD'), index=idx)
df
A B C D
=================================
2015-01-31 10 10 NaN 10
2015-02-01 2 3 NaN 22
2015-02-02 10 60 NaN 280
2015-02-03 10 100 NaN 250
def calculate(mul, add):
global value
value = value * mul + add
return value
value = df.loc['2015-01-31', 'D']
df.loc['2015-01-31', 'C'] = value
df.loc['2015-02-01':, 'C'] = df.loc['2015-02-01':].apply(lambda row: calculate(*row[['A', 'B']]), axis=1)
df
A B C D
=================================
2015-01-31 10 10 10 10
2015-02-01 2 3 23 22
2015-02-02 10 60 290 280
2015-02-03 10 100 3000 250
So basically we use a apply
from pandas and the help of a global variable that keeps track of the previous calculated value.
Time comparison with a for
loop:
data = np.random.random(size=(1000, 4))
idx = pd.date_range('20150131', end='20171026')
df = pd.DataFrame(data=data, columns=list('ABCD'), index=idx)
df.C = np.nan
df.loc['2015-01-31', 'C'] = df.loc['2015-01-31', 'D']
%%timeit
for i in df.loc['2015-02-01':].index.date:
df.loc[i, 'C'] = df.loc[(i - pd.DateOffset(days=1)).date(), 'C'] * df.loc[i, 'A'] + df.loc[i, 'B']
3.2 s ± 114 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
data = np.random.random(size=(1000, 4))
idx = pd.date_range('20150131', end='20171026')
df = pd.DataFrame(data=data, columns=list('ABCD'), index=idx)
df.C = np.nan
def calculate(mul, add):
global value
value = value * mul + add
return value
value = df.loc['2015-01-31', 'D']
df.loc['2015-01-31', 'C'] = value
%%timeit
df.loc['2015-02-01':, 'C'] = df.loc['2015-02-01':].apply(lambda row: calculate(*row[['A', 'B']]), axis=1)
1.82 s ± 64.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
So 0.57 times faster on average.
It seems none of the current answers will actually remove 100% of whitespace from the start and end of a string.
As mentioned in other posts, the default TRIM
only removes spaces - not tabs, formfeeds etc. A combination of TRIM
s specifying other whitespace characters may provide a limited improvement e.g. TRIM(BOTH '\r' FROM TRIM(BOTH '\n' FROM TRIM(BOTH '\f' FROM TRIM(BOTH '\t' FROM TRIM(txt)))))
. But the problem with this approach is only a single character can be specified for a particular TRIM
and those characters are only removed from the start and end. So if the string being trimmed is something like \t \t \t \t
(i.e. alternate spaces and tab characters), more TRIM
s would be needed - and in the general case this could go on indefinitely.
For a lightweight solution, it should be possible to write a simple User Defined Function (UDF) to do the job by looping through the characters at the start and end of a string. But I'm not going to do that... as I've already written a rather more heavyweight regular expression replacer which can also do the job - and may come in useful for other reasons, as described in this blog post.
Demo
Rextester online demo. In particular, the last row shows the other methods failing but the regular expression method succeeding.
Function:
-- ------------------------------------------------------------------------------------
-- USAGE
-- ------------------------------------------------------------------------------------
-- SELECT reg_replace(<subject>,
-- <pattern>,
-- <replacement>,
-- <greedy>,
-- <minMatchLen>,
-- <maxMatchLen>);
-- where:
-- <subject> is the string to look in for doing the replacements
-- <pattern> is the regular expression to match against
-- <replacement> is the replacement string
-- <greedy> is TRUE for greedy matching or FALSE for non-greedy matching
-- <minMatchLen> specifies the minimum match length
-- <maxMatchLen> specifies the maximum match length
-- (minMatchLen and maxMatchLen are used to improve efficiency but are
-- optional and can be set to 0 or NULL if not known/required)
-- Example:
-- SELECT reg_replace(txt, '^[Tt][^ ]* ', 'a', TRUE, 2, 0) FROM tbl;
DROP FUNCTION IF EXISTS reg_replace;
CREATE FUNCTION reg_replace(subject VARCHAR(21845), pattern VARCHAR(21845),
replacement VARCHAR(21845), greedy BOOLEAN, minMatchLen INT, maxMatchLen INT)
RETURNS VARCHAR(21845) DETERMINISTIC BEGIN
DECLARE result, subStr, usePattern VARCHAR(21845);
DECLARE startPos, prevStartPos, startInc, len, lenInc INT;
IF subject REGEXP pattern THEN
SET result = '';
-- Sanitize input parameter values
SET minMatchLen = IF(minMatchLen < 1, 1, minMatchLen);
SET maxMatchLen = IF(maxMatchLen < 1 OR maxMatchLen > CHAR_LENGTH(subject),
CHAR_LENGTH(subject), maxMatchLen);
-- Set the pattern to use to match an entire string rather than part of a string
SET usePattern = IF (LEFT(pattern, 1) = '^', pattern, CONCAT('^', pattern));
SET usePattern = IF (RIGHT(pattern, 1) = '$', usePattern, CONCAT(usePattern, '$'));
-- Set start position to 1 if pattern starts with ^ or doesn't end with $.
IF LEFT(pattern, 1) = '^' OR RIGHT(pattern, 1) <> '$' THEN
SET startPos = 1, startInc = 1;
-- Otherwise (i.e. pattern ends with $ but doesn't start with ^): Set start position
-- to the min or max match length from the end (depending on "greedy" flag).
ELSEIF greedy THEN
SET startPos = CHAR_LENGTH(subject) - maxMatchLen + 1, startInc = 1;
ELSE
SET startPos = CHAR_LENGTH(subject) - minMatchLen + 1, startInc = -1;
END IF;
WHILE startPos >= 1 AND startPos <= CHAR_LENGTH(subject)
AND startPos + minMatchLen - 1 <= CHAR_LENGTH(subject)
AND !(LEFT(pattern, 1) = '^' AND startPos <> 1)
AND !(RIGHT(pattern, 1) = '$'
AND startPos + maxMatchLen - 1 < CHAR_LENGTH(subject)) DO
-- Set start length to maximum if matching greedily or pattern ends with $.
-- Otherwise set starting length to the minimum match length.
IF greedy OR RIGHT(pattern, 1) = '$' THEN
SET len = LEAST(CHAR_LENGTH(subject) - startPos + 1, maxMatchLen), lenInc = -1;
ELSE
SET len = minMatchLen, lenInc = 1;
END IF;
SET prevStartPos = startPos;
lenLoop: WHILE len >= 1 AND len <= maxMatchLen
AND startPos + len - 1 <= CHAR_LENGTH(subject)
AND !(RIGHT(pattern, 1) = '$'
AND startPos + len - 1 <> CHAR_LENGTH(subject)) DO
SET subStr = SUBSTRING(subject, startPos, len);
IF subStr REGEXP usePattern THEN
SET result = IF(startInc = 1,
CONCAT(result, replacement), CONCAT(replacement, result));
SET startPos = startPos + startInc * len;
LEAVE lenLoop;
END IF;
SET len = len + lenInc;
END WHILE;
IF (startPos = prevStartPos) THEN
SET result = IF(startInc = 1, CONCAT(result, SUBSTRING(subject, startPos, 1)),
CONCAT(SUBSTRING(subject, startPos, 1), result));
SET startPos = startPos + startInc;
END IF;
END WHILE;
IF startInc = 1 AND startPos <= CHAR_LENGTH(subject) THEN
SET result = CONCAT(result, RIGHT(subject, CHAR_LENGTH(subject) + 1 - startPos));
ELSEIF startInc = -1 AND startPos >= 1 THEN
SET result = CONCAT(LEFT(subject, startPos), result);
END IF;
ELSE
SET result = subject;
END IF;
RETURN result;
END;
DROP FUNCTION IF EXISTS format_result;
CREATE FUNCTION format_result(result VARCHAR(21845))
RETURNS VARCHAR(21845) DETERMINISTIC BEGIN
RETURN CONCAT(CONCAT('|', REPLACE(REPLACE(REPLACE(REPLACE(result, '\t', '\\t'), CHAR(12), '\\f'), '\r', '\\r'), '\n', '\\n')), '|');
END;
DROP TABLE IF EXISTS tbl;
CREATE TABLE tbl
AS
SELECT 'Afghanistan' AS txt
UNION ALL
SELECT ' AF' AS txt
UNION ALL
SELECT ' Cayman Islands ' AS txt
UNION ALL
SELECT CONCAT(CONCAT(CONCAT('\t \t ', CHAR(12)), ' \r\n\t British Virgin Islands \t \t ', CHAR(12)), ' \r\n') AS txt;
SELECT format_result(txt) AS txt,
format_result(TRIM(txt)) AS trim,
format_result(TRIM(BOTH '\r' FROM TRIM(BOTH '\n' FROM TRIM(BOTH '\f' FROM TRIM(BOTH '\t' FROM TRIM(txt))))))
AS `trim spaces, tabs, formfeeds and line endings`,
format_result(reg_replace(reg_replace(txt, '^[[:space:]]+', '', TRUE, 1, 0), '[[:space:]]+$', '', TRUE, 1, 0))
AS `reg_replace`
FROM tbl;
Usage:
SELECT reg_replace(
reg_replace(txt,
'^[[:space:]]+',
'',
TRUE,
1,
0),
'[[:space:]]+$',
'',
TRUE,
1,
0) AS `trimmed txt`
FROM tbl;
You could actually put the value = to the text and then do
$j(document).ready(function(){
$j("select#select_2").change(function(){
val = $j("#select_2 option:selected").html();
alert(val);
});
});
Or what I did on a similar case was
<select name="options[2]" id="select_2" onChange="JavascriptMethod()">
with you're options here
</select>
With this second option you should have a undefined. Give me feedback if it worked :)
Patrick
You want something more like this:
SELECT TableA.*, TableB.*, TableC.*, TableD.*
FROM TableA
JOIN TableB
ON TableB.aID = TableA.aID
JOIN TableC
ON TableC.cID = TableB.cID
JOIN TableD
ON TableD.dID = TableA.dID
WHERE DATE(TableC.date)=date(now())
In your example, you are not actually including TableD
. All you have to do is perform another join just like you have done before.
A note: you will notice that I removed many of your parentheses, as they really are not necessary in most of the cases you had them, and only add confusion when trying to read the code. Proper nesting is the best way to make your code readable and separated out.
I know this doesn't use flexbox, but for the simple use-case of three items (one at left, one at center, one at right), this can be accomplished easily using display: grid
on the parent, grid-area: 1/1/1/1;
on the children, and justify-self
for positioning of those children.
<div style="border: 1px solid red; display: grid; width: 100px; height: 25px;">_x000D_
<div style="border: 1px solid blue; width: 25px; grid-area: 1/1/1/1; justify-self: left;"></div>_x000D_
<div style="border: 1px solid blue; width: 25px; grid-area: 1/1/1/1; justify-self: center;"></div>_x000D_
<div style="border: 1px solid blue; width: 25px; grid-area: 1/1/1/1; justify-self: right;"></div>_x000D_
</div>
_x000D_
This is copied from above, but condensed slightly and re-written in semantic terms. Note: #Container
has display: flex;
and flex-direction: column;
, while the columns have flex: 3;
and flex: 2;
(where "One value, unitless number" determines the flex-grow
property) per MDN flex
docs.
#Container {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
height: 600px;_x000D_
width: 580px;_x000D_
}_x000D_
_x000D_
.Content {_x000D_
display: flex;_x000D_
flex: 1;_x000D_
}_x000D_
_x000D_
#Detail {_x000D_
flex: 3;_x000D_
background-color: lime;_x000D_
}_x000D_
_x000D_
#ThumbnailContainer {_x000D_
flex: 2;_x000D_
background-color: black;_x000D_
}
_x000D_
<div id="Container">_x000D_
<div class="Content">_x000D_
<div id="Detail"></div>_x000D_
<div id="ThumbnailContainer"></div>_x000D_
</div>_x000D_
</div>
_x000D_
If you want to pass the form to the controller for validation purposes you can simply pass it as an argument to the method handling the submission. Use the form name, so for the original question it would be something like:
<button ng-click="submit(customerForm)">Save</button>
I developed a jQuery plugin that allows you to call any core PHP function or even user defined PHP functions as methods of the plugin: jquery.php
After including jquery and jquery.php in the head of our document and placing request_handler.php on our server we would start using the plugin in the manner described below.
For ease of use reference the function in a simple manner:
var P = $.fn.php;
Then initialize the plugin:
P('init',
{
// The path to our function request handler is absolutely required
'path': 'http://www.YourDomain.com/jqueryphp/request_handler.php',
// Synchronous requests are required for method chaining functionality
'async': false,
// List any user defined functions in the manner prescribed here
// There must be user defined functions with these same names in your PHP
'userFunctions': {
languageFunctions: 'someFunc1 someFunc2'
}
});
And now some usage scenarios:
// Suspend callback mode so we don't work with the DOM
P.callback(false);
// Both .end() and .data return data to variables
var strLenA = P.strlen('some string').end();
var strLenB = P.strlen('another string').end();
var totalStrLen = strLenA + strLenB;
console.log( totalStrLen ); // 25
// .data Returns data in an array
var data1 = P.crypt("Some Crypt String").data();
console.log( data1 ); // ["$1$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"]
Demonstrating PHP function chaining:
var data1 = P.strtoupper("u,p,p,e,r,c,a,s,e").strstr([], "C,A,S,E").explode(",", [], 2).data();
var data2 = P.strtoupper("u,p,p,e,r,c,a,s,e").strstr([], "C,A,S,E").explode(",", [], 2).end();
console.log( data1, data2 );
Demonstrating sending a JSON block of PHP pseudo-code:
var data1 =
P.block({
$str: "Let's use PHP's file_get_contents()!",
$opts:
[
{
http: {
method: "GET",
header: "Accept-language: en\r\n" +
"Cookie: foo=bar\r\n"
}
}
],
$context:
{
stream_context_create: ['$opts']
},
$contents:
{
file_get_contents: ['http://www.github.com/', false, '$context']
},
$html:
{
htmlentities: ['$contents']
}
}).data();
console.log( data1 );
The backend configuration provides a whitelist so you can restrict which functions can be called. There are a few other patterns for working with PHP described by the plugin as well.
C:\Program Files (x86)\LG Electronics\LG PC Suite\adb>adb install com.lge.filemanager-15052-v3.1.15052.apk
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
2683 KB/s (3159508 bytes in 1.150s)
pkg: /data/local/tmp/com.lge.filemanager-15052-v3.1.15052.apk
Success
C:\Program Files (x86)\LG Electronics\LG PC Suite\adb>
We can use the adb.exe which is there in PC suit, it worked for me. Thanks Chethan
Try defaulting the exports in your components:
import React from 'react';
import Navbar from 'react-bootstrap/lib/Navbar';
export default class MyNavbar extends React.Component {
render(){
return (
<Navbar className="navbar-dark" fluid>
...
</Navbar>
);
}
}
by using default you express that's going to be member in that module which would be imported if no specific member name is provided. You could also express you want to import the specific member called MyNavbar by doing so: import {MyNavbar} from './comp/my-navbar.jsx'; in this case, no default is needed
Slightly modified Yannith version. It is just I like to have it as a return value
typedef struct {_x000D_
size_t len;_x000D_
uint8_t *bytes;_x000D_
} vdata;_x000D_
_x000D_
char* vdata_get_hex(const vdata data)_x000D_
{_x000D_
char hex_str[]= "0123456789abcdef";_x000D_
_x000D_
char* out;_x000D_
out = (char *)malloc(data.len * 2 + 1);_x000D_
(out)[data.len * 2] = 0;_x000D_
_x000D_
if (!data.len) return NULL;_x000D_
_x000D_
for (size_t i = 0; i < data.len; i++) {_x000D_
(out)[i * 2 + 0] = hex_str[(data.bytes[i] >> 4) & 0x0F];_x000D_
(out)[i * 2 + 1] = hex_str[(data.bytes[i] ) & 0x0F];_x000D_
}_x000D_
return out;_x000D_
}
_x000D_
Just hold cursor over member you interested in, and see tooltip - it will show memeber's type:
MVW stands for Model-View-Whatever.
For completeness, here are all the acronyms mentioned:
MVC - Model-View-Controller
MVP - Model-View-Presenter
MVVM - Model-View-ViewModel
MVW / MV* / MVx - Model-View-Whatever
And some more:
HMVC - Hierarchical Model-View-Controller
MMV - Multiuse Model View
MVA - Model-View-Adapter
MVI - Model-View-Intent
After=
dependency is only effective when service including After=
and service included by After=
are both scheduled to start as part of your boot up.
Ex:
a.service
[Unit]
After=b.service
This way, if both a.service
and b.service
are enabled, then systemd will order b.service
after a.service
.
If I am not misunderstanding, what you are asking is how to start b.service
when a.service
starts even though b.service
is not enabled.
The directive for this is Wants=
or Requires=
under [Unit]
.
website.service
[Unit]
Wants=mongodb.service
After=mongodb.service
The difference between Wants=
and Requires=
is that with Requires=
, a failure to start b.service
will cause the startup of a.service
to fail, whereas with Wants=
, a.service
will start even if b.service
fails. This is explained in detail on the man page of .unit
.
Your css is fine, but I think it's not applying on divs. Just write simple class name and then try. You can check it at Jsfiddle.
.left {
float: left;
width: 125px;
text-align: right;
margin: 2px 10px;
display: inline;
}
.right {
float: left;
text-align: left;
margin: 2px 10px;
display: inline;
}
try
{
..
..
..
}
catch(Exception ex)
{
..
..
..
}
the Exception ex means all the exceptions.
Stephen Darlington makes a very good point, and you can see that if you change my benchmark to use a more realistically sized table if I fill the table out to 10000 rows using the following:
begin
for i in 2 .. 10000 loop
insert into t (NEEDED_FIELD, cond) values (i, 10);
end loop;
end;
Then re-run the benchmarks. (I had to reduce the loop counts to 5000 to get reasonable times).
declare
otherVar number;
cnt number;
begin
for i in 1 .. 5000 loop
select count(*) into cnt from t where cond = 0;
if (cnt = 1) then
select NEEDED_FIELD INTO otherVar from t where cond = 0;
else
otherVar := 0;
end if;
end loop;
end;
/
PL/SQL procedure successfully completed.
Elapsed: 00:00:04.34
declare
otherVar number;
begin
for i in 1 .. 5000 loop
begin
select NEEDED_FIELD INTO otherVar from t where cond = 0;
exception
when no_data_found then
otherVar := 0;
end;
end loop;
end;
/
PL/SQL procedure successfully completed.
Elapsed: 00:00:02.10
The method with the exception is now more than twice as fast. So, for almost all cases,the method:
SELECT NEEDED_FIELD INTO var WHERE condition;
EXCEPTION
WHEN NO_DATA_FOUND....
is the way to go. It will give correct results and is generally the fastest.
Try string.Remove();
string str = "1,5,12,34,";
string removecomma = str.Remove(str.Length-1);
MessageBox.Show(removecomma);
DONE.
Example whatever.h
#ifndef WHATEVER_H_INCLUDED
#define WHATEVER_H_INCLUDED
int f(int a);
#endif
Note: include guards (preprocessor commands) added thanks to luke. They avoid including the same header file twice in the same compilation. Another possibility (also mentioned on the comments) is to add #pragma once
but it is not guaranteed to be supported on every compiler.
Example whatever.c
#include "whatever.h"
int f(int a) { return a + 1; }
And then you can include "whatever.h" into any other .c file, and link it with whatever.c's object file.
Like this:
sample.c
#include "whatever.h"
int main(int argc, char **argv)
{
printf("%d\n", f(2)); /* prints 3 */
return 0;
}
To compile it (if you use GCC):
$ gcc -c whatever.c -o whatever.o
$ gcc -c sample.c -o sample.o
To link the files to create an executable file:
$ gcc sample.o whatever.o -o sample
You can test sample:
$ ./sample
3
$
A very simple way to do it is:
list1=['']
j=0
for i in com_list:
if j==0:
list1[0]=(i['value'])
else:
list1.append(i['value'])
j+=1
Output:
['apple', 'banana', 'cars']
Following Rory McCrossan answer, if you want to send an array of integer (almost for .NET), this is the code:
// ...
url: "MyUrl", // For example --> @Url.Action("Method", "Controller")
method: "post",
traditional: true,
data:
$('#myForm').serialize() +
"¶m1="xxx" +
"¶m2="33" +
"&" + $.param({ paramArray: ["1","2","3"]}, true)
,
// ...
Go to Settings => Plugins => Search Plugins in Marketplace
Search by material theme
and download and restart it. it is a good theme.
In the market place, you can also search by theme
and it will list all the themes and you can download any themes. You no need to find themes and download and import it. You can also remove the theme very easily. thanks
If you look for POSIX compliant solution:
cd DirsRoot && find . -type f -print -o -name . -o -prune
-maxdepth is not POSIX compliant option.
I use a generic query I call "dump" (why? I don't know) that looks like this:
SET NEWPAGE NONE
SET PAGESIZE 0
SET SPACE 0
SET LINESIZE 16000
SET ECHO OFF
SET FEEDBACK OFF
SET VERIFY OFF
SET HEADING OFF
SET TERMOUT OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET COLSEP |
spool &1..txt
@@&1
spool off
exit
I then call SQL*Plus passing the actual SQL script I want to run as an argument:
sqlplus -S user/password@database @dump.sql my_real_query.sql
The result is written to a file
my_real_query.sql.txt
.
Do just simple thing:
You can do it this simple way :
A1 = Mahi
A2 = NULL(blank)
Select A2 Right click on cell --> Format cells --> change to TEXT
Then put the date in A2 (A2 =31/07/1990)
Then concatenate it will work. No need of any formulae.
=CONCATENATE(A1,A2)
mahi31/07/1990
(This works on the empty cells ie.,Before entering the DATE value to cell you need to make it as TEXT).
Here is my 'simple' helper class which returns an ImageView with the border. Just drop this in your utils folder, and call it like this:
ImageView selectionBorder = BorderDrawer.generateBorderImageView(context, borderWidth, borderHeight, thickness, Color.Blue);
Here is the code.
/**
* Because creating a border is Rocket Science in Android.
*/
public class BorderDrawer
{
public static ImageView generateBorderImageView(Context context, int borderWidth, int borderHeight, int borderThickness, int color)
{
ImageView mask = new ImageView(context);
// Create the square to serve as the mask
Bitmap squareMask = Bitmap.createBitmap(borderWidth - (borderThickness*2), borderHeight - (borderThickness*2), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(squareMask);
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(color);
canvas.drawRect(0.0f, 0.0f, (float)borderWidth, (float)borderHeight, paint);
// Create the darkness bitmap
Bitmap solidColor = Bitmap.createBitmap(borderWidth, borderHeight, Bitmap.Config.ARGB_8888);
canvas = new Canvas(solidColor);
paint.setStyle(Paint.Style.FILL);
paint.setColor(color);
canvas.drawRect(0.0f, 0.0f, borderWidth, borderHeight, paint);
// Create the masked version of the darknessView
Bitmap borderBitmap = Bitmap.createBitmap(borderWidth, borderHeight, Bitmap.Config.ARGB_8888);
canvas = new Canvas(borderBitmap);
Paint clearPaint = new Paint();
clearPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
canvas.drawBitmap(solidColor, 0, 0, null);
canvas.drawBitmap(squareMask, borderThickness, borderThickness, clearPaint);
clearPaint.setXfermode(null);
ImageView borderView = new ImageView(context);
borderView.setImageBitmap(borderBitmap);
return borderView;
}
}
For the special case where you search for the n'th occurence of a character (i.e. substring of length 1), the following function works by building a list of all positions of occurences of the given character:
def find_char_nth(string, char, n):
"""Find the n'th occurence of a character within a string."""
return [i for i, c in enumerate(string) if c == char][n-1]
If there are fewer than n
occurences of the given character, it will give IndexError: list index out of range
.
This is derived from @Zv_oDD's answer and simplified for the case of a single character.
Why not use padding with negative margins? Something like this:
<div class="parent">
<div class="child1">
</div>
<div class="child2">
</div>
</div>
And then
.parent {
padding-top: 1em;
}
.child1 {
margin-top: -1em;
height: 1em;
}
.child2 {
margin-top: 0;
height: 100%;
}