If you like to give a special kind of experience to the users you could use pushState
to bring a wide range of characters to the browser's url:
var u="";var tt=168;
for(var i=0; i< 250;i++){
var x = i+250*tt;
console.log(x);
var c = String.fromCharCode(x);
u+=c;
}
history.pushState({},"",250*tt+u);
On Windows 2008 R2 servers you have two means of viewing what files are open and closing those connections.
Via Share and Storage Management
Server Manager > Roles > File Services > Share and Storage Management > right-click on SaSM > Manage Open File
Via OpenFiles
CMD > Openfiles.exe /query /s SERVERNAME
See http://technet.microsoft.com/en-us/library/bb490961.aspx.
The terminal uses environment variables to determine which character set to use, therefore you can determine it by looking at those variables:
echo $LC_CTYPE
or
echo $LANG
Note that you can use the Polynomial class directly to do the fitting and return a Polynomial instance.
from numpy.polynomial import Polynomial
p = Polynomial.fit(x, y, 4)
plt.plot(*p.linspace())
p
uses scaled and shifted x values for numerical stability. If you need the usual form of the coefficients, you will need to follow with
pnormal = p.convert(domain=(-1, 1))
Found this by searching for "linux output formatted columns".
http://www.unix.com/shell-programming-scripting/117543-formatting-output-columns.html
For your needs, it's like:
awk '{ printf "%-20s %-40s\n", $1, $2}'
conda init
As pointed out in a different answer, manually adding Conda on $PATH
is no longer recommended as of v4.4.0 (see Release Notes). Furthermore, since Conda v4.6 new functionality to manage shell initialization via the conda init
command was introduced. Hence, the updated recommendation is to run
Linux/UNIX (OS X < 10.15)
./anaconda3/bin/conda init
Mac OS X >= 10.15
./anaconda3/bin/conda init zsh
Windows
./anaconda3/Scripts/conda.exe init
You must launch a new shell or source your init file (e.g., source .bashrc
) for the changes to take effect.
You may need to explicitly identify your shell to Conda. For example, if you run zsh
(Mac OS X 10.15+ default) instead of bash
then you would run
./anaconda3/bin/conda init zsh
Please see ./anaconda3/bin/conda init --help
for a comprehensive list of supported shells.
I'd recommend running the above command with a --dry-run|-d
flag and a verbosity (-vv
) flag, in order to see exactly what it would do. If you don't already have a Conda-managed section in your shell run commands file (e.g., .bashrc
), then this should appear like a straight-forward insertion of some new lines. If it isn't such a straightforward insertion, I'd recommend clearing any previous Conda sections from $PATH
and the relevant shell initialization files (e.g., bashrc
) first.
Conda v4.6.9 introduced a --reverse
flag that automates removing the changes that are inserted by conda init
.
A more-advanced example:
? unlimited arguments.
? exist on file system (either
file
ordirectory
?) or a genericstring
.? specify if is a file
? specify is a directory
? no extensions, would work in legacy scripts!
? minimal code ?
@echo off :loop ::-------------------------- has argument ? if ["%~1"]==[""] ( echo done. goto end ) ::-------------------------- argument exist ? if not exist %~s1 ( echo not exist ) else ( echo exist if exist %~s1\NUL ( echo is a directory ) else ( echo is a file ) ) ::-------------------------- shift goto loop :end pause
? other stuff..?
¦ in %~1
- the ~
removes any wrapping "
or '
.
¦ in %~s1
- the s
makes the path be DOS 8.3 naming
, which is a nice trick to avoid spaces in file-name while checking stuff (and this way no need to wrap the resource with more "
s.
¦ the ["%~1"]==[""]
"can not be sure" if the argument is a file/directory or just a generic string yet, so instead the expression uses brackets and the original unmodified %1
(just without the "
wrapping, if any..)
if there were no arguments of if we've used shift
and the arg-list pointer has passed the last one, the expression will be evaluated to [""]==[""]
.
¦ this is as much specific you can be without using more tricks (it would work even in windows-95's batch-scripts...)
save it as identifier.cmd
it can identify an unlimited arguments (normally you are limited to %1
-%9
), just remember to wrap the arguments with inverted-commas, or use 8.3 naming, or drag&drop them over (it automatically does either of above).
this allows you to run the following commands:
?identifier.cmd c:\windows
and to get
exist is a directory done
?identifier.cmd "c:\Program Files (x86)\Microsoft Office\OFFICE11\WINWORD.EXE"
and to get
exist is a file done
? and multiple arguments (of course this is the whole-deal..)
identifier.cmd c:\windows\system32 c:\hiberfil.sys "c:\pagefile.sys" hello-world
and to get
exist is a directory exist is a file exist is a file not exist done.
naturally it can be a lot more complex, but nice examples should always be simple and minimal. :)
published here:CMD Ninja - Unlimited Arguments Processing, Identifying If Exist In File-System, Identifying If File Or Directory
and here is a working example that takes any amount of APK files (Android apps) and installs them on your device via debug-console (ADB.exe): Make The Previous Post A Mass APK Installer That Does Not Uses ADB Install-Multi Syntax
change svg
to match your element
function svg2img(){
var svg = document.querySelector('svg');
var xml = new XMLSerializer().serializeToString(svg);
var svg64 = btoa(xml); //for utf8: btoa(unescape(encodeURIComponent(xml)))
var b64start = 'data:image/svg+xml;base64,';
var image64 = b64start + svg64;
return image64;
};svg2img()
Set the following CSS properties to the image:
user-drag: none;
user-select: none;
-moz-user-select: none;
-webkit-user-drag: none;
-webkit-user-select: none;
-ms-user-select: none;
For Some reason it is not working so we can do this by another way
just remove the line and add this :-
<a onclick="window.open ('http://www.foracure.org.au', ''); return false" href="javascript:void(0);"></a>
Good luck.
From the Android Studio download page:
Caution: Android Studio is currently available as an early access preview. Several features are either incomplete or not yet implemented and you may encounter bugs. If you are not comfortable using an unfinished product, you may want to instead download (or continue to use) the ADT Bundle (Eclipse with the ADT Plugin).
You need to use an explicit java.util.Iterator
to iterate over the Map
's entry set rather than being able to use the enhanced For-loop syntax available in Java 6. The following example iterates over a Map
of Integer
, String
pairs, removing any entry whose Integer
key is null or equals 0.
Map<Integer, String> map = ...
Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, String> entry = it.next();
// Remove entry if key is null or equals 0.
if (entry.getKey() == null || entry.getKey() == 0) {
it.remove();
}
}
The problem is with percentage sizing. You are not defining the size of the parent div (the new one), so the browser can not report the size to the Google Maps API. Giving the wrapper div a specific size, or a percentage size if the size of its parent can be determined, will work.
See this explanation from Mike Williams' Google Maps API v2 tutorial:
If you try to use style="width:100%;height:100%" on your map div, you get a map div that has zero height. That's because the div tries to be a percentage of the size of the
<body>
, but by default the<body>
has an indeterminate height.There are ways to determine the height of the screen and use that number of pixels as the height of the map div, but a simple alternative is to change the
<body>
so that its height is 100% of the page. We can do this by applying style="height:100%" to both the<body>
and the<html>
. (We have to do it to both, otherwise the<body>
tries to be 100% of the height of the document, and the default for that is an indeterminate height.)
Add the 100% size to html and body in your css
html, body, #map-canvas {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
}
Add it inline to any divs that don't have an id:
<body>
<div style="height:100%; width: 100%;">
<div id="map-canvas"></div>
</div>
</body>
My solution using File Provider
private void viewGallery(File file) {
Uri mImageCaptureUri = FileProvider.getUriForFile(
mContext,
mContext.getApplicationContext()
.getPackageName() + ".provider", file);
Intent view = new Intent();
view.setAction(Intent.ACTION_VIEW);
view.setData(mImageCaptureUri);
List < ResolveInfo > resInfoList =
mContext.getPackageManager()
.queryIntentActivities(view, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo: resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
mContext.grantUriPermission(packageName, mImageCaptureUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
view.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(mImageCaptureUri, "image/*");
mContext.startActivity(intent);
}
Shorter version of:
REGEXP_REPLACE( my_value, '[[:space:]]', '' )
Would be:
REGEXP_REPLACE( my_value, '\s')
Neither of the above statements will remove "null" characters.
To remove "nulls" encase the statement with a replace
Like so:
REPLACE(REGEXP_REPLACE( my_value, '\s'), CHR(0))
For all those of you that try to remove the separating line of the tabWidget, here is an example project (and its respective tutorial), that work great for customizing the tabs and thus removing problems when tabs are at bottom. Eclipse Project: android-custom-tabs ; Original explanation: blog; Hope this helped.
You could always make a unique index, which causes MongoDB to reject a conflicting save. Consider the following done using the mongodb shell:
> db.getCollection("test").insert ({a:1, b:2, c:3})
> db.getCollection("test").find()
{ "_id" : ObjectId("50c8e35adde18a44f284e7ac"), "a" : 1, "b" : 2, "c" : 3 }
> db.getCollection("test").ensureIndex ({"a" : 1}, {unique: true})
> db.getCollection("test").insert({a:2, b:12, c:13}) # This works
> db.getCollection("test").insert({a:1, b:12, c:13}) # This fails
E11000 duplicate key error index: foo.test.$a_1 dup key: { : 1.0 }
Pretty sad, eh? The way I usually do it is build up a container of iterators instead of deleting during traversal. Then loop through the container and use map.erase()
std::map<K,V> map;
std::list< std::map<K,V>::iterator > iteratorList;
for(auto i : map ){
if ( needs_removing(i)){
iteratorList.push_back(i);
}
}
for(auto i : iteratorList){
map.erase(*i)
}
Another variation:
git branch -r --sort=-committerdate --format='%(HEAD)%(color:yellow)%(refname:short)|%(color:bold green)%(committerdate:relative)|%(color:blue)%(subject)|%(color:magenta)%(authorname)%(color:reset)' --color=always | column -ts'|'
Worth noting that even though it's looking at changes in remote branches, it's worth syncing with origin before running the command (can use git fetch), as I found it can return out of date information if your local Git folder hasn't been updated in a while.
Also, this is a version that works in Windows cmd and PowerShell (didn't get output displayed in columns, would be interested to see if anyone gets this working):
git branch -r --sort=-committerdate --format="%(HEAD)%(color:yellow)%(refname:short)|%(color:bold green)%(committerdate:relative)|%(color:blue)%(subject)|%(color:magenta)%(authorname)%(color:reset)" --color=always
CONCAT
is new to SQL Server 2012. The link you gave makes this clear, it is not a function on Previous Versions, including 2008 R2.
That it is part of SQL Server 2012 can be seen in the document tree:
SQL Server 2012
Product Documentation
Books Online for SQL Server 2012
Database Engine
Transact-SQL Reference (Database Engine)
Built-in Functions (Transact-SQL)
String Functions (Transact-SQL)
EDIT Martin Smith helpfully points out that SQL Server provides an implementation of ODBC's CONCAT
function.
All answers are based on anonymous inner class. We have one more way for adding click event for buttons as well as other components too.
An activity needs to implement View.OnClickListener interface and we need to override the onClick function. I think this is best approach compared to using anonymous class.
package com.pointerunits.helloworld;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
private Button login;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
login = (Button)findViewById(R.id.loginbutton);
login.setOnClickListener((OnClickListener) this);
Log.i(DISPLAY_SERVICE, "Activity is created");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View v) {
Log.i(DISPLAY_SERVICE, "Button clicked : " + v.getId());
}
}
We use it with custom memory pools. Just a sketch:
class Pool {
public:
Pool() { /* implementation details irrelevant */ };
virtual ~Pool() { /* ditto */ };
virtual void *allocate(size_t);
virtual void deallocate(void *);
static Pool::misc_pool() { return misc_pool_p; /* global MiscPool for general use */ }
};
class ClusterPool : public Pool { /* ... */ };
class FastPool : public Pool { /* ... */ };
class MapPool : public Pool { /* ... */ };
class MiscPool : public Pool { /* ... */ };
// elsewhere...
void *pnew_new(size_t size)
{
return Pool::misc_pool()->allocate(size);
}
void *pnew_new(size_t size, Pool *pool_p)
{
if (!pool_p) {
return Pool::misc_pool()->allocate(size);
}
else {
return pool_p->allocate(size);
}
}
void pnew_delete(void *p)
{
Pool *hp = Pool::find_pool(p);
// note: if p == 0, then Pool::find_pool(p) will return 0.
if (hp) {
hp->deallocate(p);
}
}
// elsewhere...
class Obj {
public:
// misc ctors, dtors, etc.
// just a sampling of new/del operators
void *operator new(size_t s) { return pnew_new(s); }
void *operator new(size_t s, Pool *hp) { return pnew_new(s, hp); }
void operator delete(void *dp) { pnew_delete(dp); }
void operator delete(void *dp, Pool*) { pnew_delete(dp); }
void *operator new[](size_t s) { return pnew_new(s); }
void *operator new[](size_t s, Pool* hp) { return pnew_new(s, hp); }
void operator delete[](void *dp) { pnew_delete(dp); }
void operator delete[](void *dp, Pool*) { pnew_delete(dp); }
};
// elsewhere...
ClusterPool *cp = new ClusterPool(arg1, arg2, ...);
Obj *new_obj = new (cp) Obj(arg_a, arg_b, ...);
Now you can cluster objects together in a single memory arena, select an allocator which is very fast but does no deallocation, use memory mapping, and any other semantic you wish to impose by choosing the pool and passing it as an argument to an object's placement new operator.
The follows is often used:
select field_SQ.nextval from dual;
select field_SQ.currval from DUAL;
However the following is able to change the sequence to what you expected. The 1
can be an integer (negative or positive)
alter sequence field_SQ increment by 1 minvalue 0
An IDE is an integrated development environment - a suped-up text editor with additional support for developing (such as forms designers, resource editors, etc), compiling and debugging applications. e.g Eclipse, Visual Studio.
A Library is a chunk of code that you can call from your own code, to help you do things more quickly/easily. For example, a Bitmap Processing library will provide facilities for loading and manipulating bitmap images, saving you having to write all that code for yourself. Typically a library will only offer one area of functionality (processing images or operating on zip files)
An API (application programming interface) is a term meaning the functions/methods in a library that you can call to ask it to do things for you - the interface to the library.
An SDK (software development kit) is a library or group of libraries (often with extra tool applications, data files and sample code) that aid you in developing code that uses a particular system (e.g. extension code for using features of an operating system (Windows SDK), drawing 3D graphics via a particular system (DirectX SDK), writing add-ins to extend other applications (Office SDK), or writing code to make a device like an Arduino or a mobile phone do what you want). An SDK will still usually have a single focus.
A toolkit is like an SDK - it's a group of tools (and often code libraries) that you can use to make it easier to access a device or system... Though perhaps with more focus on providing tools and applications than on just code libraries.
A framework is a big library or group of libraries that provides many services (rather than perhaps only one focussed ability as most libraries/SDKs do). For example, .NET provides an application framework - it makes it easier to use most (if not all) of the disparate services you need (e.g. Windows, graphics, printing, communications, etc) to write a vast range of applications - so one "library" provides support for pretty much everything you need to do. Often a framework supplies a complete base on which you build your own code, rather than you building an application that consumes library code to do parts of its work.
There are of course many examples in the wild that won't exactly match these descriptions though.
The name attribute allows you to refer to an element by its name (like id) through a list of children, so fast way is:
document.head.children.namedItem('description').content = '...'
The options above where not possible for me to include. I solved it by specifying the Runpath Search Path
This is on the 'Build Settings' tab.
In the 'Linking' section.
Change 'Runpath Search Paths' into $(inherited) @executable_path/Frameworks
You can always write it like this
String[] errorSoon = {"Hello","World"};
For (int x=0;x<errorSoon.length;x++) // in this way u create a for loop that would like display the elements which are inside the array errorSoon.oh errorSoon.length is the same as errorSoon<2
{
System.out.println(" "+errorSoon[x]); // this will output those two words, at the top hello and world at the bottom of hello.
}
The simple answer is to change
div.rounded div div div {
padding: 10px;
}
to
div.rounded div div div {
background-image: none;
padding: 10px;
}
The reason is because when you make a rule for div.rounded div div
it means every div
element nested inside a div
inside a div
with a class of rounded
, regardless of nesting.
If you want to only target a div that's the direct descendent, you can use the syntax div.rounded div > div
(though this is only supported by more recent browsers).
Incidentally, you can usually simplify this method to use only two div
s (one each for either top and bottom or left and right), by using a technique called Sliding Doors.
I faced the same issue. In my case, part of my variables were in a dictionary i.e. with_dict variable (looping) and I had to run 3 commands on each item.key. This solution is more relevant where you have to use with_dict dictionary with running multiple commands (without requiring with_items)
Using with_dict and with_items in one task didn't help as it was not resolving the variables.
My task was like:
- name: Make install git source
command: "{{ item }}"
with_items:
- cd {{ tools_dir }}/{{ item.value.artifact_dir }}
- make prefix={{ tools_dir }}/{{ item.value.artifact_dir }} all
- make prefix={{ tools_dir }}/{{ item.value.artifact_dir }} install
with_dict: "{{ git_versions }}"
roles/git/defaults/main.yml was:
---
tool: git
default_git: git_2_6_3
git_versions:
git_2_6_3:
git_tar_name: git-2.6.3.tar.gz
git_tar_dir: git-2.6.3
git_tar_url: https://www.kernel.org/pub/software/scm/git/git-2.6.3.tar.gz
The above resulted in an error similar to the following for each {{ item }} (for 3 commands as mentioned above). As you see, the values of tools_dir is not populated (tools_dir is a variable which is defined in a common role's defaults/main.yml and also item.value.git_tar_dir value was not populated/resolved).
failed: [server01.poc.jenkins] => (item=cd {# tools_dir #}/{# item.value.git_tar_dir #}) => {"cmd": "cd '{#' tools_dir '#}/{#' item.value.git_tar_dir '#}'", "failed": true, "item": "cd {# tools_dir #}/{# item.value.git_tar_dir #}", "rc": 2}
msg: [Errno 2] No such file or directory
Solution was easy. Instead of using "COMMAND" module in Ansible, I used "Shell" module and created a a variable in roles/git/defaults/main.yml
So, now roles/git/defaults/main.yml looks like:
---
tool: git
default_git: git_2_6_3
git_versions:
git_2_6_3:
git_tar_name: git-2.6.3.tar.gz
git_tar_dir: git-2.6.3
git_tar_url: https://www.kernel.org/pub/software/scm/git/git-2.6.3.tar.gz
#git_pre_requisites_install_cmds: "cd {{ tools_dir }}/{{ item.value.git_tar_dir }} && make prefix={{ tools_dir }}/{{ item.value.git_tar_dir }} all && make prefix={{ tools_dir }}/{{ item.value.git_tar_dir }} install"
#or use this if you want git installation to work in ~/tools/git-x.x.x
git_pre_requisites_install_cmds: "cd {{ tools_dir }}/{{ item.value.git_tar_dir }} && make prefix=`pwd` all && make prefix=`pwd` install"
#or use this if you want git installation to use the default prefix during make
#git_pre_requisites_install_cmds: "cd {{ tools_dir }}/{{ item.value.git_tar_dir }} && make all && make install"
and the task roles/git/tasks/main.yml looks like:
- name: Make install from git source
shell: "{{ git_pre_requisites_install_cmds }}"
become_user: "{{ build_user }}"
with_dict: "{{ git_versions }}"
tags:
- koba
This time, the values got successfully substituted as the module was "SHELL" and ansible output echoed the correct values. This didn't require with_items: loop.
"cmd": "cd ~/tools/git-2.6.3 && make prefix=/home/giga/tools/git-2.6.3 all && make prefix=/home/giga/tools/git-2.6.3 install",
Above answer is partially correct for me, but In my scenario, I want to set the value to a state, because I have used the value to show/toggle a modal. So I have used like below. Hope it will help someone.
class Child extends React.Component {
state = {
visible:false
};
handleCancel = (e) => {
e.preventDefault();
this.setState({ visible: false });
};
componentDidMount() {
this.props.onRef(this)
}
componentWillUnmount() {
this.props.onRef(undefined)
}
method() {
this.setState({ visible: true });
}
render() {
return (<Modal title="My title?" visible={this.state.visible} onCancel={this.handleCancel}>
{"Content"}
</Modal>)
}
}
class Parent extends React.Component {
onClick = () => {
this.child.method() // do stuff
}
render() {
return (
<div>
<Child onRef={ref => (this.child = ref)} />
<button onClick={this.onClick}>Child.method()</button>
</div>
);
}
}
Reference - https://github.com/kriasoft/react-starter-kit/issues/909#issuecomment-252969542
exit
is a helper for the interactive shell - sys.exit
is intended for use in programs.
The
site
module (which is imported automatically during startup, except if the-S
command-line option is given) adds several constants to the built-in namespace (e.g.exit
). They are useful for the interactive interpreter shell and should not be used in programs.
Technically, they do mostly the same: raising SystemExit
. sys.exit
does so in sysmodule.c:
static PyObject *
sys_exit(PyObject *self, PyObject *args)
{
PyObject *exit_code = 0;
if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
return NULL;
/* Raise SystemExit so callers may catch it or clean up. */
PyErr_SetObject(PyExc_SystemExit, exit_code);
return NULL;
}
While exit
is defined in site.py and _sitebuiltins.py, respectively.
class Quitter(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return 'Use %s() or %s to exit' % (self.name, eof)
def __call__(self, code=None):
# Shells like IDLE catch the SystemExit, but listen when their
# stdin wrapper is closed.
try:
sys.stdin.close()
except:
pass
raise SystemExit(code)
__builtin__.quit = Quitter('quit')
__builtin__.exit = Quitter('exit')
Note that there is a third exit option, namely os._exit, which exits without calling cleanup handlers, flushing stdio buffers, etc. (and which should normally only be used in the child process after a fork()
).
Are you looking for this selector?:
.ui-menu .ui-menu-item a{
background:red;
height:10px;
font-size:8px;
}
Ugly demo:
Just replace with your code:
.ui-menu .ui-menu-item a{
color: #96f226;
border-radius: 0px;
border: 1px solid #454545;
}
It tells you that there is some unprocessed migration in your application and it requires running Update-Database
before you can add another migration.
print the state of a component with JSX
render() {
return (
<div>
<h1>Adopt Me!</h1>
<pre>
<code>{JSON.stringify(this.state, null, 4)}</code>
</pre>
</div>
);
}
@Ahamed has a point, but if you're insisting on using lists so you can have three arraylist like this:
ArrayList<Integer> first = new ArrayList<Integer>(Arrays.AsList(100,100,100,100,100));
ArrayList<Integer> second = new ArrayList<Integer>(Arrays.AsList(50,35,25,45,65));
ArrayList<Integer> third = new ArrayList<Integer>();
for(int i = 0; i < first.size(); i++) {
third.add(first.get(i));
third.add(second.get(i));
}
Edit: If you have those values on your list that below:
List<double[]> values = new ArrayList<double[]>(2);
what you want to do is combine them, right? You can try something like this: (I assume that both array are same sized, otherwise you need to use two for statement)
ArrayList<Double> yourArray = new ArrayList<Double>();
for(int i = 0; i < values.get(0).length; i++) {
yourArray.add(values.get(0)[i]);
yourArray.add(values.get(1)[i]);
}
2 things.
The query has to complete on sql server before the return value is sent.
The results have to be captured and then finish executing before the return value gets to the object.
In English, finish the work and then retrieve the value.
this will not work:
cmm.ExecuteReader();
int i = (int) cmm.Parameters["@RETURN_VALUE"].Value;
This will work:
SqlDataReader reader = cmm.ExecuteReader();
reader.Close();
foreach (SqlParameter prm in cmd.Parameters)
{
Debug.WriteLine("");
Debug.WriteLine("Name " + prm.ParameterName);
Debug.WriteLine("Type " + prm.SqlDbType.ToString());
Debug.WriteLine("Size " + prm.Size.ToString());
Debug.WriteLine("Direction " + prm.Direction.ToString());
Debug.WriteLine("Value " + prm.Value);
}
if you are not sure check the value of the parameter before during and after the results have been processed by the reader.
I agree that in most cases the if (!(x instanceof Y)) {...}
is the best approach, but in some cases creating an isY(x)
function so you can if (!isY(x)) {...}
is worthwhile.
I'm a typescript novice, and I've bumped into this S/O question a bunch of times over the last few weeks, so for the googlers the typescript way to do this is to create a typeguard like this:
typeGuards.ts
export function isHTMLInputElement (value: any): value is HTMLInputElement {
return value instanceof HTMLInputElement
}
usage
if (!isHTMLInputElement(x)) throw new RangeError()
// do something with an HTMLInputElement
I guess the only reason why this might be appropriate in typescript and not regular js is that typeguards are a common convention, so if you're writing them for other interfaces, it's reasonable / understandable / natural to write them for classes too.
There's more detail about user defined type guards like this in the docs
It is all explained by the javadoc for the constructor. It is a convenience constructor that populates the model with one attribute / value pair.
So ...
new ModelAndView(view, name, value);
is equivalent to:
Map model = ...
model.put(name, value);
new ModelAndView(view, model);
If you want to automatically/periodically clean up exited containers and remove images and volumes that aren't in use by a running container you can download the Docker image meltwater/docker-cleanup
.
That way you don't need to go clean it up by hand.
Just run:
docker run -d -v /var/run/docker.sock:/var/run/docker.sock:rw -v /var/lib/docker:/var/lib/docker:rw --restart=unless-stopped meltwater/docker-cleanup:latest
It will run every 30 minutes (or however long you set it using DELAY_TIME=1800 option) and clean up exited containers and images.
More details: https://github.com/meltwater/docker-cleanup/blob/master/README.md
Typically, no.
Streaming is seldom used over HTTP itself, and HTTP is seldom run over UDP. See, however, RTP.
For something as your example (in the comment), you're not showing a protocol for the resource. If that protocol were to be HTTP, then I wouldn't call the access "streaming"; even if it in some sense of the word is since it's sending a (possibly large) resource serially over a network. Typically, the resource will be saved to local disk before being played back, so the network transfer is not what's usually meant by "streaming".
As commenters have pointed out, though, it's certainly possible to really stream over HTTP, and that's done by some.
The "up" affordance indicator is provided by a drawable specified in the homeAsUpIndicator
attribute of the theme. To override it with your own custom version it would be something like this:
<style name="Theme.MyFancyTheme" parent="android:Theme.Holo">
<item name="android:homeAsUpIndicator">@drawable/my_fancy_up_indicator</item>
</style>
If you are supporting pre-3.0 with your application be sure you put this version of the custom theme in values-v11
or similar.
Ups, I entirely forgot this question. In the meantime I got a solution.
This Powershell script converts a CSV to XLSX in the background
=B1+B2
or 0000001
.#Name
or anything like that. No autoformating is done.### Set input and output path
$inputCSV = "C:\somefolder\input.csv"
$outputXLSX = "C:\somefolder\output.xlsx"
### Create a new Excel Workbook with one empty sheet
$excel = New-Object -ComObject excel.application
$workbook = $excel.Workbooks.Add(1)
$worksheet = $workbook.worksheets.Item(1)
### Build the QueryTables.Add command
### QueryTables does the same as when clicking "Data » From Text" in Excel
$TxtConnector = ("TEXT;" + $inputCSV)
$Connector = $worksheet.QueryTables.add($TxtConnector,$worksheet.Range("A1"))
$query = $worksheet.QueryTables.item($Connector.name)
### Set the delimiter (, or ;) according to your regional settings
$query.TextFileOtherDelimiter = $Excel.Application.International(5)
### Set the format to delimited and text for every column
### A trick to create an array of 2s is used with the preceding comma
$query.TextFileParseType = 1
$query.TextFileColumnDataTypes = ,2 * $worksheet.Cells.Columns.Count
$query.AdjustColumnWidth = 1
### Execute & delete the import query
$query.Refresh()
$query.Delete()
### Save & close the Workbook as XLSX. Change the output extension for Excel 2003
$Workbook.SaveAs($outputXLSX,51)
$excel.Quit()
try this formula in column E:
=IF( AND( ISNUMBER(D2), D2=G2), H2, "")
your error is the number test, ISNUMBER( ISMATCH(D2,G:G,0) )
you do check if ismatch is-a-number, (i.e. isNumber("true") or isNumber("false"), which is not!.
I hope you understand my explanation.
Use the variables "$1"
, "$2"
, "$3"
and so on to access arguments. To access all of them you can use "$@"
, or to get the count of arguments $#
(might be useful to check for too few or too many arguments).
If you would like to support really old browsers you should parse the date string, since using the ISO8601 date format with the Date
constructor is not supported pre IE9:
var queryDate = '2009-11-01',
dateParts = queryDate.match(/(\d+)/g)
realDate = new Date(dateParts[0], dateParts[1] - 1, dateParts[2]);
// months are 0-based!
// For >= IE9
var realDate = new Date('2009-11-01');
$('#datePicker').datepicker({ dateFormat: 'yy-mm-dd' }); // format to show
$('#datePicker').datepicker('setDate', realDate);
Check the above example here.
I know it's been a while on this question, but I was just looking for the same answer and found this seems to be the simplest solution:
select * from sales where datediff(dd, salesDate, '20101111') = 0
I actually use it more to find things within the last day or two, so my version looks like this:
select * from sales where datediff(dd, salesDate, getdate()) = 0
And by changing the 0 for today to a 1 I get yesterday's transactions, 2 is the day before that, and so on. And if you want everything for the last week, just change the equals to a less-than-or-equal-to:
select * from sales where datediff(dd, salesDate, getdate()) <= 7
text-align: center
will center it horizontally as for vertically put it in a span and give it a css of margin:auto 0;
(you will probably also have to give the span a display: block
property)
You can use arg(), as follow:
double dbl = 0.25874601;
QString str = QString("%1").arg(dbl);
This overcomes the problem of: "Fixed precision" at the other functions like: setNum() and number(), which will generate random numbers to complete the defined precision
Actually The documentation shows that you can use XMLHttpRequest().send()
to simply send multiform data
in case jquery sucks
This is simple way to Display Div using:-
$("#musicinfo").show(); //or
$("#musicinfo").css({'display':'block'}); //or
$("#musicinfo").toggle("slow"); //or
$("#musicinfo").fadeToggle(); //or
kill -9 $(ps -ef | grep 8084 | awk 'NR==2{print $2}')
NR is for the number of records in the input file.
awk
can find or replaces text
Additionally to Bruno's answer I ended up registering the same port for localhost. Otherwise VS2015 was giving me Access Denied error on server start.
netsh http add urlacl url=http://localhost:{port}/ user=everyone
May be it's because I have binding for localhost in aplicationhost.config also.
Here x is a vector. You need to convert it into a dataframe for using $ operator.
x <- as.data.frame(x)
will work for you.
x<-c(1,2)
names(x)<- c("bob","ed")
x <- as.data.frame(x)
will give you output of x as:
bob 1
ed 2
And, will give you output of x$ed as:
NULL
If you want bob and ed as column names then you need to transpose the dataframe like x <- as.data.frame(t(x))
So your code becomes
x<-c(1,2)
x
names(x)<- c("bob","ed")
x$ed
x <- as.data.frame(t(x))
Now the output of x$ed is:
[1] 2
An epoch reference date is a point on the timeline from which we count time. Moments before that point are counted with a negative number, moments after are counted with a positive number.
Why is 1 January 1970 00:00:00 considered the epoch time?
No, not the epoch, an epoch. There are many epochs in use.
This choice of epoch is arbitrary.
Major computers systems and libraries use any of at least a couple dozen various epochs. One of the most popular epochs is commonly known as Unix Time, using the 1970 UTC moment you mentioned.
While popular, Unix Time’s 1970 may not be the most common. Also in the running for most common would be January 0, 1900 for countless Microsoft Excel & Lotus 1-2-3 spreadsheets, or January 1, 2001 used by Apple’s Cocoa framework in over a billion iOS/macOS machines worldwide in countless apps. Or perhaps January 6, 1980 used by GPS devices?
Different systems use different granularity in counting time.
Even the so-called “Unix Time” varies, with some systems counting whole seconds and some counting milliseconds. Many database such as Postgres use microseconds. Some, such as the modern java.time framework in Java 8 and later, use nanoseconds. Some use still other granularities.
Because there is so much variance in the use of an epoch reference and in the granularities, it is generally best to avoid communicating moments as a count-from-epoch. Between the ambiguity of epoch & granularity, plus the inability of humans to perceive meaningful values (and therefore miss buggy values), use plain text instead of numbers.
The ISO 8601 standard provides an extensive set of practical well-designed formats for expressing date-time values as text. These formats are easy to parse by machine as well as easy to read by humans across cultures.
These include:
2019-01-23
2019-01-23T12:34:56.123456Z
2019-01-23T18:04:56.123456+05:30
2019-234
You can define a mutable above the scope of the threaded function, and add the result to that. (I also modified the code to be python3 compatible)
returns = {}
def foo(bar):
print('hello {0}'.format(bar))
returns[bar] = 'foo'
from threading import Thread
t = Thread(target=foo, args=('world!',))
t.start()
t.join()
print(returns)
This returns {'world!': 'foo'}
If you use the function input as the key to your results dict, every unique input is guaranteed to give an entry in the results
for me, it solved just by changing the name of my cell's file into the same as its class.
In Attributes Inspector(Third tab on the right side bar in story board):
Register the cell in your view controller as follow:
tableView.register(UINib(nibName: "MyCellClass", bundle: nil), forCellReuseIdentifier: "MyCellId")
Open the storyboard in the XML view and try to edit the rowHeight
attribute of the wanted element.
It worked for me when I tried to set custom rowHeight for my prototyped row. It's not working via inspector, but via XML it works.
Consider creating a function which can return a table and be used in a query.
https://msdn.microsoft.com/en-us/library/ms186755.aspx
The main difference between a function and a procedure is that a function makes no changes to any table. It only returns a value.
In this example I'm creating a query to give me the counts of all the columns in a given table which aren't null or empty.
There are probably many ways to clean this up. But it illustrates a function well.
USE Northwind
CREATE FUNCTION usp_listFields(@schema VARCHAR(50), @table VARCHAR(50))
RETURNS @query TABLE (
FieldName VARCHAR(255)
)
BEGIN
INSERT @query
SELECT
'SELECT ''' + @table+'~'+RTRIM(COLUMN_NAME)+'~''+CONVERT(VARCHAR, COUNT(*)) '+
'FROM '+@schema+'.'+@table+' '+
' WHERE isnull("'+RTRIM(COLUMN_NAME)+'",'''')<>'''' UNION'
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @table and TABLE_SCHEMA = @schema
RETURN
END
Then executing the function with
SELECT * FROM usp_listFields('Employees')
produces a number of rows like:
SELECT 'Employees~EmployeeID~'+CONVERT(VARCHAR, COUNT(*)) FROM dbo.Employees WHERE isnull("EmployeeID",'')<>'' UNION
SELECT 'Employees~LastName~'+CONVERT(VARCHAR, COUNT(*)) FROM dbo.Employees WHERE isnull("LastName",'')<>'' UNION
SELECT 'Employees~FirstName~'+CONVERT(VARCHAR, COUNT(*)) FROM dbo.Employees WHERE isnull("FirstName",'')<>'' UNION
arange
generates lists (well, numpy arrays); type help(np.arange)
for the details. You don't need to call it on existing lists.
>>> x = [1,2,3,4]
>>> y = [3,5,7,9]
>>>
>>> m,b = np.polyfit(x, y, 1)
>>> m
2.0000000000000009
>>> b
0.99999999999999833
I should add that I tend to use poly1d
here rather than write out "m*x+b" and the higher-order equivalents, so my version of your code would look something like this:
import numpy as np
import matplotlib.pyplot as plt
x = [1,2,3,4]
y = [3,5,7,10] # 10, not 9, so the fit isn't perfect
coef = np.polyfit(x,y,1)
poly1d_fn = np.poly1d(coef)
# poly1d_fn is now a function which takes in x and returns an estimate for y
plt.plot(x,y, 'yo', x, poly1d_fn(x), '--k')
plt.xlim(0, 5)
plt.ylim(0, 12)
I was brought here for a reason not explicitly mentioned in the answers so far, so to save others the trouble:
The error also occurs if the function arguments have changed order - for the same reason as in the accepted answer: the positional arguments clash with the keyword arguments.
In my case it was because the argument order of the Pandas set_axis
function changed between 0.20 and 0.22:
0.20: DataFrame.set_axis(axis, labels)
0.22: DataFrame.set_axis(labels, axis=0, inplace=None)
Using the commonly found examples for set_axis results in this confusing error, since when you call:
df.set_axis(['a', 'b', 'c'], axis=1)
prior to 0.22, ['a', 'b', 'c']
is assigned to axis because it's the first argument, and then the positional argument provides "multiple values".
Define the query method with signatures as follows.
@Query(select p from Person p where p.forename = :forename and p.surname = :surname)
User findByForenameAndSurname(@Param("surname") String lastname,
@Param("forename") String firstname);
}
For further details, check the Spring Data JPA reference
Use this example, you can split with the colspan
attribute
<TABLE BORDER>
<TR>
<TD>Item 1</TD>
<TD>Item 1</TD>
<TD COLSPAN=2>Item 2</TD>
</TR>
<TR>
<TD>Item 3</TD>
<TD>Item 3</TD>
<TD>Item 4</TD>
<TD>Item 5</TD>
</TR>
</TABLE>
More examples at http://hypermedia.univ-paris8.fr/jean/internet/ex_table.html.
Does an implicit conversion occur between Task<> and int?
Nope. This is just part of how async
/await
works.
Any method declared as async
has to have a return type of:
void
(avoid if possible)Task
(no result beyond notification of completion/failure)Task<T>
(for a logical result of type T
in an async manner)The compiler does all the appropriate wrapping. The point is that you're asynchronously returning urlContents.Length
- you can't make the method just return int
, as the actual method will return when it hits the first await
expression which hasn't already completed. So instead, it returns a Task<int>
which will complete when the async method itself completes.
Note that await
does the opposite - it unwraps a Task<T>
to a T
value, which is how this line works:
string urlContents = await getStringTask;
... but of course it unwraps it asynchronously, whereas just using Result
would block until the task had completed. (await
can unwrap other types which implement the awaitable pattern, but Task<T>
is the one you're likely to use most often.)
This dual wrapping/unwrapping is what allows async to be so composable. For example, I could write another async method which calls yours and doubles the result:
public async Task<int> AccessTheWebAndDoubleAsync()
{
var task = AccessTheWebAsync();
int result = await task;
return result * 2;
}
(Or simply return await AccessTheWebAsync() * 2;
of course.)
In my case everything was set up correctly but still the InfoPlist.strings file was not found.
The only thing that really worked was, to remove and add the InfoPlist.strings files again to the project.
That won't work if the string contains more than one match... try this:
echo "/x/y/z/x" | awk '{ gsub("/", "_") ; system( "echo " $0) }'
or better (if the echo
isn't a placeholder for something else):
echo "/x/y/z/x" | awk '{ gsub("/", "_") ; print $0 }'
In your case you want to make a copy of the value before changing it:
echo "/x/y/z/x" | awk '{ c=$0; gsub("/", "_", c) ; system( "echo " $0 " " c )}'
To make @Raghavendra's answer more specific:
Once you've downloaded 2 zip files,
copy ALL the contents of "win64_11gR2_database_2of2.zip -> Database -> Stage -> Components" folder to "win64_11gR2_database_1of2.zip -> Database -> Stage -> Components" folder.
You'll still get the same warning, however, the installation will run completely without generating any errors.
SELECT vg.id,
vg.name
FROM v_groups vg INNER JOIN
people2v_groups p2vg ON vg.id = p2vg.v_group_id
WHERE p2vg.people_id = 0;
In a much simpler way, you can do the same using
from PIL import Image
image = Image.open('image.jpg')
image.show()
+=
is the in-place addition operator.
It's the same as doing cnt = cnt + 1
. For example:
>>> cnt = 0
>>> cnt += 2
>>> print cnt
2
>>> cnt += 42
>>> print cnt
44
The operator is often used in a similar fashion to the ++
operator in C-ish languages, to increment a variable by one in a loop (i += 1
)
There are similar operator for subtraction/multiplication/division/power and others:
i -= 1 # same as i = i - 1
i *= 2 # i = i * 2
i /= 3 # i = i / 3
i **= 4 # i = i ** 4
The +=
operator also works on strings, for example:
>>> s = "Hi"
>>> s += " there"
>>> print s
Hi there
People tend to recommend against doing this for performance reason, but for the most scripts this really isn't an issue. To quote from the "Sequence Types" docs:
- If s and t are both strings, some Python implementations such as CPython can usually perform an in-place optimization for assignments of the form s=s+t or s+=t. When applicable, this optimization makes quadratic run-time much less likely. This optimization is both version and implementation dependent. For performance sensitive code, it is preferable to use the str.join() method which assures consistent linear concatenation performance across versions and implementations.
The str.join() method refers to doing the following:
mysentence = []
for x in range(100):
mysentence.append("test")
" ".join(mysentence)
..instead of the more obvious:
mysentence = ""
for x in range(100):
mysentence += " test"
The problem with the later is (aside from the leading-space), depending on the Python implementation, the Python interpreter will have to make a new copy of the string in memory every time you append (because strings are immutable), which will get progressively slower the longer the string to append is.. Whereas appending to a list then joining it together into a string is a consistent speed (regardless of implementation)
If you're doing basic string manipulation, don't worry about it. If you see a loop which is basically just appending to a string, consider constructing an array, then "".join()
'ing it.
Just invert the indexes' order like this:
for (int j = 0; j<array[0].length; j++){
for (int i = 0; i<array.length; i++){
because all rows has same amount of columns you can use this condition j < array[0].lengt in first for condition due to the fact you are iterating over a matrix
I've implemented and tested this one; it should cover most bases:
public static <T> List<T> safeSubList(List<T> list, int fromIndex, int toIndex) {
int size = list.size();
if (fromIndex >= size || toIndex <= 0 || fromIndex >= toIndex) {
return Collections.emptyList();
}
fromIndex = Math.max(0, fromIndex);
toIndex = Math.min(size, toIndex);
return list.subList(fromIndex, toIndex);
}
What causes runtime error 380? Attempting to set a property of an object or control to a value that is not allowed. Look through the code that runs when your search form loads (Form_Load etc.) for any code that sets a property to something that depends on runtime values.
My other advice is to add some error handling and some logging to track down the exact line that is causing the error.
Erl
to report line numbers and find the exact line - MZTools can automatically put in line numbers for you. _
On Error Goto Handler
<routine contents>
Handler:
Err.Raise Err.Number, "(function_name)->" & Err.source, Err.Description
From PowerShell remove force answer: help Remove-Item says:
The Recurse parameter in this cmdlet does not work properly
The command to workaround is
Get-ChildItem -Path $Destination -Recurse | Remove-Item -force -recurse
And then delete the folder itself
Remove-Item $Destination -Force
Update: check for existence using TryGetValue
to do only one lookup in the case where you have the list:
List<int> list;
if (!dictionary.TryGetValue("foo", out list))
{
list = new List<int>();
dictionary.Add("foo", list);
}
list.Add(2);
var dictionary = new Dictionary<string, List<int>>();
if (!dictionary.ContainsKey("foo"))
dictionary.Add("foo", new List<int>());
dictionary["foo"].Add(42);
dictionary["foo"].AddRange(oneHundredInts);
Or List<string>
as in your case.
As an aside, if you know how many items you are going to add to a dynamic collection such as List<T>
, favour the constructor that takes the initial list capacity: new List<int>(100);
.
This will grab the memory required to satisfy the specified capacity upfront, instead of grabbing small chunks every time it starts to fill up. You can do the same with dictionaries if you know you have 100 keys.
toInteger()
method is available in groovy, you could use that.
You need to follow the directions to install and start the server.
The command varies depending on how you installed MySQL. Try this first:
sudo /Library/StartupItems/MySQLCOM/MySQLCOM start
If that fails:
cd /usr/local/mysql
sudo ./bin/mysqld_safe
(Enter your password, if necessary)
(Press Control-Z)
bg
This should solve your problem: FB Share button/dialog documentation Genereally speaking you can use either normal HTML code and style it with CSS, or you can use Javascript.
Here is an example:
<a href="https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fparse.com" target="_blank" rel="noopener">
<img class="YOUR_FB_CSS_STYLING_CLASS" src="img/YOUR_FB_ICON_IMAGE.png" width="22px" height="22px" alt="Share on Facebook">
</a>
Replace https%3A%2F%2Fparse.com, YOUR_FB_CSS_STYLING_CLASS and YOUR_FB_ICON_IMAGE.png with your own choices and you should be ok.
Note: For the sake of your users' security use the HTTPS link to FB, like in the a's href attribute.
If you're not worried about a couple minutes time to do so, a solution would be to rm -rf node_modules
and npm install
again to rebuild the local modules.
To do links, you can do
.social h2 a:link {
color: pink;
font-size: 14px;
}
You can change the hover, visited, and active link styling too. Just replace "link" with what you want to style. You can learn more at the w3schools page CSS Links.
The reason why what you want to do doesn't work is because of the logical order of operations in SQL, which, for your first query, is (simplified):
FROM MonitoringJob
SELECT Category, CreationDate
i.e. add a so called extended sort key columnORDER BY CreationDate DESC
SELECT Category
i.e. remove the extended sort key column again from the result.So, thanks to the SQL standard extended sort key column feature, it is totally possible to order by something that is not in the SELECT
clause, because it is being temporarily added to it behind the scenes.
DISTINCT
?If we add the DISTINCT
operation, it would be added between SELECT
and ORDER BY
:
FROM MonitoringJob
SELECT Category, CreationDate
DISTINCT
ORDER BY CreationDate DESC
SELECT Category
But now, with the extended sort key column CreationDate
, the semantics of the DISTINCT
operation has been changed, so the result will no longer be the same. This is not what we want, so both the SQL standard, and all reasonable databases forbid this usage.
It can be emulated with standard syntax as follows
SELECT Category
FROM (
SELECT Category, MAX(CreationDate) AS CreationDate
FROM MonitoringJob
GROUP BY Category
) t
ORDER BY CreationDate DESC
Or, just simply (in this case), as shown also by Prutswonder
SELECT Category, MAX(CreationDate) AS CreationDate
FROM MonitoringJob
GROUP BY Category
ORDER BY CreationDate DESC
I have blogged about SQL DISTINCT and ORDER BY more in detail here.
git rev-parse HEAD
does the trick.
If you need to store it to checkout back later than saving actual branch if any may be preferable:
cat .git/HEAD
Example output:
ref: refs/heads/master
Parse it:
cat .git/HEAD | sed "s/^.\+ \(.\+\)$/\1/g"`
If you have Windows then you may consider using wsl.exe:
wsl cat .git/HEAD | wsl sed "s/^.\+ \(.\+\)$/\1/g"
Output:
refs/heads/master
This value may be used to git checkout later but it becomes pointing to its SHA. To make it to point to the actual current branch by its name do:
wsl cat .git/HEAD | wsl sed "s/^.\+ \(.\+\)$/\1/g" | wsl sed "s/^refs\///g" | wsl sed "s/^heads\///g"
Output:
master
I am using Git Bash on Win7. The following worked for me.
Create a config file at ~/.ssh/config or c:/users/[your_user_name]/.ssh/config. In the file enter:
Host your_host.com
IdentityFile [absolute_path_to_your_.ssh]\id_rsa
I guess the host has to be a URL and not just a "name" or ref for your host. For example,
Host github.com
IdentityFile c:/users/[user_name]/.ssh/id_rsa
The path can also be written in /c/users/[user_name]/.... format
The solution provided by Giordano Scalzo is great too. https://stackoverflow.com/a/9149518/1738546
Although this entry is quite old and most of you probably already know, I think it's worth mention that GWT 2.x includes a new compile flag which speeds up compiles by skipping optimizations. You definitely shouldn't deploy JavaScript compiled that way, but it can be a time saver during non-production continuous builds.
Just include the flag: -draftCompile to your GWT compiler line.
I came across a similar issue but instead of changing the regedit I decided to change the Chrome settings
Try the following steps
chrome://plugins/
+ Details
(top right corner) to expand all the plugin details.Java
and click on Disable
for the path(s) that you don't want to be used.You might have to restart the browser to see the changes. This also assumes that the Java that you have enabled is the latest Java.
Hope this helps
<script type="text/javascript">
$(function(){
$('#areaCode,#firstNum,#secNum').keyup(function(e){
if($(this).val().length==$(this).attr('maxlength'))
$(this).next(':input').focus()
})
})
</script>
<body>
<input type="text" id="areaCode" name="areaCode" maxlength="3" value="" size="3" />-
<input type="text" id="firstNum" name="firstNum" maxlength="3" value="" size="3" />-
<input type="text" id="secNum" name=" secNum " maxlength="4" value="" size="4" />
</body>
I am surprised that in almost ten years, no one has posted this approach yet:
If using older versions of bash where &>>
isn't available, you also can do:
(cmd 2>&1) >> file.txt
This spawns a subshell, so it's less efficient than the traditional approach of cmd >> file.txt 2>&1
, and it consequently won't work for commands that need to modify the current shell (e.g. cd
, pushd
), but this approach feels more natural and understandable to me:
Also, the parentheses remove any ambiguity of order, especially if you want to pipe stdout and stderr to another command instead.
Edit: To avoid starting a subshell, you instead could use curly braces instead of parentheses to create a group command:
{ cmd 2>&1; } >> file.txt
(Note that a semicolon (or newline) is required to terminate the group command.)
Did you try using the -ArgumentList
parameter:
invoke-command -ComputerName studio -ScriptBlock { param ( $myarg ) ping.exe $myarg } -ArgumentList localhost
http://technet.microsoft.com/en-us/library/dd347578.aspx
An example of invoking a program that is not in the path and has a space in it's folder path:
invoke-command -ComputerName Computer1 -ScriptBlock { param ($myarg) & 'C:\Program Files\program.exe' -something $myarg } -ArgumentList "myArgValue"
If the value of the argument is static you can just provide it in the script block like this:
invoke-command -ComputerName Computer1 -ScriptBlock { & 'C:\Program Files\program.exe' -something "myArgValue" }
Some OpenJDK vendors releases caused this by having an empty cacerts
file distributed with the binary. The bug is explained here: https://github.com/AdoptOpenJDK/openjdk-build/issues/555
You can copy to adoptOpenJdk8\jre\lib\security\cacerts
the file from an old instalation like c:\Program Files\Java\jdk1.8.0_192\jre\lib\security\cacerts
.
The AdoptOpenJDK buggy version is https://github.com/AdoptOpenJDK/openjdk8-releases/releases/download/jdk8u172-b11/OpenJDK8_x64_Win_jdk8u172-b11.zip
For t2/m3/c3/c4/r3/i2/d2 instances:
m1 small, medium, and large instances tend to perform higher than expected. c1.medium is another freak, at 800 MBit/s.
I gathered this by combing dozens of sources doing benchmarks (primarily using iPerf & TCP connections). Credit to CloudHarmony & flux7 in particular for many of the benchmarks (note that those two links go to google searches showing the numerous individual benchmarks).
The large instance size has the most variation reported:
Burstable (T2) instances appear to exhibit burstable networking performance too:
The CloudHarmony iperf benchmarks show initial transfers start at 1 GBit/s and then gradually drop to the sustained levels above after a few minutes. PDF links to reports below:
t2.small (PDF)
Note that these are within the same region - if you're transferring across regions, real performance may be much slower. Even for the larger instances, I'm seeing numbers of a few hundred MBit/s.
I had also the same problem and fix it via Jenkins Console.
Go to "Manage Jenkins" > "Script Console" and run a script:
Jenkins .instance.getItemByFullName("JobName")
.getBuildByNumber(JobNumber)
.finish(hudson.model.Result.ABORTED, new java.io.IOException("Aborting build"));
You'll have just specify your JobName and JobNumber.
For anyone, like me, trying to set a query string on the action and wondering why it's not working-
You cannot set a query string for a GET form submission, but I have found you can for a POST.
For a GET submission you must set the values in hidden inputs e.g.
an action of: "/handleformsubmission?foo=bar"
would have be added as the hidden field like: <input type="hidden" name="foo" value="bar" />
This can be done add dynamically in JavaScript as (where clickedButton is the submitted button that was clicked:
var form = clickedButton.form;
var hidden = document.createElement("input");
hidden.setAttribute("type", "hidden");
hidden.setAttribute("name", "foo");
hidden.setAttribute("value", "bar");
form.appendChild(hidden);
See this question for more info submitting a GET form with query string params and hidden params disappear
I second Jon Skeet's answer and want to add the following links for everyone who want to know more about "volatile" and Interlocked:
Atomicity, volatility and immutability are different, part two
Atomicity, volatility and immutability are different, part three
Sayonara Volatile - (Wayback Machine snapshot of Joe Duffy's Weblog as it appeared in 2012)
I used the following instructions to upgrade from Node.js version 0.10.6 to 0.10.21 on a Mac.
Clear NPM's cache:
sudo npm cache clean -f
Install a little helper called 'n'
sudo npm install -g n
Install latest stable Node.js version
sudo n stable
Alternatively pick a specific version and install like this:
sudo n 0.8.20
For production environments you might want to pay attention to version numbering and be picky about odd/even numbers.
Credits
Update (June 2017):
This four years old post still receives up-votes so I'm guessing it still works for many people. However, Mr. Walsh himself recommended to update Node.js just using nvm instead.
So here's what you might want to do today:
Find out which version of Node.js you are using:
node --version
Find out which versions of Node.js you may have installed and which one of those you're currently using:
nvm ls
List all versions of Node.js available for installation:
nvm ls-remote
Apparently for Windows the command would be rather like this:
nvm ls available
Assuming you would pick Node.js v8.1.0 for installation you'd type the following to install that version:
nvm install 8.1.0
You are then free to choose between installed versions of Node.js. So if you would need to use an older version like v4.2.0 you would set it as the active version like this:
nvm use 4.2
Pythonic way of iterating over a file and converting to int:
for line in open(fname):
if line.strip(): # line contains eol character(s)
n = int(line) # assuming single integer on each line
What you're trying to do is slightly more complicated, but still not straight-forward:
h = open(fname)
for line in h:
if line.strip():
[int(next(h).strip()) for _ in range(4)] # list of integers
This way it processes 5 lines at the time. Use h.next()
instead of next(h)
prior to Python 2.6.
The reason you had ValueError
is because int
cannot convert an empty string to the integer. In this case you'd need to either check the content of the string before conversion, or except an error:
try:
int('')
except ValueError:
pass # or whatever
And if you can't repeat the background image (for esthetic reasons), then this handy JQuery plugin will stretch the background image to fit the window.
Backstretch http://srobbin.com/jquery-plugins/backstretch/
Works great...
~Cheers!
I show you my example with modal windows...you create your modal and give it an id then In your table you have tr section, just ad the first line you see below (don't forget to set the on the first row like this
<tr onclick="input" data-toggle="modal" href="#the name for my modal windows" >
<td><label>Some value here</label></td>
</tr>
You could also try doing this using a sub select
SELECT c.*, p.*
FROM customer c INNER JOIN
(
SELECT customer_id,
MAX(date) MaxDate
FROM purchase
GROUP BY customer_id
) MaxDates ON c.id = MaxDates.customer_id INNER JOIN
purchase p ON MaxDates.customer_id = p.customer_id
AND MaxDates.MaxDate = p.date
The select should join on all customers and their Last purchase date.
The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName
to be the name of the file you wish to open.
Private Const TargetWBName As String = "myworkbook.xlsx"
'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
WorkbookOpen = False
On Error GoTo WorkBookNotOpen
If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
WorkbookOpen = True
Exit Function
End If
WorkBookNotOpen:
End Function
Private Sub Workbook_Open()
'Check if our target workbook is open
If WorkbookOpen(TargetWBName) = False Then
'set calculation to manual
Application.Calculation = xlCalculationManual
Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
DoEvents
Me.Close False
End If
End Sub
Set the constant 'TargetWBName' to be the name of the workbook that you wish to open.
This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself.
*NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True
after Me.Close
In addition, you can change Eclipse shortcut in Windows -> Preferences -> General -> Keys
The builtin copy(dst, src)
copies min(len(dst), len(src))
elements.
So if your dst
is empty (len(dst) == 0
), nothing will be copied.
Try tmp := make([]int, len(arr))
(Go Playground):
arr := []int{1, 2, 3}
tmp := make([]int, len(arr))
copy(tmp, arr)
fmt.Println(tmp)
fmt.Println(arr)
Output (as expected):
[1 2 3]
[1 2 3]
Unfortunately this is not documented in the builtin
package, but it is documented in the Go Language Specification: Appending to and copying slices:
The number of elements copied is the minimum of
len(src)
andlen(dst)
.
Edit:
Finally the documentation of copy()
has been updated and it now contains the fact that the minimum length of source and destination will be copied:
Copy returns the number of elements copied, which will be the minimum of len(src) and len(dst).
A lambda can only be converted to a function pointer if it does not capture, from the draft C++11 standard section 5.1.2
[expr.prim.lambda] says (emphasis mine):
The closure type for a lambda-expression with no lambda-capture has a public non-virtual non-explicit const conversion function to pointer to function having the same parameter and return types as the closure type’s function call operator. The value returned by this conversion function shall be the address of a function that, when invoked, has the same effect as invoking the closure type’s function call operator.
Note, cppreference also covers this in their section on Lambda functions.
So the following alternatives would work:
typedef bool(*DecisionFn)(int);
Decide greaterThanThree{ []( int x ){ return x > 3; } };
and so would this:
typedef bool(*DecisionFn)();
Decide greaterThanThree{ [](){ return true ; } };
and as 5gon12eder points out, you can also use std::function
, but note that std::function
is heavy weight, so it is not a cost-less trade-off.
I like getopt from stdlib, eg:
try:
opts, args = getopt.getopt(sys.argv[1:], 'h', ['help'])
except getopt.GetoptError, err:
usage(err)
for opt, arg in opts:
if opt in ('-h', '--help'):
usage()
if len(args) != 1:
usage("specify thing...")
Lately I have been wrapping something similiar to this to make things less verbose (eg; making "-h" implicit).
TRUNCATE will blank your table and reset primary key DELETE will also make your table blank but it will not reset primary key.
we can use for truncate
TRUNCATE TABLE tablename
we can use for delete
DELETE FROM tablename
we can also give conditions as below
DELETE FROM tablename WHERE id='xyz'
RMI generally won't work over a firewall, since it uses unpredictable ports (it starts off on 1099, and then runs off with a random port after that).
In these situations, you generally need to resort to tunnelling RMI over HTTP, which is described well here.
Well, even the SELECT COUNT(*) FROM Table
will be fairly inefficient, especially on large tables, since SQL Server really can't do anything but do a full table scan (clustered index scan).
Sometimes, it's good enough to know an approximate number of rows from the database, and in such a case, a statement like this might suffice:
SELECT
SUM(used_page_count) * 8 AS SizeKB,
SUM(row_count) AS [RowCount],
OBJECT_NAME(OBJECT_ID) AS TableName
FROM
sys.dm_db_partition_stats
WHERE
OBJECT_ID = OBJECT_ID('YourTableNameHere')
AND (index_id = 0 OR index_id = 1)
GROUP BY
OBJECT_ID
This will inspect the dynamic management view and extract the number of rows and the table size from it, given a specific table. It does so by summing up the entries for the heap (index_id = 0) or the clustered index (index_id = 1).
It's quick, it's easy to use, but it's not guaranteed to be 100% accurate or up to date. But in many cases, this is "good enough" (and put much less burden on the server).
Maybe that would work for you, too? Of course, to use it in EF, you'd have to wrap this up in a stored proc or use a straight "Execute SQL query" call.
Marc
The fields of your object have in turn their fields, some of which do not implement Serializable
. In your case the offending class is TransformGroup
. How to solve it?
Serializable
transient
A little late for the party, here's how I do it
./shutdown.sh
/work/Catalina/...
./startup.sh
/webapps
and start it.This should be cross platform. At least for Linux and Mac OS X.
python -c 'import multiprocessing as mp; print(mp.cpu_count())'
A little bit slow but works.
If you are editing HTML in Notepad you should use "Save As" and alter the default "Encoding:" selection at the botom of the dialog to UTF-8. you should also include-
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
_x000D_
This un-ambiguously sets the correct character set and informs the browser.
Java objects reside in an area called the heap, while metadata such as class objects and method objects reside in the permanent generation or Perm Gen area. The permanent generation is not part of the heap.
The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.
-Xmssize Specifies the initial heap size.
-Xmxsize Specifies the maximum heap size.
-XX:MaxPermSize=size Sets the maximum permanent generation space size. This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.
Sizes are expressed in bytes. Append the letter k
or K
to indicate kilobytes, m
or M
to indicate megabytes, g
or G
to indicate gigabytes.
How is the java memory pool divided?
Java (JVM) Memory Model – Memory Management in Java
From the C99 standard (C++ should be the same, barring strange overloading)
6.5.2.4 Postfix increment and decrement operators
Constraints
1 The operand of the postfix increment or decrement operator shall have qualified or unqualified real or pointer type and shall be a modifiable lvalue.
Semantics
2 The result of the postfix ++ operator is the value of the operand. After the result is obtained, the value of the operand is incremented. (That is, the value 1 of the appropriate type is added to it.) See the discussions of additive operators and compound assignment for information on constraints, types, and conversions and the effects of operations on pointers. The side effect of updating the stored value of the operand shall occur between the previous and the next sequence point.
3 The postfix -- operator is analogous to the postfix ++ operator, except that the value of the operand is decremented (that is, the value 1 of the appropriate type is subtracted from it).
6.5.3.1 Prefix increment and decrement operators
Constraints
1 The operand of the prefix increment or decrement operator shall have qualified or unqualified real or pointer type and shall be a modifiable lvalue.
Semantics
2 The value of the operand of the prefix ++ operator is incremented. The result is the new value of the operand after incrementation. The expression ++E is equivalent to (E+=1). See the discussions of additive operators and compound assignment for information on constraints, types, side effects, and conversions and the effects of operations on pointers.
3 The prefix -- operator is analogous to the prefix ++ operator, except that the value of the operand is decremented.
I followed @PabloG's steps as follows
I had same issue and my mistake was, I was trying to start tomcat server with incompatible version of JDK and installed Apache tomcat server. In my case I had installed JDK 7 with Apache tomcat 9. For Apache 9 JDK should be >= 8.
For compatibility check this https://tomcat.apache.org/whichversion.html
In this fast changing world most of these link are obsolet.
Now you can use Google Drive Web APIs:
Try something like this:
foreach (ListItem listItem in YrChkBox.Items)
{
if (listItem.Selected)
{
//do some work
}
else
{
//do something else
}
}
To my mind, the question ought to be the other way round whenever you see an inner class - does it really need to be an inner class, with the extra complexity and the implicit (rather than explicit and clearer, IMO) reference to an instance of the containing class?
Mind you, I'm biased as a C# fan - C# doesn't have the equivalent of inner classes, although it does have nested types. I can't say I've missed inner classes yet :)
In all filesystems that I am familiar with, you can't do this in-place. You have to use an auxiliary file (which you can then rename to take the name of the original file).
If you are using startActivityForResult()
in your previous activities, just override OnActivityResult()
and call the finish();
method inside it in all activities.. This will do the job...
Sql server unlike oracle does not need commits unless you are using transactions.
Immediatly after your update statement the table will be commited, don't use the commit command in this scenario.
use this:
Notification mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_music)
.setContentTitle(songName).build();
mBuilder.contentIntent= PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
contentIntent will take care of openning activity when notification clicked
This is a simple example of JSON parsing by taking example of google map API. This will return City name of given zip code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using System.Net;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
WebClient client = new WebClient();
string jsonstring;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
jsonstring = client.DownloadString("http://maps.googleapis.com/maps/api/geocode/json?address="+txtzip.Text.Trim());
dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);
Response.Write(dynObj.results[0].address_components[1].long_name);
}
}
}
You can use sets:
first_list = [1, 2, 2, 5]
second_list = [2, 5, 7, 9]
resultList= list(set(first_list) | set(second_list))
print(resultList)
# Results in : resultList = [1,2,5,7,9]
This works fine for me..!
Here is a solution
Declare @tablename varchar(20)
DECLARE @SQL NVARCHAR(MAX)
SET @tablename = '_RJ_TEMPOV4'
SET @SQL = 'DROP TABLE dbo.' + QUOTENAME(@tablename) + '';
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(@tablename) AND type in (N'U'))
EXEC sp_executesql @SQL;
Works fine on SQL Server 2014 Christophe
I had this problem today. I fixed it being being explict about my require
gem 'uglifier', '>= 1.0.3', require: 'uglifier'
I had mine still in the assets group.
Managed code is a differentiation coined by Microsoft to identify computer program code that requires and will only execute under the "management" of a Common Language Runtime virtual machine (resulting in Bytecode).
Also remember that all info()
, error()
, and debug()
logging calls provide internal documentation within any application.
Getting one month ago is easy with a single MySQL function:
SELECT DATE_SUB(NOW(), INTERVAL 1 MONTH);
or
SELECT NOW() - INTERVAL 1 MONTH;
Off the top of my head, I can't think of an elegant way to get the first day of last month in MySQL, but this will certainly work:
SELECT CONCAT(LEFT(NOW() - INTERVAL 1 MONTH,7),'-01');
Put them together and you get a query that solves your problem:
SELECT *
FROM your_table
WHERE t >= CONCAT(LEFT(NOW() - INTERVAL 1 MONTH,7),'-01')
AND t <= NOW() - INTERVAL 1 MONTH
UPDATE: READONLY
doesn't work on checkboxes
You could use disabled="disabled"
but at this point checkbox's value will not appear into POST
values. One of the strategy is to add an hidden field holding checkbox's value within the same form and read value back from that field
Simply change disabled
to readonly
You can create an array containing the numbers 0 to 5 and shuffle those. Then use the result as a mapping of "oldIndex -> newIndex" and apply this mapping to both your original arrays.
Download commons-net binary from here. Extract the files and reference the commons-net-x.x.jar file.
This should get you started:
R> qplot(hwy, cty, data = mpg) +
facet_grid(. ~ manufacturer) +
theme(strip.text.x = element_text(size = 8, colour = "orange", angle = 90))
See also this question: How can I manipulate the strip text of facet plots in ggplot2?
The below function gives distance between two geocoordinates in miles
create function [dbo].[fnCalcDistanceMiles] (@Lat1 decimal(8,4), @Long1 decimal(8,4), @Lat2 decimal(8,4), @Long2 decimal(8,4))
returns decimal (8,4) as
begin
declare @d decimal(28,10)
-- Convert to radians
set @Lat1 = @Lat1 / 57.2958
set @Long1 = @Long1 / 57.2958
set @Lat2 = @Lat2 / 57.2958
set @Long2 = @Long2 / 57.2958
-- Calc distance
set @d = (Sin(@Lat1) * Sin(@Lat2)) + (Cos(@Lat1) * Cos(@Lat2) * Cos(@Long2 - @Long1))
-- Convert to miles
if @d <> 0
begin
set @d = 3958.75 * Atan(Sqrt(1 - power(@d, 2)) / @d);
end
return @d
end
The below function gives distance between two geocoordinates in kilometres
CREATE FUNCTION dbo.fnCalcDistanceKM(@lat1 FLOAT, @lat2 FLOAT, @lon1 FLOAT, @lon2 FLOAT)
RETURNS FLOAT
AS
BEGIN
RETURN ACOS(SIN(PI()*@lat1/180.0)*SIN(PI()*@lat2/180.0)+COS(PI()*@lat1/180.0)*COS(PI()*@lat2/180.0)*COS(PI()*@lon2/180.0-PI()*@lon1/180.0))*6371
END
The below function gives distance between two geocoordinates in kilometres using Geography data type which was introduced in sql server 2008
DECLARE @g geography;
DECLARE @h geography;
SET @g = geography::STGeomFromText('LINESTRING(-122.360 47.656, -122.343 47.656)', 4326);
SET @h = geography::STGeomFromText('POINT(-122.34900 47.65100)', 4326);
SELECT @g.STDistance(@h);
Usage:
select [dbo].[fnCalcDistanceKM](13.077085,80.262675,13.065701,80.258916)
It seems that the extension cannot be found anymore using "Visual Studio Team Services". Instead, by following the link in Using Visual Studio Code & Team Foundation Version Control on "Get the TFVC plugin working in Visual Studio Code" you get to the Azure Repos Extension for Visual Studio Code GitHub. There it is explained that you now have to look for "Team Azure Repos".
Also, please note, that with the new Settings editor in Visual Studio Code the additional slashes do not have to be added. The path to tf.exe for VS 2017 - if specified using the "user friendly" Settings editor - would be just
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe
Addition to the Usage from the ORM layer in the accepted answer: count(*) can be done for ORM using the query.with_entities(func.count())
, like this:
session.query(MyModel).with_entities(func.count()).scalar()
It can also be used in more complex cases, when we have joins and filters - the important thing here is to place with_entities
after joins, otherwise SQLAlchemy could raise the Don't know how to join
error.
For example:
User
model (id
, name
) and Song
model (id
, title
, genre
)UserSong
model (user_id
, song_id
, is_liked
) where user_id
+ song_id
is a primary key)We want to get a number of user's liked rock songs:
SELECT count(*)
FROM user_song
JOIN song ON user_song.song_id = song.id
WHERE user_song.user_id = %(user_id)
AND user_song.is_liked IS 1
AND song.genre = 'rock'
This query can be generated in a following way:
user_id = 1
query = session.query(UserSong)
query = query.join(Song, Song.id == UserSong.song_id)
query = query.filter(
and_(
UserSong.user_id == user_id,
UserSong.is_liked.is_(True),
Song.genre == 'rock'
)
)
# Note: important to place `with_entities` after the join
query = query.with_entities(func.count())
liked_count = query.scalar()
Complete example is here.
Put the table in a container element that has
overflow:scroll; max-width:95vw;
or make the table fit to the screen and overflow:scroll all table cells.
$("input[name='mygroup'][value='5']").attr("checked", true);
Try this, in your parent frame set up you IFRAMEs like this:
<iframe id="frame1" src="inner.html#frame1"></iframe>
<iframe id="frame2" src="inner.html#frame2"></iframe>
<iframe id="frame3" src="inner.html#frame3"></iframe>
Note that the id of each frame is passed as an anchor in the src.
then in your inner html you can access the id of the frame it is loaded in via location.hash:
<button onclick="alert('I am frame: ' + location.hash.substr(1))">Who Am I?</button>
then you can access parent.document.getElementById() to access the iframe tag from inside the iframe
I just utilize Network Interface Names, my custom command is
[[ $(ip addr | grep enp0s25) != '' ]] && ip addr show dev enp0s25 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p' || ip addr show dev eth0 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p'
in my own notebook
[flying@lempstacker ~]$ cat /etc/redhat-release
CentOS Linux release 7.2.1511 (Core)
[flying@lempstacker ~]$ [[ $(ip addr | grep enp0s25) != '' ]] && ip addr show dev enp0s25 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p' || ip addr show dev eth0 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p'
192.168.2.221
[flying@lempstacker ~]$
but if the network interface owns at least one ip, then it will show all ip belong to it
for example
Ubuntu 16.10
root@yakkety:~# sed -r -n 's@"@@g;s@^VERSION=(.*)@\1@p' /etc/os-release
16.04.1 LTS (Xenial Xerus)
root@yakkety:~# [[ $(ip addr | grep enp0s25) != '' ]] && ip addr show dev enp0s25 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p' || ip addr show dev eth0 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p'
178.62.236.250
root@yakkety:~#
Debian Jessie
root@jessie:~# sed -r -n 's@"@@g;s@^PRETTY_NAME=(.*)@\1@p' /etc/os-release
Debian GNU/Linux 8 (jessie)
root@jessie:~# [[ $(ip addr | grep enp0s25) != '' ]] && ip addr show dev enp0s25 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p' || ip addr show dev eth0 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p'
192.81.222.54
root@jessie:~#
CentOS 6.8
[root@centos68 ~]# cat /etc/redhat-release
CentOS release 6.8 (Final)
[root@centos68 ~]# [[ $(ip addr | grep enp0s25) != '' ]] && ip addr show dev enp0s25 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p' || ip addr show dev eth0 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p'
162.243.17.224
10.13.0.5
[root@centos68 ~]# ip route get 1 | awk '{print $NF;exit}'
162.243.17.224
[root@centos68 ~]#
Fedora 24
[root@fedora24 ~]# cat /etc/redhat-release
Fedora release 24 (Twenty Four)
[root@fedora24 ~]# [[ $(ip addr | grep enp0s25) != '' ]] && ip addr show dev enp0s25 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p' || ip addr show dev eth0 | sed -n -r 's@.*inet (.*)/.*brd.*@\1@p'
104.131.54.185
10.17.0.5
[root@fedora24 ~]# ip route get 1 | awk '{print $NF;exit}'
104.131.54.185
[root@fedora24 ~]#
It seems like that command ip route get 1 | awk '{print $NF;exit}'
provided by link is more accurate, what's more, it more shorter.
Here's two simple examples
> x <- letters[1:4]
> replace(x, 3, 'Z') #replacing 'c' by 'Z'
[1] "a" "b" "Z" "d"
>
> y <- 1:10
> replace(y, c(4,5), c(20,30)) # replacing 4th and 5th elements by 20 and 30
[1] 1 2 3 20 30 6 7 8 9 10
Initially, I was running php composer.phar self-update and got the same error message.
As a resolve, you should use composer command directly after install it.From the command prompt, just type composer and press enter.
If composer is installed correctly then you should able to see a lot of suggestion and command list from composer.
If you are up to this point then you should able to run composer self-update directly.
I know it's late and was answered, but I'd like to share the neat stuff I made. I created an ng-validate directive that hooks the onsubmit of the form, then it issues prevent-default if the $eval is false:
app.directive('ngValidate', function() {
return function(scope, element, attrs) {
if (!element.is('form'))
throw new Error("ng-validate must be set on a form elment!");
element.bind("submit", function(event) {
if (!scope.$eval(attrs.ngValidate, {'$event': event}))
event.preventDefault();
if (!scope.$$phase)
scope.$digest();
});
};
});
In your html:
<form name="offering" method="post" action="offer" ng-validate="<boolean expression">
In getUserById
you shouldn't create a new object (user1) which isn't used. Just assign it to the already (but null) initialized user
. Otherwise Hibernate.initialize(user);
is actually Hibernate.initialize(null);
Here's the new getUserById
(I haven't tested this ;)):
public User getUserById(Long user_id) {
Session session = null;
Object user = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
user = (User)session.load(User.class, user_id);
Hibernate.initialize(user);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
return user;
}
The event when user releases his finger is MotionEvent.ACTION_UP
. I'm not aware if there are any guidelines which prohibit using View.OnTouchListener instead of onClick(), most probably it depends of situation.
Here's a sample code:
imageButton.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP){
// Do what you want
return true;
}
return false;
}
});
You should use :first-child
instead of :first
:
Sounds like you're wanting to iterate through them. You can do this using .each()
.
Example:
$('td:first-child').each(function() {
console.log($(this).text());
});
Result:
nonono
nonono2
nonono3
Alernatively if you're not wanting to iterate:
$('td:first-child').css('background', '#000');
You can just delete .git. Typically:
rm -rf .git
Then, recreate as the right user.
Note that -p
is an argument to the mkdir
command specifically, not the whole of Unix. Every command can have whatever arguments it needs.
In this case it means "parents", meaning mkdir
will create a directory and any parents that don't already exist.
https://developer.apple.com/ios/human-interface-guidelines/icons-and-images/app-icon/
Keep icon corners square. The system applies a mask that rounds icon corners automatically.
Keep the background simple and avoid transparency. Make sure your icon is opaque, and don’t clutter the background. Give it a simple background so it doesn’t overpower other app icons nearby. You don’t need to fill the entire icon with content.
I come a bit late with a more advanced version of Arun P Johny's answer. His solution doesn't handle multiple console.log()
arguments and doesn't give an access to the original function.
Here's my version:
(function (logger) {_x000D_
console.old = console.log;_x000D_
console.log = function () {_x000D_
var output = "", arg, i;_x000D_
_x000D_
for (i = 0; i < arguments.length; i++) {_x000D_
arg = arguments[i];_x000D_
output += "<span class=\"log-" + (typeof arg) + "\">";_x000D_
_x000D_
if (_x000D_
typeof arg === "object" &&_x000D_
typeof JSON === "object" &&_x000D_
typeof JSON.stringify === "function"_x000D_
) {_x000D_
output += JSON.stringify(arg); _x000D_
} else {_x000D_
output += arg; _x000D_
}_x000D_
_x000D_
output += "</span> ";_x000D_
}_x000D_
_x000D_
logger.innerHTML += output + "<br>";_x000D_
console.old.apply(undefined, arguments);_x000D_
};_x000D_
})(document.getElementById("logger"));_x000D_
_x000D_
// Testing_x000D_
console.log("Hi!", {a:3, b:6}, 42, true);_x000D_
console.log("Multiple", "arguments", "here");_x000D_
console.log(null, undefined);_x000D_
console.old("Eyy, that's the old and boring one.");
_x000D_
body {background: #333;}_x000D_
.log-boolean,_x000D_
.log-undefined {color: magenta;}_x000D_
.log-object,_x000D_
.log-string {color: orange;}_x000D_
.log-number {color: cyan;}
_x000D_
<pre id="logger"></pre>
_x000D_
I took it a tiny bit further and added a class to each log so you can color it. It outputs all arguments as seen in the Chrome console. You also have access to the old log via console.old()
.
Here's a minified version of the script above to paste inline, just for you:
<script>
!function(o){console.old=console.log,console.log=function(){var n,e,t="";for(e=0;e<arguments.length;e++)t+='<span class="log-'+typeof(n=arguments[e])+'">',"object"==typeof n&&"object"==typeof JSON&&"function"==typeof JSON.stringify?t+=JSON.stringify(n):t+=n,t+="</span> ";o.innerHTML+=t+"<br>",console.old.apply(void 0,arguments)}}
(document.body);
</script>
Replace document.body
in the parentheses with whatever element you wish to log into.
Use .closest()
, which gets the first ancestor element that matches the given selector 'div'
:
var classes = $(this).closest('div').attr('class').split(' ');
EDIT:
As @Shef noted, .closest()
will return the current element if it happens to be a DIV also. To take that into account, use .parent()
first:
var classes = $(this).parent().closest('div').attr('class').split(' ');
There's a drop down just above the code window:
It's called Navigation bar and contains three drop downs: first drop down contains project, second type and third members (methods).
You can use the shortcut Ctrl + F2 (move focus to the project drop down) and press Tab twice (move focus to the third drop down) to focus it, down arrow will expand the list.
A big part of the REST philosophy is to exploit as many standard features of the HTTP protocol as possible when designing your API. Applying that philosophy to authentication, client and server would utilize standard HTTP authentication features in the API.
Login screens are great for human user use cases: visit a login screen, provide user/password, set a cookie, client provides that cookie in all future requests. Humans using web browsers can't be expected to provide a user id and password with each individual HTTP request.
But for a REST API, a login screen and session cookies are not strictly necessary, since each request can include credentials without impacting a human user; and if the client does not cooperate at any time, a 401
"unauthorized" response can be given. RFC 2617 describes authentication support in HTTP.
TLS (HTTPS) would also be an option, and would allow authentication of the client to the server (and vice versa) in every request by verifying the public key of the other party. Additionally this secures the channel for a bonus. Of course, a keypair exchange prior to communication is necessary to do this. (Note, this is specifically about identifying/authenticating the user with TLS. Securing the channel by using TLS / Diffie-Hellman is always a good idea, even if you don't identify the user by its public key.)
An example: suppose that an OAuth token is your complete login credentials. Once the client has the OAuth token, it could be provided as the user id in standard HTTP authentication with each request. The server could verify the token on first use and cache the result of the check with a time-to-live that gets renewed with each request. Any request requiring authentication returns 401
if not provided.
You can use ResolveUrl
<link type="text/css" rel="stylesheet" href="<%=Page.ResolveUrl("~/Content/table-sorter.css")%>" />
You can use the following
/*eslint-disable */
//suppress all warnings between comments
alert('foo');
/*eslint-enable */
Which is slightly buried the "configuring rules" section of the docs;
To disable a warning for an entire file, you can include a comment at the top of the file e.g.
/*eslint eqeqeq:0*/
ESlint has now been updated with a better way disable a single line, see @goofballLogic's excellent answer.
New introduction 2
In the previous version of macro "SaveEmailDetails" I used this statement to find Inbox:
Set FolderTgt = CreateObject("Outlook.Application"). _
GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
I have since installed a newer version of Outlook and I have discovered that it does not use the default Inbox. For each of my email accounts, it created a separate store (named for the email address) each with its own Inbox. None of those Inboxes is the default.
This macro, outputs the name of the store holding the default Inbox to the Immediate Window:
Sub DsplUsernameOfDefaultStore()
Dim NS As Outlook.NameSpace
Dim DefaultInboxFldr As MAPIFolder
Set NS = CreateObject("Outlook.Application").GetNamespace("MAPI")
Set DefaultInboxFldr = NS.GetDefaultFolder(olFolderInbox)
Debug.Print DefaultInboxFldr.Parent.Name
End Sub
On my installation, this outputs: "Outlook Data File".
I have added an extra statement to macro "SaveEmailDetails" that shows how to access the Inbox of any store.
New introduction 1
A number of people have picked up the macro below, found it useful and have contacted me directly for further advice. Following these contacts I have made a few improvements to the macro so I have posted the revised version below. I have also added a pair of macros which together will return the MAPIFolder object for any folder with the Outlook hierarchy. These are useful if you wish to access other than a default folder.
The original text referenced one question by date which linked to an earlier question. The first question has been deleted so the link has been lost. That link was to Update excel sheet based on outlook mail (closed)
Original text
There are a surprising number of variations of the question: "How do I extract data from Outlook emails to Excel workbooks?" For example, two questions up on [outlook-vba] the same question was asked on 13 August. That question references a variation from December that I attempted to answer.
For the December question, I went overboard with a two part answer. The first part was a series of teaching macros that explored the Outlook folder structure and wrote data to text files or Excel workbooks. The second part discussed how to design the extraction process. For this question Siddarth has provided an excellent, succinct answer and then a follow-up to help with the next stage.
What the questioner of every variation appears unable to understand is that showing us what the data looks like on the screen does not tell us what the text or html body looks like. This answer is an attempt to get past that problem.
The macro below is more complicated than Siddarth’s but a lot simpler that those I included in my December answer. There is more that could be added but I think this is enough to start with.
The macro creates a new Excel workbook and outputs selected properties of every email in Inbox to create this worksheet:
Near the top of the macro there is a comment containing eight hashes (#). The statement below that comment must be changed because it identifies the folder in which the Excel workbook will be created.
All other comments containing hashes suggest amendments to adapt the macro to your requirements.
How are the emails from which data is to be extracted identified? Is it the sender, the subject, a string within the body or all of these? The comments provide some help in eliminating uninteresting emails. If I understand the question correctly, an interesting email will have Subject = "Task Completed"
.
The comments provide no help in extracting data from interesting emails but the worksheet shows both the text and html versions of the email body if they are present. My idea is that you can see what the macro will see and start designing the extraction process.
This is not shown in the screen image above but the macro outputs two versions on the text body. The first version is unchanged which means tab, carriage return, line feed are obeyed and any non-break spaces look like spaces. In the second version, I have replaced these codes with the strings [TB], [CR], [LF] and [NBSP] so they are visible. If my understanding is correct, I would expect to see the following within the second text body:
Activity[TAB]Count[CR][LF]Open[TAB]35[CR][LF]HCQA[TAB]42[CR][LF]HCQC[TAB]60[CR][LF]HAbst[TAB]50 45 5 2 2 1[CR][LF] and so on
Extracting the values from the original of this string should not be difficult.
I would try amending my macro to output the extracted values in addition to the email’s properties. Only when I have successfully achieved this change would I attempt to write the extracted data to an existing workbook. I would also move processed emails to a different folder. I have shown where these changes must be made but give no further help. I will respond to a supplementary question if you get to the point where you need this information.
Good luck.
Latest version of macro included within the original text
Option Explicit
Public Sub SaveEmailDetails()
' This macro creates a new Excel workbook and writes to it details
' of every email in the Inbox.
' Lines starting with hashes either MUST be changed before running the
' macro or suggest changes you might consider appropriate.
Dim AttachCount As Long
Dim AttachDtl() As String
Dim ExcelWkBk As Excel.Workbook
Dim FileName As String
Dim FolderTgt As MAPIFolder
Dim HtmlBody As String
Dim InterestingItem As Boolean
Dim InxAttach As Long
Dim InxItemCrnt As Long
Dim PathName As String
Dim ReceivedTime As Date
Dim RowCrnt As Long
Dim SenderEmailAddress As String
Dim SenderName As String
Dim Subject As String
Dim TextBody As String
Dim xlApp As Excel.Application
' The Excel workbook will be created in this folder.
' ######## Replace "C:\DataArea\SO" with the name of a folder on your disc.
PathName = "C:\DataArea\SO"
' This creates a unique filename.
' #### If you use a version of Excel 2003, change the extension to "xls".
FileName = Format(Now(), "yymmdd hhmmss") & ".xlsx"
' Open own copy of Excel
Set xlApp = Application.CreateObject("Excel.Application")
With xlApp
' .Visible = True ' This slows your macro but helps during debugging
.ScreenUpdating = False ' Reduces flash and increases speed
' Create a new workbook
' #### If updating an existing workbook, replace with an
' #### Open workbook statement.
Set ExcelWkBk = xlApp.Workbooks.Add
With ExcelWkBk
' #### None of this code will be useful if you are adding
' #### to an existing workbook. However, it demonstrates a
' #### variety of useful statements.
.Worksheets("Sheet1").Name = "Inbox" ' Rename first worksheet
With .Worksheets("Inbox")
' Create header line
With .Cells(1, "A")
.Value = "Field"
.Font.Bold = True
End With
With .Cells(1, "B")
.Value = "Value"
.Font.Bold = True
End With
.Columns("A").ColumnWidth = 18
.Columns("B").ColumnWidth = 150
End With
End With
RowCrnt = 2
End With
' FolderTgt is the folder I am going to search. This statement says
' I want to seach the Inbox. The value "olFolderInbox" can be replaced
' to allow any of the standard folders to be searched.
' See FindSelectedFolder() for a routine that will search for any folder.
Set FolderTgt = CreateObject("Outlook.Application"). _
GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
' #### Use the following the access a non-default Inbox.
' #### Change "Xxxx" to name of one of your store you want to access.
Set FolderTgt = Session.Folders("Xxxx").Folders("Inbox")
' This examines the emails in reverse order. I will explain why later.
For InxItemCrnt = FolderTgt.Items.Count To 1 Step -1
With FolderTgt.Items.Item(InxItemCrnt)
' A folder can contain several types of item: mail items, meeting items,
' contacts, etc. I am only interested in mail items.
If .Class = olMail Then
' Save selected properties to variables
ReceivedTime = .ReceivedTime
Subject = .Subject
SenderName = .SenderName
SenderEmailAddress = .SenderEmailAddress
TextBody = .Body
HtmlBody = .HtmlBody
AttachCount = .Attachments.Count
If AttachCount > 0 Then
ReDim AttachDtl(1 To 7, 1 To AttachCount)
For InxAttach = 1 To AttachCount
' There are four types of attachment:
' * olByValue 1
' * olByReference 4
' * olEmbeddedItem 5
' * olOLE 6
Select Case .Attachments(InxAttach).Type
Case olByValue
AttachDtl(1, InxAttach) = "Val"
Case olEmbeddeditem
AttachDtl(1, InxAttach) = "Ebd"
Case olByReference
AttachDtl(1, InxAttach) = "Ref"
Case olOLE
AttachDtl(1, InxAttach) = "OLE"
Case Else
AttachDtl(1, InxAttach) = "Unk"
End Select
' Not all types have all properties. This code handles
' those missing properties of which I am aware. However,
' I have never found an attachment of type Reference or OLE.
' Additional code may be required for them.
Select Case .Attachments(InxAttach).Type
Case olEmbeddeditem
AttachDtl(2, InxAttach) = ""
Case Else
AttachDtl(2, InxAttach) = .Attachments(InxAttach).PathName
End Select
AttachDtl(3, InxAttach) = .Attachments(InxAttach).FileName
AttachDtl(4, InxAttach) = .Attachments(InxAttach).DisplayName
AttachDtl(5, InxAttach) = "--"
' I suspect Attachment had a parent property in early versions
' of Outlook. It is missing from Outlook 2016.
On Error Resume Next
AttachDtl(5, InxAttach) = .Attachments(InxAttach).Parent
On Error GoTo 0
AttachDtl(6, InxAttach) = .Attachments(InxAttach).Position
' Class 5 is attachment. I have never seen an attachment with
' a different class and do not see the purpose of this property.
' The code will stop here if a different class is found.
Debug.Assert .Attachments(InxAttach).Class = 5
AttachDtl(7, InxAttach) = .Attachments(InxAttach).Class
Next
End If
InterestingItem = True
Else
InterestingItem = False
End If
End With
' The most used properties of the email have been loaded to variables but
' there are many more properies. Press F2. Scroll down classes until
' you find MailItem. Look through the members and note the name of
' any properties that look useful. Look them up using VB Help.
' #### You need to add code here to eliminate uninteresting items.
' #### For example:
'If SenderEmailAddress <> "[email protected]" Then
' InterestingItem = False
'End If
'If InStr(Subject, "Accounts payable") = 0 Then
' InterestingItem = False
'End If
'If AttachCount = 0 Then
' InterestingItem = False
'End If
' #### If the item is still thought to be interesting I
' #### suggest extracting the required data to variables here.
' #### You should consider moving processed emails to another
' #### folder. The emails are being processed in reverse order
' #### to allow this removal of an email from the Inbox without
' #### effecting the index numbers of unprocessed emails.
If InterestingItem Then
With ExcelWkBk
With .Worksheets("Inbox")
' #### This code creates a dividing row and then
' #### outputs a property per row. Again it demonstrates
' #### statements that are likely to be useful in the final
' #### version
' Create dividing row between emails
.Rows(RowCrnt).RowHeight = 5
.Range(.Cells(RowCrnt, "A"), .Cells(RowCrnt, "B")) _
.Interior.Color = RGB(0, 255, 0)
RowCrnt = RowCrnt + 1
.Cells(RowCrnt, "A").Value = "Sender name"
.Cells(RowCrnt, "B").Value = SenderName
RowCrnt = RowCrnt + 1
.Cells(RowCrnt, "A").Value = "Sender email address"
.Cells(RowCrnt, "B").Value = SenderEmailAddress
RowCrnt = RowCrnt + 1
.Cells(RowCrnt, "A").Value = "Received time"
With .Cells(RowCrnt, "B")
.NumberFormat = "@"
.Value = Format(ReceivedTime, "mmmm d, yyyy h:mm")
End With
RowCrnt = RowCrnt + 1
.Cells(RowCrnt, "A").Value = "Subject"
.Cells(RowCrnt, "B").Value = Subject
RowCrnt = RowCrnt + 1
If AttachCount > 0 Then
.Cells(RowCrnt, "A").Value = "Attachments"
.Cells(RowCrnt, "B").Value = "Inx|Type|Path name|File name|Display name|Parent|Position|Class"
RowCrnt = RowCrnt + 1
For InxAttach = 1 To AttachCount
.Cells(RowCrnt, "B").Value = InxAttach & "|" & _
AttachDtl(1, InxAttach) & "|" & _
AttachDtl(2, InxAttach) & "|" & _
AttachDtl(3, InxAttach) & "|" & _
AttachDtl(4, InxAttach) & "|" & _
AttachDtl(5, InxAttach) & "|" & _
AttachDtl(6, InxAttach) & "|" & _
AttachDtl(7, InxAttach)
RowCrnt = RowCrnt + 1
Next
End If
If TextBody <> "" Then
' ##### This code was in the original version of the macro
' ##### but I did not find it as useful as the other version of
' ##### the text body. See below
' This outputs the text body with CR, LF and TB obeyed
'With .Cells(RowCrnt, "A")
' .Value = "text body"
' .VerticalAlignment = xlTop
'End With
'With .Cells(RowCrnt, "B")
' ' The maximum size of a cell 32,767
' .Value = Mid(TextBody, 1, 32700)
' .WrapText = True
'End With
'RowCrnt = RowCrnt + 1
' This outputs the text body with NBSP, CR, LF and TB
' replaced by strings.
With .Cells(RowCrnt, "A")
.Value = "text body"
.VerticalAlignment = xlTop
End With
TextBody = Replace(TextBody, Chr(160), "[NBSP]")
TextBody = Replace(TextBody, vbCr, "[CR]")
TextBody = Replace(TextBody, vbLf, "[LF]")
TextBody = Replace(TextBody, vbTab, "[TB]")
With .Cells(RowCrnt, "B")
' The maximum size of a cell 32,767
.Value = Mid(TextBody, 1, 32700)
.WrapText = True
End With
RowCrnt = RowCrnt + 1
End If
If HtmlBody <> "" Then
' ##### This code was in the original version of the macro
' ##### but I did not find it as useful as the other version of
' ##### the html body. See below
' This outputs the html body with CR, LF and TB obeyed
'With .Cells(RowCrnt, "A")
' .Value = "Html body"
' .VerticalAlignment = xlTop
'End With
'With .Cells(RowCrnt, "B")
' .Value = Mid(HtmlBody, 1, 32700)
' .WrapText = True
'End With
'RowCrnt = RowCrnt + 1
' This outputs the html body with NBSP, CR, LF and TB
' replaced by strings.
With .Cells(RowCrnt, "A")
.Value = "Html body"
.VerticalAlignment = xlTop
End With
HtmlBody = Replace(HtmlBody, Chr(160), "[NBSP]")
HtmlBody = Replace(HtmlBody, vbCr, "[CR]")
HtmlBody = Replace(HtmlBody, vbLf, "[LF]")
HtmlBody = Replace(HtmlBody, vbTab, "[TB]")
With .Cells(RowCrnt, "B")
.Value = Mid(HtmlBody, 1, 32700)
.WrapText = True
End With
RowCrnt = RowCrnt + 1
End If
End With
End With
End If
Next
With xlApp
With ExcelWkBk
' Write new workbook to disc
If Right(PathName, 1) <> "\" Then
PathName = PathName & "\"
End If
.SaveAs FileName:=PathName & FileName
.Close
End With
.Quit ' Close our copy of Excel
End With
Set xlApp = Nothing ' Clear reference to Excel
End Sub
Macros not included in original post but which some users of above macro have found useful.
Public Sub FindSelectedFolder(ByRef FolderTgt As MAPIFolder, _
ByVal NameTgt As String, ByVal NameSep As String)
' This routine (and its sub-routine) locate a folder within the hierarchy and
' returns it as an object of type MAPIFolder
' NameTgt The name of the required folder in the format:
' FolderName1 NameSep FolderName2 [ NameSep FolderName3 ] ...
' If NameSep is "|", an example value is "Personal Folders|Inbox"
' FolderName1 must be an outer folder name such as
' "Personal Folders". The outer folder names are typically the names
' of PST files. FolderName2 must be the name of a folder within
' Folder1; in the example "Inbox". FolderName2 is compulsory. This
' routine cannot return a PST file; only a folder within a PST file.
' FolderName3, FolderName4 and so on are optional and allow a folder
' at any depth with the hierarchy to be specified.
' NameSep A character or string used to separate the folder names within
' NameTgt.
' FolderTgt On exit, the required folder. Set to Nothing if not found.
' This routine initialises the search and finds the top level folder.
' FindSelectedSubFolder() is used to find the target folder within the
' top level folder.
Dim InxFolderCrnt As Long
Dim NameChild As String
Dim NameCrnt As String
Dim Pos As Long
Dim TopLvlFolderList As Folders
Set FolderTgt = Nothing ' Target folder not found
Set TopLvlFolderList = _
CreateObject("Outlook.Application").GetNamespace("MAPI").Folders
' Split NameTgt into the name of folder at current level
' and the name of its children
Pos = InStr(NameTgt, NameSep)
If Pos = 0 Then
' I need at least a level 2 name
Exit Sub
End If
NameCrnt = Mid(NameTgt, 1, Pos - 1)
NameChild = Mid(NameTgt, Pos + 1)
' Look for current name. Drop through and return nothing if name not found.
For InxFolderCrnt = 1 To TopLvlFolderList.Count
If NameCrnt = TopLvlFolderList(InxFolderCrnt).Name Then
' Have found current name. Call FindSelectedSubFolder() to
' look for its children
Call FindSelectedSubFolder(TopLvlFolderList.Item(InxFolderCrnt), _
FolderTgt, NameChild, NameSep)
Exit For
End If
Next
End Sub
Public Sub FindSelectedSubFolder(FolderCrnt As MAPIFolder, _
ByRef FolderTgt As MAPIFolder, _
ByVal NameTgt As String, ByVal NameSep As String)
' See FindSelectedFolder() for an introduction to the purpose of this routine.
' This routine finds all folders below the top level
' FolderCrnt The folder to be seached for the target folder.
' NameTgt The NameTgt passed to FindSelectedFolder will be of the form:
' A|B|C|D|E
' A is the name of outer folder which represents a PST file.
' FindSelectedFolder() removes "A|" from NameTgt and calls this
' routine with FolderCrnt set to folder A to search for B.
' When this routine finds B, it calls itself with FolderCrnt set to
' folder B to search for C. Calls are nested to whatever depth are
' necessary.
' NameSep As for FindSelectedSubFolder
' FolderTgt As for FindSelectedSubFolder
Dim InxFolderCrnt As Long
Dim NameChild As String
Dim NameCrnt As String
Dim Pos As Long
' Split NameTgt into the name of folder at current level
' and the name of its children
Pos = InStr(NameTgt, NameSep)
If Pos = 0 Then
NameCrnt = NameTgt
NameChild = ""
Else
NameCrnt = Mid(NameTgt, 1, Pos - 1)
NameChild = Mid(NameTgt, Pos + 1)
End If
' Look for current name. Drop through and return nothing if name not found.
For InxFolderCrnt = 1 To FolderCrnt.Folders.Count
If NameCrnt = FolderCrnt.Folders(InxFolderCrnt).Name Then
' Have found current name.
If NameChild = "" Then
' Have found target folder
Set FolderTgt = FolderCrnt.Folders(InxFolderCrnt)
Else
'Recurse to look for children
Call FindSelectedSubFolder(FolderCrnt.Folders(InxFolderCrnt), _
FolderTgt, NameChild, NameSep)
End If
Exit For
End If
Next
' If NameCrnt not found, FolderTgt will be returned unchanged. Since it is
' initialised to Nothing at the beginning, that will be the returned value.
End Sub
There is a tutorial for creating an HTML5 progress bar here. If you don't want to use HTML5 methods or you are looking for an all-browser solution, try this code:
<div style="width: 150px; height: 25px; background-color: #dbdbdb;">
<div style="height: 25px; width:87%; background-color: gold"> </div>
</div>
_x000D_
You can change the color GOLD to any progress bar color and #dbdbdb to the background-color of your progress bar.
Yes, it is possible both in Sublime Text 2 and 3 (which you should really upgrade to if you haven't already). Select View ? Ruler ? 80
(there are several other options there as well). If you like to actually wrap your text at 80 columns, select View ? Word Wrap Column ? 80
. Make sure that View ? Word Wrap
is selected.
To make your selections permanent (the default for all opened files or views), open Preferences ? Settings—User
and use any of the following rules:
{
// set vertical rulers in specified columns.
// Use "rulers": [80] for just one ruler
// default value is []
"rulers": [80, 100, 120],
// turn on word wrap for source and text
// default value is "auto", which means off for source and on for text
"word_wrap": true,
// set word wrapping at this column
// default value is 0, meaning wrapping occurs at window width
"wrap_width": 80
}
These settings can also be used in a .sublime-project
file to set defaults on a per-project basis, or in a syntax-specific .sublime-settings
file if you only want them to apply to files written in a certain language (Python.sublime-settings
vs. JavaScript.sublime-settings
, for example). Access these settings files by opening a file with the desired syntax, then selecting Preferences ? Settings—More ? Syntax Specific—User
.
As always, if you have multiple entries in your settings file, separate them with commas ,
except for after the last one. The entire content should be enclosed in curly braces { }
. Basically, make sure it's valid JSON.
If you'd like a key combo to automatically set the ruler at 80 for a particular view/file, or you are interested in learning how to set the value without using the mouse, please see my answer here.
Finally, as mentioned in another answer, you really should be using a monospace font in order for your code to line up correctly. Other types of fonts have variable-width letters, which means one 80-character line may not appear to be the same length as another 80-character line with different content, and your indentations will look all messed up. Sublime has monospace fonts set by default, but you can of course choose any one you want. Personally, I really like Liberation Mono. It has glyphs to support many different languages and Unicode characters, looks good at a variety of different sizes, and (most importantly for a programming font) clearly differentiates between 0
and O
(digit zero and capital letter oh) and 1
and l
(digit one and lowercase letter ell), which not all monospace fonts do, unfortunately. Version 2.0 and later of the font are licensed under the open-source SIL Open Font License 1.1 (here is the FAQ).
I moved my htdocs folder from C:\xampp\htdocs to D:\htdocs without editing the Apache config file (httpd.conf).
Step 1) Move C:\xampp\htdocs
folder to D:\htdocs
Step 2) Create a symbolic link in C:\xampp\htdocs linked to D:\htdocs using mklink command.
D:\>mklink /J C:\xampp\htdocs D:\htdocs
Junction created for C:\xampp\htdocs <<===>> D:\htdocs
D:\>
Step 3) Done!
q = request.GET.get("q", None)
if q:
message = 'q= %s' % q
else:
message = 'Empty'
Maybe more clear:
Note that precision is the total number of digits, scale included
NUMBER(Precision,Scale)
Precision 8, scale 3 : 87654.321
Precision 5, scale 3 : 54.321
Precision 5, scale 1 : 5432.1
Precision 5, scale 0 : 54321
Precision 5, scale -1: 54320
Precision 5, scale -3: 54000
Trying to write a REST API from scratch is not a simple task. There are many issues to factor and you will need to write a lot of code to process requests and data coming from the caller, authentication, retrieval of data and sending back responses.
Your best bet is to use a framework that already has this functionality ready and tested for you.
Some suggestions are:
Phalcon - REST API building - Easy to use all in one framework with huge performance
Apigility - A one size fits all API handling framework by Zend Technologies
Laravel API Building Tutorial
and many more. Simple searches on Bitbucket/Github will give you a lot of resources to start with.
John Gruber (who wrote Markdown, which is made of regular expressions and is used right here on Stack Overflow) had a go at producing a regular expression that recognises URLs in text:
http://daringfireball.net/2009/11/liberal_regex_for_matching_urls
If you just want to grab the URL (i.e. you’re not really trying to parse the HTML), this might be more lightweight than an HTML parser.
$('#search_code').select2({
.
.
.
.
}).on("change", function (e) {
var str = $("#s2id_search_code .select2-choice span").text();
DOSelectAjaxProd(e.val, str);
});
You should use querySelectorAll
. It returns NodeList, however querySelector
returns only the first found element:
var deleteLink = document.querySelectorAll('.delete');
Then you would loop:
for (var i = 0; i < deleteLink.length; i++) {
deleteLink[i].addEventListener('click', function(event) {
if (!confirm("sure u want to delete " + this.title)) {
event.preventDefault();
}
});
}
Also you should preventDefault only if confirm === false
.
It's also worth noting that return false/true
is only useful for event handlers bound with onclick = function() {...}
. For addEventListening
you should use event.preventDefault()
.
Demo: http://jsfiddle.net/Rc7jL/3/
ES6 version
You can make it a little cleaner (and safer closure-in-loop wise) by using Array.prototype.forEach iteration instead of for-loop:
var deleteLinks = document.querySelectorAll('.delete');
Array.from(deleteLinks).forEach(link => {
link.addEventListener('click', function(event) {
if (!confirm(`sure u want to delete ${this.title}`)) {
event.preventDefault();
}
});
});
Example above uses Array.from and template strings from ES2015 standard.
FLAG_ACTIVITY_NO_HISTORY when starting the activity you wish to finish after the user goes to another one.
http://developer.android.com/reference/android/content/Intent.html#FLAG%5FACTIVITY%5FNO%5FHISTORY
If you would like to query all columns
List<Users> list_users = new List<Users>();
MySqlConnection cn = new MySqlConnection("connection");
MySqlCommand cm = new MySqlCommand("select * from users",cn);
try
{
cn.Open();
MySqlDataReader dr = cm.ExecuteReader();
while (dr.Read())
{
list_users.Add(new Users(dr));
}
}
catch { /* error */ }
finally { cn.Close(); }
The User's constructor would do all the "dr.GetString(i)"
I just posted a kind of a RFC that might help you: Split a vector into chunks in R
x = data.frame(num = 1:26, let = letters, LET = LETTERS)
## number of chunks
n <- 2
dfchunk <- split(x, factor(sort(rank(row.names(x))%%n)))
dfchunk
$`0`
num let LET
1 1 a A
2 2 b B
3 3 c C
4 4 d D
5 5 e E
6 6 f F
7 7 g G
8 8 h H
9 9 i I
10 10 j J
11 11 k K
12 12 l L
13 13 m M
$`1`
num let LET
14 14 n N
15 15 o O
16 16 p P
17 17 q Q
18 18 r R
19 19 s S
20 20 t T
21 21 u U
22 22 v V
23 23 w W
24 24 x X
25 25 y Y
26 26 z Z
Cheers, Sebastian
The abstract methods are implicitly virtual. Abstract methods require an instance, but static methods do not have an instance. So, you can have a static method in an abstract class, it just cannot be static abstract (or abstract static).
I had challenge with users innocently entering € and some using double quotes to define their content. I tweaked a couple of answers from this page and others to finally define my small little work-around
$products = array($ofDirtyArray);
if($products !=null) {
header("Content-type: application/json");
header('Content-Type: charset=utf-8');
array_walk_recursive($products, function(&$val) {
$val = html_entity_decode(htmlentities($val, ENT_QUOTES, "UTF-8"));
});
echo json_encode($products, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
}
I hope it helps someone/someone improves it.
Use the following command in your Terminal/Command Prompt:
php bin/console --version
This will give you your Symfony Version.
I would create a jUnit inner class that inherits from the abstract class. This can be instantiated and have access to all the methods defined in the abstract class.
public class AbstractClassTest {
public void testMethod() {
...
}
}
class ConcreteClass extends AbstractClass {
}
User can use this
Dim todaysdate As String = String.Format("{0:dd/MM/yyyy}", DateTime.Now)
this will format the date as required whereas user can change the string type dd/MM/yyyy or MM/dd/yyyy or yyyy/MM/dd or even can have this format to get the time from date
yyyy/MM/dd HH:mm:ss
How about this in your .htaccess:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
Assuming that you have a primary key for this table (you should have), as well as using a CTE or a WITH, it is also possible to use an update with a self-join to the same table:
UPDATE a
SET a.interfaceId = b.sequence
FROM prices a
INNER JOIN
(
SELECT ROW_NUMBER() OVER ( ORDER BY b.priceId ) + ( SELECT MAX( interfaceId ) + 1 FROM prices ) AS sequence, b.priceId
FROM prices b
WHERE b.interfaceId IS NULL
) b ON b.priceId = a.priceId
I have assumed that the primary key is price-id.
The derived table, alias b, is used to generated the sequence via the ROW_NUMBER() function together with the primary key column(s). For each row where the column interface-id is NULL, this will generate a row with a unique sequence value together with the primary key value.
It is possible to order the sequence in some other order rather than the primary key.
The sequence is offset by the current MAX interface-id + 1 via a sub-query. The MAX() function ignores NULL values.
The WHERE clause limits the update to those rows that are NULL.
The derived table is then joined to the same table, alias a, joining on the primary key column(s) with the column to be updated set to the generated sequence.
Use QString::arg()
for the same effect.
Use repr
and eval
:
>>> s = set([1,2,3])
>>> strs = repr(s)
>>> strs
'set([1, 2, 3])'
>>> eval(strs)
set([1, 2, 3])
Note that eval
is not safe if the source of string is unknown, prefer ast.literal_eval
for safer conversion:
>>> from ast import literal_eval
>>> s = set([10, 20, 30])
>>> lis = str(list(s))
>>> set(literal_eval(lis))
set([10, 20, 30])
help on repr
:
repr(object) -> string
Return the canonical string representation of the object.
For most object types, eval(repr(object)) == object.
In Ubuntu 18.04, below are the steps that I followed.
python3 -m pip install --upgrade pip
For some reason you will be getting an error, and that be fixed by making bash forget the wrongly referenced locations using the following command.
hash -r pip
Have you tried loading all the initialization functions using the $().ready
, running the jQuery function you wanted last?
Perhaps you can use setTimeout()
on the $().ready
function you wanted to run, calling the functionality you wanted to load.
Or, use setInterval()
and have the interval check to see if all the other load functions have completed (store the status in a boolean variable). When conditions are met, you could cancel the interval and run the load function.
FYI, in case you need to add attributes to your dictionary (things that are attached to the dictionary, but are not one of the keys), then you'll need the second form. In that case, you can initialize your dictionary with keys having arbitrary characters, one at a time, like so:
class mydict(dict): pass
a = mydict()
a["b=c"] = 'value'
a.test = False
Everything is encoded by default!!! This is pretty huge.
Declarative helpers can be compiled so you don't need to do anything special to share them. I think they will replace .ascx controls to some extent. You have to jump through some hoops to use an .ascx control in another project.
You can make a section required which is nice.
You can use the momentjs http://momentjs.com/ Library.
var moment = require('moment');
foo = new moment(something).add(10, 'm').toDate();
Using ASCII(RIGHT(ProductAlternateKey, 1))
you can see that the right most character in row 2 is a Line Feed or Ascii Character 10.
This can not be removed using the standard LTrim
RTrim
functions.
You could however use (REPLACE(ProductAlternateKey, CHAR(10), '')
You may also want to account for carriage returns and tabs. These three (Line feeds, carriage returns and tabs) are the usual culprits and can be removed with the following :
LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(ProductAlternateKey, CHAR(10), ''), CHAR(13), ''), CHAR(9), '')))
If you encounter any more "white space" characters that can't be removed with the above then try one or all of the below:
--NULL
Replace([YourString],CHAR(0),'');
--Horizontal Tab
Replace([YourString],CHAR(9),'');
--Line Feed
Replace([YourString],CHAR(10),'');
--Vertical Tab
Replace([YourString],CHAR(11),'');
--Form Feed
Replace([YourString],CHAR(12),'');
--Carriage Return
Replace([YourString],CHAR(13),'');
--Column Break
Replace([YourString],CHAR(14),'');
--Non-breaking space
Replace([YourString],CHAR(160),'');
This list of potential white space characters could be used to create a function such as :
Create Function [dbo].[CleanAndTrimString]
(@MyString as varchar(Max))
Returns varchar(Max)
As
Begin
--NULL
Set @MyString = Replace(@MyString,CHAR(0),'');
--Horizontal Tab
Set @MyString = Replace(@MyString,CHAR(9),'');
--Line Feed
Set @MyString = Replace(@MyString,CHAR(10),'');
--Vertical Tab
Set @MyString = Replace(@MyString,CHAR(11),'');
--Form Feed
Set @MyString = Replace(@MyString,CHAR(12),'');
--Carriage Return
Set @MyString = Replace(@MyString,CHAR(13),'');
--Column Break
Set @MyString = Replace(@MyString,CHAR(14),'');
--Non-breaking space
Set @MyString = Replace(@MyString,CHAR(160),'');
Set @MyString = LTRIM(RTRIM(@MyString));
Return @MyString
End
Go
Which you could then use as follows:
Select
dbo.CleanAndTrimString(ProductAlternateKey) As ProductAlternateKey
from DimProducts
If you want to just auto focus any modal that was open you can put in you patterns or lib functions this snippet that will focus on the first input:
$('.modal').on('shown.bs.modal', function () {
$(this).find('input:first').focus();
})
Try to use (focusout) instead of (blur)
Are you using a UNIX based OS such as Linux? If so, add a shebang line to the very top of your script:
#!/usr/bin/python
Underneath which you would have the rest of the code (xx.py
in your case) that you already have. Then run that same command at the terminal:
$ python xx.py
This should then work fine, as it is now interpreting this as Python code. However when running from the terminal this does not matter as python
tells how to interpret it here. What it does allow you to do is execute it outside the terminal, i.e. executing it from a file browser.
Edit 2015
Someone has made a project on NPM with my solution: https://github.com/lovasoa/react-contenteditable
Edit 06/2016: I've just encoutered a new problem that occurs when the browser tries to "reformat" the html you just gave him, leading to component always re-rendering. See
Edit 07/2016: here's my production contentEditable implementation. It has some additional options over react-contenteditable
that you might want, including:
FakeRainBrigand's solution has worked quite fine for me for some time until I got new problems. ContentEditables are a pain, and are not really easy to deal with React...
This JSFiddle demonstrates the problem.
As you can see, when you type some characters and click on Clear
, the content is not cleared. This is because we try to reset the contenteditable to the last known virtual dom value.
So it seems that:
shouldComponentUpdate
to prevent caret position jumpsshouldComponentUpdate
this way.So you need an extra line so that whenever shouldComponentUpdate
returns yes, you are sure the DOM content is actually updated.
So the version here adds a componentDidUpdate
and becomes:
var ContentEditable = React.createClass({
render: function(){
return <div id="contenteditable"
onInput={this.emitChange}
onBlur={this.emitChange}
contentEditable
dangerouslySetInnerHTML={{__html: this.props.html}}></div>;
},
shouldComponentUpdate: function(nextProps){
return nextProps.html !== this.getDOMNode().innerHTML;
},
componentDidUpdate: function() {
if ( this.props.html !== this.getDOMNode().innerHTML ) {
this.getDOMNode().innerHTML = this.props.html;
}
},
emitChange: function(){
var html = this.getDOMNode().innerHTML;
if (this.props.onChange && html !== this.lastHtml) {
this.props.onChange({
target: {
value: html
}
});
}
this.lastHtml = html;
}
});
The Virtual dom stays outdated, and it may not be the most efficient code, but at least it does work :) My bug is resolved
Details:
1) If you put shouldComponentUpdate to avoid caret jumps, then the contenteditable never rerenders (at least on keystrokes)
2) If the component never rerenders on key stroke, then React keeps an outdated virtual dom for this contenteditable.
3) If React keeps an outdated version of the contenteditable in its virtual dom tree, then if you try to reset the contenteditable to the value outdated in the virtual dom, then during the virtual dom diff, React will compute that there are no changes to apply to the DOM!
This happens mostly when:
There is no difference between the two in how they are stored in memory and registers, there is no signed and unsigned version of int registers there is no signed info stored with the int, the difference only becomes relevant when you perform maths operations, there are signed and unsigned version of the maths ops built into the CPU and the signedness tell the compiler which version to use.
Ref parameters aren't required to be set in the function, whereas out parameters must be bound to a value before exiting the function. Variables passed as out may also be passed to a function without being initialized.
I do the "in clause" query with spring jdbc like this:
String sql = "SELECT bg.goodsid FROM beiker_goods bg WHERE bg.goodsid IN (:goodsid)";
List ids = Arrays.asList(new Integer[]{12496,12497,12498,12499});
Map<String, List> paramMap = Collections.singletonMap("goodsid", ids);
NamedParameterJdbcTemplate template =
new NamedParameterJdbcTemplate(getJdbcTemplate().getDataSource());
List<Long> list = template.queryForList(sql, paramMap, Long.class);
Now I got it working (after removing the header
command). I think the problem was that the encoding of the php file was in ISO-8859-1. I set it to UTF-8 without BOM. I thought I already have done that, but perhaps I made an additional undo.
Furthermore, I used SET NAMES 'utf8'
for the database. Now it is also correct in the database.
I would use bash's [[
:
if [[ ! ("$#" == 1 && $1 =~ ^[0-9]+$ && -d $1) ]]; then
echo 'Please pass a number that corresponds to a directory'
exit 1
fi
I found this faq to be a good source of information.
This has been filed multiple times on Connect, Microsoft's community bug reporting site. FYI, I believe this bug has afflicted Visual Studio since 2003 and has been fixed after RTM each time. :( One of the references is as follows:
for /f "usebackq tokens=2*" %%i in (`svn status ^| findstr /r "^\?"`) do svn add "%%i %%j"
Within this implementation, you will get in trouble in the case your folders/filenames have more than one space like below:
"C:\PROJECTS\BACKUP_MGs_via_SVN\TEST-MG-10\data\destinations\Sega Mega 2"
"C:\PROJECTS\BACKUP_MGs_via_SVN\TEST-MG-10\data\destinations\One space"
"C:\PROJECTS\BACKUP_MGs_via_SVN\TEST-MG-10\data\destinations\Double space"
"C:\PROJECTS\BACKUP_MGs_via_SVN\TEST-MG-10\data\destinations\Single"
such cases are covered by simple:
for /f "usebackq tokens=1*" %%i in (`svn status ^| findstr /r "^\?"`) do svn add "%%j"
Mime type option is not best option for validating CSV file. I used this code this worked well in all browser
$type = explode(".",$_FILES['file']['name']);
if(strtolower(end($type)) == 'csv'){
}
else
{
}
Both the org.hibernate.Session
API and javax.persistence.EntityManager
API represent a context for dealing with persistent data.
This concept is called a persistence context. Persistent data has a state in relation to both a persistence context and the underlying database.
The following code takes an integer and makes a string out of it in hex format:
int num = 32424;
char hex[5];
sprintf(hex, "%x", num);
puts(hex);
gives
7ea8