Here's an MSDN article on Vista Gadgets. Some preliminary documentation on 7 gadgets, and changes. I think the only major changes are that Gadgets don't reside in the Sidebar anymore, and as such "dock/undock events" are now backwards-compatibility cludges that really shouldn't be used.
Best way to get started is probably to just tweak an existing gadget. There's an example gadget in the above link, or you could pick a different one out on your own.
Gadgets are written in HTML, CSS, and some IE scripting language (generally Javascript, but I believe VBScript also works). For really fancy things you might need to create an ActiveX object, so C#/C++ for COM could be useful to know.
Gadgets are packaged as ".gadget" files, which are just renamed Zip archives that contain a gadget manifest (gadget.xml) in their top level.
//set height of html
$("html").css("height", screen.height);
//set width of html
$("html").css("width", screen.width);
//go to full screen mode
document.documentElement.webkitRequestFullscreen();
Apart from having a Path
variable, the directory C:\data\db
is mandatory.
Create this and the error shall be solved.
for people new to this you can also use a callback for example:
In your service:
.factory('DataHandler',function ($http){
var GetRandomArtists = function(data, callback){
$http.post(URL, data).success(function (response) {
callback(response);
});
}
})
In your controller:
DataHandler.GetRandomArtists(3, function(response){
$scope.data.random_artists = response;
});
It's not called a tag; what you're looking for is called an html attribute.
$('div[imageId="imageN"]').each(function(i,el){
$(el).html('changes');
//do what ever you wish to this object :)
});
Good day
for some guys the order by in the sub-query is questionable. the order by in sub-query is a must to use if you need to delete some records based on some sorting. like
delete from someTable Where ID in (select top(1) from sometable where condition order by insertionstamp desc)
so that you can delete the last insertion form table. there are three way to do this deletion actually.
however, the order by in the sub-query can be used in many cases.
for the deletion methods that uses order by in sub-query review below link
i hope it helps. thanks you all
Here you get the name of the file
String[] projection = {MediaStore.MediaColumns.DISPLAY_NAME};
Uri uri = data.getData();
String fileName = null;
ContentResolver cr = getActivity().getApplicationContext().getContentResolver();
Cursor metaCursor = cr.query(uri,
projection, null, null, null);
if (metaCursor != null) {
try {
if (metaCursor.moveToFirst()) {
fileName = metaCursor.getString(0);
}
} finally {
metaCursor.close();
}
}
import { HttpClientModule } from '@angular/common/http';
The HttpClient API was introduced in the version 4.3.0. It is an evolution of the existing HTTP API and has it's own package @angular/common/http. One of the most notable changes is that now the response object is a JSON by default, so there's no need to parse it with map method anymore .Straight away we can use like below
http.get('friends.json').subscribe(result => this.result =result);
While indenting your code in the function (which is ok), you did also indent the lines of the raw message string. But leading white space implies folding (concatenation) of the header lines, as described in sections 2.2.3 and 3.2.3 of RFC 2822 - Internet Message Format:
Each header field is logically a single line of characters comprising the field name, the colon, and the field body. For convenience however, and to deal with the 998/78 character limitations per line, the field body portion of a header field can be split into a multiple line representation; this is called "folding".
In the function form of your sendmail
call, all lines are starting with white space and so are "unfolded" (concatenated) and you are trying to send
From: [email protected] To: [email protected] Subject: Hello! This message was sent with Python's smtplib.
Other than our mind suggests, smtplib
will not understand the To:
and Subject:
headers any longer, because these names are only recognized at the beginning of a line. Instead smtplib
will assume a very long sender email address:
[email protected] To: [email protected] Subject: Hello! This message was sent with Python's smtplib.
This won't work and so comes your Exception.
The solution is simple: Just preserve the message
string as it was before. This can be done by a function (as Zeeshan suggested) or right away in the source code:
import smtplib
def sendMail(FROM,TO,SUBJECT,TEXT,SERVER):
"""this is some test documentation in the function"""
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
# Send the mail
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
Now the unfolding does not occur and you send
From: [email protected]
To: [email protected]
Subject: Hello!
This message was sent with Python's smtplib.
which is what works and what was done by your old code.
Note that I was also preserving the empty line between headers and body to accommodate section 3.5 of the RFC (which is required) and put the include outside the function according to the Python style guide PEP-0008 (which is optional).
There are only 4 specific atrributes:
So you cannot control length of what user type by keyword. But the implementation of browsers may change.
Just fixed this. Hope this helps others. (Issue as in Android studio v2) This issue is for arm emulators. In this example I am using armeabi-v7a API 16
The fix is three steps:
Step 1: Open sdk manager and make sure that you have installed ARM EABI v7a System Image
Step 2. This is the obvious case of adding the location of sdk to system variables.
Right click on "This PC" icon on desktop, then
Properties -> Advanced system settings -> Environment Variables...
Then add the path to sdk as new to system variables section using variable name ANDROID_SDK_ROOT
.
Step 3.
Restart Android Studio for changes to register. After correcting the ANDROID_SDK_ROOT
is undefined issue, the emulator still can't find the kernel files even though it can see that the sdk manager installed it to
path-to-sdk\sdk\system-images\android-16\default\armeabi-v7a\kernel-qemu
The reason is a mix-up between the location the sdk manager installs the kernel file to and the location the emulator is looking for it.
If you open your config.ini (Android Studio -> AVD Mananger -> "Show On Disk") for your emulator you will see the following line:
image.sysdir.1=add-ons\addon-google_apis-google-16\images\armeabi-v7a\
(i.e \path-to-sdk\add-ons\addon-....)
Instead of changing this value in the config.ini file I copied
path-to-sdk\sdk\system-images\android-16\default\armeabi-v7a\kernel-qemu
(kernel file from the folder sdk manager installed)
to
\path-to-sdk\add-ons\addon-google_apis-google-16\images\armeabi-v7a\
And that was the missing kernel file. You can run the emulator. (You will need to close the Android Studio and reopen again) Give the emulator some time as it is 10x times slower compared to x86. (Mine took about 5 minutes to start)
SELECT from_unixtime( UNIX_TIMESTAMP(fild_with_timestamp) ) from "your_table"
This work for me
This answer uses the dynamic routing approach embraced in react-router
v4+. Other answers may reference the previously-used "static routing" approach that has been abandoned by react-router
.
react-router
is a great solution. You create your pages as Components and the router swaps out the pages according to the current URL. In other words, it replaces your original page with your new page dynamically instead of asking the server for a new page.
For web apps I recommend you read these two things first:
1 - Add react-router-dom
to your project:
Yarn
yarn add react-router-dom
or NPM
npm install react-router-dom
2 - Update your index.js
file to something like:
import { BrowserRouter } from 'react-router-dom';
ReactDOM.render((
<BrowserRouter>
<App /> {/* The various pages will be displayed by the `Main` component. */}
</BrowserRouter>
), document.getElementById('root')
);
3 - Create a Main
component that will show your pages according to the current URL:
import React from 'react';
import { Switch, Route } from 'react-router-dom';
import Home from '../pages/Home';
import Signup from '../pages/Signup';
const Main = () => {
return (
<Switch> {/* The Switch decides which component to show based on the current URL.*/}
<Route exact path='/' component={Home}></Route>
<Route exact path='/signup' component={Signup}></Route>
</Switch>
);
}
export default Main;
4 - Add the Main
component inside of the App.js
file:
function App() {
return (
<div className="App">
<Navbar />
<Main />
</div>
);
}
5 - Add Link
s to your pages.
(You must use Link
from react-router-dom
instead of just a plain old <a>
in order for the router to work properly.)
import { Link } from "react-router-dom";
...
<Link to="/signup">
<button variant="outlined">
Sign up
</button>
</Link>
If the children have FKs linking them to the parent, then you can use DELETE CASCADE on the parent.
e.g.
CREATE TABLE supplier
( supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)
);
CREATE TABLE products
( product_id numeric(10) not null,
supplier_id numeric(10) not null,
CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id)
REFERENCES supplier(supplier_id)
ON DELETE CASCADE
);
Delete the supplier, and it will delate all products for that supplier
You need also $sce.trustAsResourceUrl
or it won't open the website inside the iframe:
angular.module('myApp', [])_x000D_
.controller('dummy', ['$scope', '$sce', function ($scope, $sce) {_x000D_
_x000D_
$scope.url = $sce.trustAsResourceUrl('https://www.angularjs.org');_x000D_
_x000D_
$scope.changeIt = function () {_x000D_
$scope.url = $sce.trustAsResourceUrl('https://docs.angularjs.org/tutorial');_x000D_
}_x000D_
}]);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="dummy">_x000D_
<iframe ng-src="{{url}}" width="300" height="200"></iframe>_x000D_
<br>_x000D_
<button ng-click="changeIt()">Change it</button>_x000D_
</div>
_x000D_
One more way,
git rebase -i ad0389efc1a79b1f9c4dd6061dca6edc1d5bb78a (C's hash)
and
git push origin master -f
pick the hash that you want to use it as a base, and the above command should make it interactive so you can squash all the top messages ( you need to leave the oldest )
In this case, myvar should be a boolean value. If this variable is true, it will show the div, if it's false.. It will hide.
Check this out.
In Windows I had to create the environment variable HOME
pointing to my user profile first (C:\Users\<name>)
or whatever directory you prefer.
Then start a new command line window, create a a .ssh
directory in your user profile or choosen diretory using mkdir ".ssh"
command.
After doing that I was able to use the ssh-keygen without any path problems.
It is very convenient to use train_test_split
without performing reindexing after dividing to several sets and not writing some additional code. Best answer above does not mention that by separating two times using train_test_split
not changing partition sizes won`t give initially intended partition:
x_train, x_remain = train_test_split(x, test_size=(val_size + test_size))
Then the portion of validation and test sets in the x_remain change and could be counted as
new_test_size = np.around(test_size / (val_size + test_size), 2)
# To preserve (new_test_size + new_val_size) = 1.0
new_val_size = 1.0 - new_test_size
x_val, x_test = train_test_split(x_remain, test_size=new_test_size)
In this occasion all initial partitions are saved.
just add this line to manifest file necessary activity.
android:windowSoftInputMode="stateVisible"
for AndroidX use like
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/ic_add" />
Yes, underscores may be used anywhere in an identifier. I believe the rules are: any of a-z, A-Z, _ in the first character and those +0-9 for the following characters.
Underscore prefixes are common in C code -- a single underscore means "private", and double underscores are usually reserved for use by the compiler.
From (my entry) in the FAQ, which I certainly do not guarantee to be complete (I added two entries just two days ago):
import scala._ // Wild card -- all of Scala is imported
import scala.{ Predef => _, _ } // Exception, everything except Predef
def f[M[_]] // Higher kinded type parameter
def f(m: M[_]) // Existential type
_ + _ // Anonymous function placeholder parameter
m _ // Eta expansion of method into method value
m(_) // Partial function application
_ => 5 // Discarded parameter
case _ => // Wild card pattern -- matches anything
val (a, _) = (1, 2) // same thing
for (_ <- 1 to 10) // same thing
f(xs: _*) // Sequence xs is passed as multiple parameters to f(ys: T*)
case Seq(xs @ _*) // Identifier xs is bound to the whole matched sequence
var i: Int = _ // Initialization to the default value
def abc_<>! // An underscore must separate alphanumerics from symbols on identifiers
t._2 // Part of a method name, such as tuple getters
1_000_000 // Numeric literal separator (Scala 2.13+)
This is also part of this question.
As everyone else have already said, primary keys are automatically indexed.
Creating more indexes on the primary key column only makes sense when you need to optimize a query that uses the primary key and some other specific columns. By creating another index on the primary key column and including some other columns with it, you may reach the desired optimization for a query.
For example you have a table with many columns but you are only querying ID, Name and Address columns. Taking ID as the primary key, we can create the following index that is built on ID but includes Name and Address columns.
CREATE NONCLUSTERED INDEX MyIndex
ON MyTable(ID)
INCLUDE (Name, Address)
So, when you use this query:
SELECT ID, Name, Address FROM MyTable WHERE ID > 1000
SQL Server will give you the result only using the index you've created and it'll not read anything from the actual table.
It might be useful.
Just type this into your command prompt while cd your/package/src/
go get github.com/go-gl/[email protected]
You get specific revision of package in question right into your source code, ready to use in import statement.
Set the UINavigationBar's delegate, and then use:
- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item {
//handle the action here
}
Just try it like this:
<!-- A light one -->
<nav class="navbar navbar-default" role="navigation"></nav>
<!-- A dark one -->
<nav class="navbar navbar-inverse" role="navigation"></nav>
navabr.css
/* Navbar */
.navbar-default {
background-color: #F8F8F8;
border-color: #E7E7E7;
}
/* Title */
.navbar-default .navbar-brand {
color: #777;
}
.navbar-default .navbar-brand:hover,
.navbar-default .navbar-brand:focus {
color: #5E5E5E;
}
/* Link */
.navbar-default .navbar-nav > li > a {
color: #777;
}
.navbar-default .navbar-nav > li > a:hover,
.navbar-default .navbar-nav > li > a:focus {
color: #333;
}
.navbar-default .navbar-nav > .active > a,
.navbar-default .navbar-nav > .active > a:hover,
.navbar-default .navbar-nav > .active > a:focus {
color: #555;
background-color: #E7E7E7;
}
.navbar-default .navbar-nav > .open > a,
.navbar-default .navbar-nav > .open > a:hover,
.navbar-default .navbar-nav > .open > a:focus {
color: #555;
background-color: #D5D5D5;
}
/* Caret */
.navbar-default .navbar-nav > .dropdown > a .caret {
border-top-color: #777;
border-bottom-color: #777;
}
.navbar-default .navbar-nav > .dropdown > a:hover .caret,
.navbar-default .navbar-nav > .dropdown > a:focus .caret {
border-top-color: #333;
border-bottom-color: #333;
}
.navbar-default .navbar-nav > .open > a .caret,
.navbar-default .navbar-nav > .open > a:hover .caret,
.navbar-default .navbar-nav > .open > a:focus .caret {
border-top-color: #555;
border-bottom-color: #555;
}
/* Mobile version */
.navbar-default .navbar-toggle {
border-color: #DDD;
}
.navbar-default .navbar-toggle:hover,
.navbar-default .navbar-toggle:focus {
background-color: #DDD;
}
.navbar-default .navbar-toggle .icon-bar {
background-color: #CCC;
}
@media (max-width: 767px) {
.navbar-default .navbar-nav .open .dropdown-menu > li > a {
color: #777;
}
.navbar-default .navbar-nav .open .dropdown-menu > li > a:hover,
.navbar-default .navbar-nav .open .dropdown-menu > li > a:focus {
color: #333;
}
}
The default major color uses are as below:
You can learn more in To change navbar color in Twitter Bootstrap 3.
to work this with unicode or fontawesome, you should add a span with class like below, because input tag not support pseudo classes like :after. this is not a direct solution
in html:
<span class="button1 search"></span>
<input name="username">
in css:
.button1 {
background-color: #B9D5AD;
border-radius: 0.2em 0 0 0.2em;
box-shadow: 1px 0 0 rgba(0, 0, 0, 0.5), 2px 0 0 rgba(255, 255, 255, 0.5);
pointer-events: none;
margin:1px 12px;
border-radius: 0.2em;
color: #333333;
cursor: pointer;
position: absolute;
padding: 3px;
text-decoration: none;
}
I know it seems too late, but it may help others in future.
I face the same error and the problem was that spring boot did not read my services package so add:
@ComponentScan(basePackages = {"com.example.demo.Services"})
(you have to specify your own path to the services package) and in the class demoApplication
(class that have main function) and for service interface must be annotated @Service
and the class that implement the service interface must be annotated with @Component
, then autowired the service interface.
The root of the problem is that you are unknowingly using the Frame
class from the ttk
package rather than from the tkinter
package. The one from ttk
does not support the background option.
This is the main reason why you shouldn't do global imports -- you can overwrite the definition of classes and commands.
I recommend doing imports like this:
import tkinter as tk
import ttk
Then you prefix the widgets with either tk
or ttk
:
f1 = tk.Frame(..., bg=..., fg=...)
f2 = ttk.Frame(..., style=...)
It then becomes instantly obvious which widget you are using, at the expense of just a tiny bit more typing. If you had done this, this error in your code would never have happened.
There are three packagers, and two compilers:
free packager: PAR
commercial packagers: perl2exe, perlapp
compilers: B::C, B::CC
http://search.cpan.org/dist/B-C/perlcompile.pod
(Note: perlfaq3 is still wrong)
For strawberry you need perl-5.16 and B-C from git master (1.43), as B-C-1.42 does not support 5.16.
To generate a number between 10 to 20 inclusive, you can use java.util.Random
int myNumber = new Random().nextInt(11) + 10
I cannot find a link but I remember reading somewhere (which I agree with) that avoiding Hungarian notation results in better programming style.
When you program a statement of your program, you should not be thinking about "what type this object is" before calling its method, but rather you should think "what do I want to do with it", "which message to send to it".
Kind of vague concept to explain, but I think it works.
For example, if you have customer name stored in variable customerName, you should not care if it is a string or some other class. More important to think what do you want from this object. Do you want it to print(), getFirstName(), getLastName(), convertToString() etc. Once you make it an instance of String class and take it as granted, you limit yourself and your design since you have to build up all other logic you need elsewhere in the code.
try this
<a id="link" href="www.gmail.com" target="_blank" >gmail</a>
Simplest way is probably as follows - you basically need to construct a new array that is one element smaller, then copy the elements you want to keep to the right positions.
int n=oldArray.length-1;
String[] newArray=new String[n];
System.arraycopy(oldArray,1,newArray,0,n);
Note that if you find yourself doing this kind of operation frequently, it could be a sign that you should actually be using a different kind of data structure, e.g. a linked list. Constructing a new array every time is an O(n) operation, which could get expensive if your array is large. A linked list would give you O(1) removal of the first element.
An alternative idea is not to remove the first item at all, but just increment an integer that points to the first index that is in use. Users of the array will need to take this offset into account, but this can be an efficient approach. The Java String class actually uses this method internally when creating substrings.
you can use
@Html.Raw(str)
See MSDN for more
Returns markup that is not HTML encoded.
This method wraps HTML markup using the IHtmlString class, which renders unencoded HTML.
ldf saves the log of the db, certainly doesn't saves any real data, but is very important for the proper function of the database.
You can however change the log model to the database to simple so this log does not grow too fast.
Check this for example.
Check here for reference.
Note: if you're in a hurry, and/or looking for short answer scroll to the bottom of the answer, and read the last two lines.if Not in a hurry read the whole thing.
let me start by stating the facts:
Syntax:
string.slice(start,end)
string.substr(start,length)
string.substring(start,end)
Note #1: slice()==substring()
What it does?
The slice()
method extracts parts of a string and returns the extracted parts in a new string.
The substr()
method extracts parts of a string, beginning at the character at the specified position, and returns the specified number of characters.
The substring()
method extracts parts of a string and returns the extracted parts in a new string.
Note #2:slice()==substring()
Changes the Original String?
slice()
Doesn't
substr()
Doesn't
substring()
Doesn't
Note #3:slice()==substring()
Using Negative Numbers as an Argument:
slice()
selects characters starting from the end of the string
substr()
selects characters starting from the end of the string
substring()
Doesn't Perform
Note #3:slice()==substr()
if the First Argument is Greater than the Second:
slice()
Doesn't Perform
substr()
since the Second Argument is NOT a position, but length value, it will perform as usual, with no problems
substring()
will swap the two arguments, and perform as usual
the First Argument:
slice()
Required, indicates: Starting Index
substr()
Required, indicates: Starting Index
substring()
Required, indicates: Starting Index
Note #4:slice()==substr()==substring()
the Second Argument:
slice()
Optional, The position (up to, but not including) where to end the extraction
substr()
Optional, The number of characters to extract
substring()
Optional, The position (up to, but not including) where to end the extraction
Note #5:slice()==substring()
What if the Second Argument is Omitted?
slice()
selects all characters from the start-position to the end of the string
substr()
selects all characters from the start-position to the end of the string
substring()
selects all characters from the start-position to the end of the string
Note #6:slice()==substr()==substring()
so, you can say that there's a difference between slice()
and substr()
, while substring()
is basically a copy of slice()
.
in Summary:
if you know the index(the position) on which you'll stop (but NOT include), Use slice()
if you know the length of characters to be extracted use substr()
.
A static library is just an archive of .o
object files. Extract them with ar
(assuming Unix) and pack them back into one big library.
There's no OrderedSet
in official library.
I make an exhaustive cheatsheet of all the data structure for your reference.
DataStructure = {
'Collections': {
'Map': [
('dict', 'OrderDict', 'defaultdict'),
('chainmap', 'types.MappingProxyType')
],
'Set': [('set', 'frozenset'), {'multiset': 'collection.Counter'}]
},
'Sequence': {
'Basic': ['list', 'tuple', 'iterator']
},
'Algorithm': {
'Priority': ['heapq', 'queue.PriorityQueue'],
'Queue': ['queue.Queue', 'multiprocessing.Queue'],
'Stack': ['collection.deque', 'queue.LifeQueue']
},
'text_sequence': ['str', 'byte', 'bytearray']
}
Suppose we want to move a disc from A to C through B then:
If you repeat all the above steps, the disc will transfer.
HTML:
?<div class="header">This is the header</div>
<div class="content">This is the content</div>?????????????????????????????????
CSS:
?.header
{
height:50px;
}
.content
{
position:absolute;
top: 50px;
left:0px;
right:0px;
bottom:0px;
overflow-y:scroll;
}?
I have found the answer to my question myself:)
So what I didn't understand was how the glibc could differentiate between a Segfault and a corrupted double-linked list, because according to my understanding, from perspective of glibc they should look like the same thing. Because if I implement a double-linked list inside my program, how could the glibc possibly know that this is a double-linked list, instead of any other struct? It probably can't, so thats why i was confused.
Now I've looked at malloc/malloc.c inside the glibc's code, and I see the following:
1543 /* Take a chunk off a bin list */
1544 #define unlink(P, BK, FD) { \
1545 FD = P->fd; \
1546 BK = P->bk; \
1547 if (__builtin_expect (FD->bk != P || BK->fd != P, 0)) \
1548 malloc_printerr (check_action, "corrupted double-linked list", P); \
1549 else { \
1550 FD->bk = BK; \
1551 BK->fd = FD; \
So now this suddenly makes sense. The reason why glibc can know that this is a double-linked list is because the list is part of glibc itself. I've been confused because I thought glibc can somehow detect that some programming is building a double-linked list, which I wouldn't understand how that works. But if this double-linked list that it is talking about, is part of glibc itself, of course it can know it's a double-linked list.
I still don't know what has triggered this error. But at least I understand the difference between corrupted double-linked list and a Segfault, and how the glibc can know this struct is supposed to be a double-linked list:)
String.Format must start with zero index "{0}" like this:
Aboutme.Text = String.Format("{0}", reader.GetString(0));
You do not define a binding in your service's config, so you are getting the default values for wsHttpBinding
, and the default value for securityMode\transport
for that binding is Message
.
Try copying your binding configuration from the client's config to your service config and assign that binding to the endpoint via the bindingConfiguration
attribute:
<bindings>
<wsHttpBinding>
<binding name="ota2010AEndpoint"
.......>
<readerQuotas maxDepth="32" ... />
<reliableSession ordered="true" .... />
<security mode="Transport">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="Windows" negotiateServiceCredential="true"
establishSecurityContext="true" />
</security>
</binding>
</wsHttpBinding>
</bindings>
(Snipped parts of the config to save space in the answer).
<service name="Synxis" behaviorConfiguration="SynxisWCF">
<endpoint address="" name="wsHttpEndpoint"
binding="wsHttpBinding"
bindingConfiguration="ota2010AEndpoint"
contract="Synxis" />
This will then assign your defined binding (with Transport security) to the endpoint.
I noticed a lot of these answers, use this command:
use admin
which switches to the admin database. At least in Mongo v4.0.6, creating a user in the context of the admin database will create a user with "_id" : "admin.administrator"
:
> use admin
> db.getUsers()
[ ]
> db.createUser({ user: 'administrator', pwd: 'changeme', roles: [ { role: 'root', db: 'admin' } ] })
> db.getUsers()
[
{
"_id" : "admin.administrator",
"user" : "administrator",
"db" : "admin",
"roles" : [
{
"role" : "root",
"db" : "admin"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
]
I emphasize "admin.administrator"
, for I have a Mongoid (mongodb ruby adapter) application with a different database than admin and I use the URI to reference the database in my mongoid.yml configuration:
development:
clients:
default:
uri: <%= ENV['MONGODB_URI'] %>
options:
connect_timeout: 15
retry_writes: false
This references the following environment variable:
export MONGODB_URI='mongodb://administrator:[email protected]/mysite_development?retryWrites=true&w=majority'
Notice the database is mysite_development, not admin. When I try to run the application, I get an error "User administrator (mechanism: scram256) is not authorized to access mysite_development".
So I return to the Mongo shell delete the user, switch to the specified database and recreate the user:
$ mongo
> db.dropUser('administrator')
> db.getUsers()
[]
> use mysite_development
> db.createUser({ user: 'administrator', pwd: 'changeme', roles: [ { role: 'root', db: 'admin' } ] })
> db.getUsers()
[
{
"_id" : "mysite_development.administrator",
"user" : "administrator",
"db" : "mysite_development",
"roles" : [
{
"role" : "root",
"db" : "admin"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}
]
Notice that the _id and db changed to reference the specific database my application depends on:
"_id" : "mysite_development.administrator",
"db" : "mysite_development",
After making this change, the error went away and I was able to connect to MongoDB fine inside my application.
Extra Notes:
In my example above, I deleted the user and recreated the user in the right database context. Had you already created the user in the right database context but given it the wrong roles, you could assign a mongodb built-in role to the user:
db.grantRolesToUser('administrator', [{ role: 'root', db: 'admin' }])
There is also a db.updateUser
command, albiet typically used to update the user password.
var exists = $("#yourSelect option")
.filter(function (i, o) { return o.value === yourValue; })
.length > 0;
This has the advantage of automatically escaping the value for you, which makes random quotes in the text much easier to deal with.
Install the CSS Usage add-on for Firebug and run it on that page. It will tell you which styles are being used and not used by that page.
Did you just try
$('#datebox li a').on('click', function(){
//$('#datebox').val($(this).text());
alert($(this).text());
});
It works for me :)
Note, Java 6 in the latest incarnation allows for jconsole to attach itself to a running process even after it has been started without JMX incantations.
If that is available to you, also consider jvisualvm as it provides a wealth of information on running processes, including a profiler.
You can use Microsoft Office Web Apps to embed PowerPoint and Excel Files. See Say more in your blog with embedded PowerPoint and Excel files.
Python is upset because you are attempting to assign a value to something that can't be assigned a value.
((t[1])/length) * t[1] += string
When you use an assignment operator, you assign the value of what is on the right to the variable or element on the left. In your case, there is no variable or element on the left, but instead an interpreted value: you are trying to assign a value to something that isn't a "container".
Based on what you've written, you're just misunderstanding how this operator works. Just switch your operands, like so.
string += str(((t[1])/length) * t[1])
Note that I've wrapped the assigned value in str
in order to convert it into a str
so that it is compatible with the string
variable it is being assigned to. (Numbers and strings can't be added together.)
All above not worked for me, but this was: Check that the name of Root element of class is exactly like the one from XML case sensitive.
If you update a submodule and commit to it, you need to go to the containing, or higher level repo and add the change there.
git status
will show something like:
modified:
some/path/to/your/submodule
The fact that the submodule is out of sync can also be seen with
git submodule
the output will show:
+afafaffa232452362634243523 some/path/to/your/submodule
The plus indicates that the your submodule is pointing ahead of where the top repo expects it to point to.
simply add this change:
git add some/path/to/your/submodule
and commit it:
git commit -m "referenced newer version of my submodule"
When you push up your changes, make sure you push up the change in the submodule first and then push the reference change in the outer repo. This way people that update will always be able to successfully run
git submodule update
More info on submodules can be found here http://progit.org/book/ch6-6.html.
Classic mode (the only mode in IIS6 and below) is a mode where IIS only works with ISAPI extensions and ISAPI filters directly. In fact, in this mode, ASP.NET is just an ISAPI extension (aspnet_isapi.dll) and an ISAPI filter (aspnet_filter.dll). IIS just treats ASP.NET as an external plugin implemented in ISAPI and works with it like a black box (and only when it's needs to give out the request to ASP.NET). In this mode, ASP.NET is not much different from PHP or other technologies for IIS.
Integrated mode, on the other hand, is a new mode in IIS7 where IIS pipeline is tightly integrated (i.e. is just the same) as ASP.NET request pipeline. ASP.NET can see every request it wants to and manipulate things along the way. ASP.NET is no longer treated as an external plugin. It's completely blended and integrated in IIS. In this mode, ASP.NET HttpModule
s basically have nearly as much power as an ISAPI filter would have had and ASP.NET HttpHandler
s can have nearly equivalent capability as an ISAPI extension could have. In this mode, ASP.NET is basically a part of IIS.
I can confirm that in Android Studio 1.x (here AS) on Windows also the right sequence is:
This can be done absolutely in any moments after creation of the project.
Android Studio warns you that it will overwrite the current ic_launcer, but this is exactly what we expect to do.
As noted in a prior answer, although git merge-base
works,
$ git merge-base myfeature develop
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2
If myfeature
is the current branch, as is common, you can use --fork-point
:
$ git merge-base --fork-point develop
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2
This argument works only in sufficiently recent versions of git. Unfortunately it doesn't always work, however, and it is not clear why. Please refer to the limitations noted toward the end of this answer.
For full commit info, consider:
$ git log -1 $(git merge-base --fork-point develop)
You need to make sure that the value you pass to the directory
argument is an absolute path, corrected for the current location of your application.
The best way to do this is to configure UPLOAD_FOLDER
as a relative path (no leading slash), then make it absolute by prepending current_app.root_path
:
@app.route('/uploads/<path:filename>', methods=['GET', 'POST'])
def download(filename):
uploads = os.path.join(current_app.root_path, app.config['UPLOAD_FOLDER'])
return send_from_directory(directory=uploads, filename=filename)
It is important to reiterate that UPLOAD_FOLDER
must be relative for this to work, e.g. not start with a /
.
A relative path could work but relies too much on the current working directory being set to the place where your Flask code lives. This may not always be the case.
As @Mr_and_Mrs_D suggested:
String haystack = "hellolovelyworld";
String needle = "lo";
return haystack.split(Pattern.quote(needle), -1).length - 1;
In SQL you need to use GETDATE()
:
UPDATE table SET date = GETDATE();
There is no NOW()
function.
To answer your question:
In a large table, since the function is evaluated for each row, you will end up getting different values for the updated field.
So, if your requirement is to set it all to the same date I would do something like this (untested):
DECLARE @currDate DATETIME;
SET @currDate = GETDATE();
UPDATE table SET date = @currDate;
I don't know if anyone is still reading this thread or not, but Jeff's solution will only get you halfway there (kinda literally). What his onMeasure will do is display half the image in half the parent. The problem is that calling super.onMeasure prior to the setMeasuredDimension
will measure all the children in the view based on the original size, then just cut the view in half when the setMeasuredDimension
resizes it.
Instead, you need to call setMeasuredDimension
(as required for an onMeasure override) and provide a new LayoutParams
for your view, then call super.onMeasure
. Remember, your LayoutParams
are derived from your view's parent type, not your view's type.
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
this.setMeasuredDimension(parentWidth/2, parentHeight);
this.setLayoutParams(new *ParentLayoutType*.LayoutParams(parentWidth/2,parentHeight));
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
I believe the only time you'll have problems with the parent LayoutParams
is if the parent is an AbsoluteLayout
(which is deprecated but still sometimes useful).
Run a Force re-import from the maven tool window. If that does not work, Invalidate your caches (File > Invalidate caches) and restart. Wait for IDEA to re-index the project.
I changed the Select Run/Debug Configuration
from my MainActivity
to App
and it started working. Select App configuration snapshot:
Despite that my server was running, I had the same problem. I found out that it was the port. So you need to specify the port:
mysql -u user -p --port 0000
The port on your machine may be different. To find out on which port mysql is running open the mysql ini file and look for port=
. A port often used is 3306
.
Example how to log on to mysql
mysql -u root -p --port 3306
Try to format your date with the Z
or z
timezone flags:
new SimpleDateFormat("MM/dd/yyyy KK:mm:ss a Z").format(dateObj);
This is an alternative if you don't want to use claims all the time. Take a look at this tutorial by Ben Foster.
public class AppUser : ClaimsPrincipal
{
public AppUser(ClaimsPrincipal principal)
: base(principal)
{
}
public string Name
{
get
{
return this.FindFirst(ClaimTypes.Name).Value;
}
}
}
Then you can add a base controller.
public abstract class AppController : Controller
{
public AppUser CurrentUser
{
get
{
return new AppUser(this.User as ClaimsPrincipal);
}
}
}
In you controller, you would do:
public class HomeController : AppController
{
public ActionResult Index()
{
ViewBag.Name = CurrentUser.Name;
return View();
}
}
Android Cloud to Device Messaging Framework
Important: C2DM has been officially deprecated as of June 26, 2012. This means that C2DM has stopped accepting new users and quota requests. No new features will be added to C2DM. However, apps using C2DM will continue to work. Existing C2DM developers are encouraged to migrate to the new version of C2DM, called Google Cloud Messaging for Android (GCM). See the C2DM-to-GCM Migration document for more information. Developers must use GCM for new development.
Kindly check the following link:
You could check this if you like. :)
Use this code if SavedFamilyCode is in the Report Filter:
Sub FilterPivotTable()
Application.ScreenUpdating = False
ActiveSheet.PivotTables("PivotTable2").ManualUpdate = True
ActiveSheet.PivotTables("PivotTable2").PivotFields("SavedFamilyCode").ClearAllFilters
ActiveSheet.PivotTables("PivotTable2").PivotFields("SavedFamilyCode").CurrentPage = _
"K123223"
ActiveSheet.PivotTables("PivotTable2").ManualUpdate = False
Application.ScreenUpdating = True
End Sub
But if the SavedFamilyCode is in the Column or Row Labels use this code:
Sub FilterPivotTable()
Application.ScreenUpdating = False
ActiveSheet.PivotTables("PivotTable2").ManualUpdate = True
ActiveSheet.PivotTables("PivotTable2").PivotFields("SavedFamilyCode").ClearAllFilters
ActiveSheet.PivotTables("PivotTable2").PivotFields("SavedFamilyCode").PivotFilters. _
Add Type:=xlCaptionEquals, Value1:="K123223"
ActiveSheet.PivotTables("PivotTable2").ManualUpdate = False
Application.ScreenUpdating = True
End Sub
Hope this helps you.
I've had a few cranberry-vodkas tonight so I might be missing something...Is setting the range necessary? Why not use:
Activeworkbook.Sheets("Game").Range("A1").value = "Subtotal"
Does this fail as well?
Looks like you tried something similar:
'Worksheets("Game").Range("A1") = "Asdf"
However, Worksheets is a collection, so you can't reference "Game". I think you need to use the Sheets object instead.
Normally we face this issue when there is a problem mapping JSON node with that of Java object. I faced the same issue because in the swagger the node was defined as of Type array and the JSON object was having only one element , hence the system was having difficulty in mapping one element list to an array.
In Swagger the element was defined as
Test:
"type": "array",
"minItems": 1,
"items": {
"$ref": "#/definitions/TestNew"
}
While it should be
Test:
"$ref": "#/definitions/TestNew"
And TestNew
should be of type array
a:visited
{
color: #881033;
}
(or whatever color you want it to be)
text-decoration
is for underlining(overlining etc.
decoration
ist not a valid css rule.
An alternative can be
c = Product.find_by("LOWER(name)= ?", name.downcase)
If property hibernate.ddl-auto = update
, then it will not create the tables automatically.
To create tables automatically, you need to set the property to
hibernate.ddl-auto = create
The list of option which is used in the spring boot are
validate: validate the schema, makes no changes to the database.
update: update the schema.
create: creates the schema, destroying previous data.
create-drop: drop the schema at the end of the session
none: is all other cases
So for the first time you can set it to create and then next time on-wards you should set it to update.
Made an improvement code by @Ipsita - for use asynchronous read\write file I/O
readonly string logPath = @"FilePath";
...
public async Task WriteToLogAsync(string dataToWrite)
{
TextReader tr = new StreamReader(logPath);
string data = await tr.ReadLineAsync();
tr.Close();
TextWriter tw = new StreamWriter(logPath);
await tw.WriteLineAsync(data + dataToWrite);
tw.Close();
}
...
await WriteToLogAsync("Write this to file");
I use it to amend more than just the last commit.
Let's say I made a mistake in commit A and then made commit B. Now I can only amend B.
So I do git reset --soft HEAD^^
, I correct and re-commit A and then re-commit B.
Of course, it's not very convenient for large commits… but you shouldn't do large commits anyway ;-)
how will I know that some tables are locked?
You can use SHOW OPEN TABLES command to view locked tables.
how do I unlock tables manually?
If you know the session ID that locked tables - 'SELECT CONNECTION_ID()', then you can run KILL command to terminate session and unlock tables.
The best way to use is white-space: nowrap;
This will align the text to one line.
You could define a macro containing the following code:
Sub DeleteA5X50()
Range("A5:X50").Select
Selection.ClearContents
end sub
Running the macro would select the range A5:x50 on the active worksheet and clear all the contents of the cells within that range.
To leave your formulas intact use the following instead:
Sub DeleteA5X50()
Range("A5:X50").Select
Selection.SpecialCells(xlCellTypeConstants, 23).Select
Selection.ClearContents
end sub
This will first select the overall range of cells you are interested in clearing the contents from and will then further limit the selection to only include cells which contain what excel considers to be 'Constants.'
You can do this manually in excel by selecting the range of cells, hitting 'f5' to bring up the 'Go To' dialog box and then clicking on the 'Special' button and choosing the 'Constants' option and clicking 'Ok'.
<form method='post' id='userform' action='thisform.php'> <tr>
<td>Trouble Type</td>
<td>
<input type='checkbox' name='checkboxvar[]' value='Option One'>1<br>
<input type='checkbox' name='checkboxvar[]' value='Option Two'>2<br>
<input type='checkbox' name='checkboxvar[]' value='Option Three'>3
</td> </tr> </table> <input type='submit' class='buttons'> </form>
<?php
if (isset($_POST['checkboxvar']))
{
print_r($_POST['checkboxvar']);
}
?>
You pass the form name as an array and then you can access all checked boxes using the var itself which would then be an array.
To echo checked options into your email you would then do this:
echo implode(',', $_POST['checkboxvar']); // change the comma to whatever separator you want
Please keep in mind you should always sanitize your input as needed.
For the record, official docs on this exist: http://php.net/manual/en/faq.html.php#faq.html.arrays
What about the following snippet?
require 'json'
value = '{"val":"test","val1":"test1","val2":"test2"}'
puts JSON.parse(value) # => {"val"=>"test","val1"=>"test1","val2"=>"test2"}
Seems to work:
static UIViewController *viewControllerForView(UIView *view) {
UIResponder *responder = view;
do {
responder = [responder nextResponder];
}
while (responder && ![responder isKindOfClass:[UIViewController class]]);
return (UIViewController *)responder;
}
-(void)showActionSheet {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
[alertController addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]];
[alertController addAction:[UIAlertAction actionWithTitle:@"Do it" style:UIAlertActionStyleDefault handler:nil]];
[viewControllerForView(self) presentViewController:alertController animated:YES completion:nil];
}
Would something like this work:
In [7]: df.groupby('dummy').returns.agg({'func1' : lambda x: x.sum(), 'func2' : lambda x: x.prod()})
Out[7]:
func2 func1
dummy
1 -4.263768e-16 -0.188565
In my experience, the things I need to make environment-specific are things like connection strings, appsettings and often smpt settings. The config system allows to specify these things in separate files. So you can use this in your app.config/web.config:
<appSettings configSource="appsettings.config" />
<connectionStrings configSource="connection.config" />
<system.net>
<mailSettings>
<smtp configSource="smtp.config"/>
</mailSettings>
</system.net>
What I typically do is to put these config-specific sections in separate files, in a subfolder called ConfigFiles (either in the solution root or at the project level, depends). I define a file per configuration, e.g. smtp.config.Debug and smtp.config.Release.
Then you can define a pre-build event like so:
copy $(ProjectDir)ConfigFiles\smtp.config.$(ConfigurationName) $(TargetDir)smtp.config
In team development, you can tweak this further by including the %COMPUTERNAME% and/or %USERNAME% in the convention.
Of course, this implies that the target files (x.config) should NOT be put in source control (since they are generated). You should still add them to the project file and set their output type property to 'copy always' or 'copy if newer' though.
Simple, extensible, and it works for all types of Visual Studio projects (console, winforms, wpf, web).
In the case of stored procedure update, you should delete it from the .dbml file and reinsert it again. But if the stored procedure have two paths (ex: if something; display some columns; else display some other columns), make sure the two paths have the same columns aliases!!! Otherwise only the first path columns will exist.
A faster / alternative way to change the height and/or width of a UIView
is by setting its width/height through frame.size
:
let neededHeight = UIScreen.main.bounds.height * 0.2
yourView.frame.size.height = neededHeight
FAIL-SAFE and simple "recursive" method, which can be used with multiple textboxes.
It blocks the wrong keyboard typed characters and also pasted values etc. It only accepts integer numbers, and the maximum number length is the maximum length of a string type (which is int, really long!)
public void Check_If_Int_On_TextChanged(object sender, EventArgs e)
{
// This method checks that each inputed character is a number. Any non-numeric
// characters are removed from the text
TextBox textbox = (TextBox)sender;
// If the text is empty, return
if (textbox.Text.Length == 0) { return; }
// Check the new Text value if it's only numbers
byte parsedValue;
if (!byte.TryParse(textbox.Text[(textbox.Text.Length - 1)].ToString(), out parsedValue))
{
// Remove the last character as it wasn't a number
textbox.Text = textbox.Text.Remove((textbox.Text.Length - 1));
// Move the cursor to the end of text
textbox.SelectionStart = textbox.Text.Length;
}
}
Try this first, you may be passing a Null Model:
@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
<label for="Image">Change picture</label>
}
else
{
<label for="Image">Add picture</label>
}
Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.
<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>
Reminder to self... fetch first, else the repository has not local hash (I guess).
step 1. Setup the upstream remote and above^
diffing a single file follows this pattern :
git diff localBranch uptreamBranch --spacepath/singlefile
git diff master upstream/nameofrepo -- src/index.js
JQuery .extend does this for you:
var mytsobject = new mytsobject();
var newObj = {a:1,b:2};
$.extend(mytsobject, newObj); //mytsobject will now contain a & b
If you don't mind a paid-for product, PowerGREP is my personal favorite.
For me this works on Debian 6 (Squeeze):
Linux www809 2.6.26-2-xen-686 #1 SMP Wed Sep 21 09:56:47 UTC 2011 i686 GNU/Linux
I had to go to the right path:
/usr/local/apache/bin** $ **./apachectl -v
./apachectl: line 71: ulimit: open files: cannot modify limit: Operation not permitted
Server version: Apache/2.2.21 (Unix)
Server built: Dec 17 2011 19:57:53
The easiest way is to use the ``
feature in Perl. This will execute what is inside and return what was printed to stdout:
my $pid = 5892;
my $var = `top -H -p $pid -n 1 | grep myprocess | wc -l`;
print "not = $var\n";
This should do it.
for (int j=0; j<test.length; j++) {
System.out.format("%02X ", test[j]);
}
System.out.println();
This doesn't seem to be a problem on a Core 2 Duo running Windows XP and JRE 1.5.0_06.
In a test with three threads I don't see System.nanoTime() going backwards. The processors are both busy, and threads go to sleep occasionally to provoke moving threads around.
[EDIT] I would guess that it only happens on physically separate processors, i.e. that the counters are synchronized for multiple cores on the same die.
First to answer your question, you set a variable to true or false by assigning True
or False
to it:
myFirstVar = True
myOtherVar = False
If you have a condition that is basically like this though:
if <condition>:
var = True
else:
var = False
then it is much easier to simply assign the result of the condition directly:
var = <condition>
In your case:
match_var = a == b
Right Click on your project: Run (As) -> Maven clean Right Click on your project: Run (As) -> Maven install
Use this:
var table = $(selector).dataTables();
table.api().draw(false);
or
var table = $(selector).DataTables();
table.draw(false);
Pass the object from controller to view, convert it to markup without encoding, and parse it to json.
@model IEnumerable<CollegeInformationDTO>
@section Scripts{
<script>
var jsArray = JSON.parse('@Html.Raw(Json.Encode(@Model))');
</script>
}
(Windows mysql config)
Step 1 : Go To Apache Control Panel > Apache > Config > PHP.ini
Step 2 : Search in Notepad (Ctrl+F) For: ;extension_dir = ""
(could be commented with a ;
). Replace this line with: extension_dir = "C:\php\ext"
(please do not you need to remove the ;
on the beginning of the sentence).
Step 3 : Search For: extension=php_mysql.dll
and remove the ;
in the beginning.
Step 4 : Save and Restart You Apache HTTP Server. (On Windows this usually done via a UI)
That's it :)
If you get errors about missing php_mysql.dll
you'll probably need to download this file from either the php.net site or the pecl.php.net. (Please be causius about where you get it from)
More info on PHP: Installation of extensions on Windows - Manual
Regex if you want to ensure URL starts with HTTP/HTTPS:
https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)
If you do not require HTTP protocol:
[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)
To try this out see http://regexr.com?37i6s, or for a version which is less restrictive http://regexr.com/3e6m0.
Example JavaScript implementation:
var expression = /[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)?/gi;_x000D_
var regex = new RegExp(expression);_x000D_
var t = 'www.google.com';_x000D_
_x000D_
if (t.match(regex)) {_x000D_
alert("Successful match");_x000D_
} else {_x000D_
alert("No match");_x000D_
}
_x000D_
Try this:
/* Variable Declaration */
DECLARE @EmpID AS SMALLINT
DECLARE @SQLQuery AS NVARCHAR(500)
DECLARE @ParameterDefinition AS NVARCHAR(100)
DECLARE @TableName AS NVARCHAR(100)
/* set the parameter value */
SET @EmpID = 1001
SET @TableName = 'tblEmployees'
/* Build Transact-SQL String by including the parameter */
SET @SQLQuery = 'SELECT * FROM ' + @TableName + ' WHERE EmployeeID = @EmpID'
/* Specify Parameter Format */
SET @ParameterDefinition = '@EmpID SMALLINT'
/* Execute Transact-SQL String */
EXECUTE sp_executesql @SQLQuery, @ParameterDefinition, @EmpID
try pnp_datetime, all the time been used and returned is with timezone, and will not cause any offset-naive and offset-aware issues.
>>> from pnp_datetime.pnp_datetime import Pnp_Datetime
>>>
>>> Pnp_Datetime.utcnow()
datetime.datetime(2020, 6, 5, 12, 26, 18, 958779, tzinfo=<UTC>)
You will need to use JavaScript without resulting to an iframe
(ugly approach).
You can do it in JavaScript; using jQuery will make it painless.
I suggest you check out AJAX and Posting.
You could use java.time.temporal.ValueRange
which accepts long
and would also work with int
:
int a = 2147;
//Use java 8 java.time.temporal.ValueRange. The range defined
//is inclusive of both min and max
ValueRange range = ValueRange.of(0, 2147483647);
if(range.isValidValue(a)) {
System.out.println("in range");
}else {
System.out.println("not in range");
}
If this code is on a separate project, like a library project. Don't forgeet to add reference to system.configuration.
You can use following:
angular.element(domElement).scope()
to get the current scope for the element
angular.element(domElement).injector()
to get the current app injector
angular.element(domElement).controller()
to get a hold of the ng-controller instance.
Hope that might help
Note that the %
syntax for formatting strings is becoming outdated. If your version of Python supports it, you should write:
instr = "'{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}'".format(softname, procversion, int(percent), exe, description, company, procurl)
This also fixes the error that you happened to have.
We actually have some notification code in our product that uses TLS to send mail if it is available.
You will need to set the Java Mail properties. You only need the TLS one but you might need SSL if your SMTP server uses SSL.
Properties props = new Properties();
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.auth", "true"); // If you need to authenticate
// Use the following if you need SSL
props.put("mail.smtp.socketFactory.port", d_port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
You can then either pass this to a JavaMail Session or any other session instantiator like Session.getDefaultInstance(props)
.
In order to jump out of a loop, you need to use the break statement.
n=L[0][0]
m=len(A)
for i in range(m):
for j in range(m):
if L[i][j]!=n:
break;
Here you have the official Python manual with the explanation about break and continue, and other flow control statements:
http://docs.python.org/tutorial/controlflow.html
EDITED: As a commenter pointed out, this does only end the inner loop. If you need to terminate both loops, there is no "easy" way (others have given you a few solutions). One possiblity would be to raise an exception:
def f(L, A):
try:
n=L[0][0]
m=len(A)
for i in range(m):
for j in range(m):
if L[i][j]!=n:
raise RuntimeError( "Not equal" )
return True
except:
return False
I dont know about XamGrid
but that's what i'll do with a standard wpf DataGrid
:
<DataGrid>
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding DataContext.MyProperty, RelativeSource={RelativeSource AncestorType=MyUserControl}}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding DataContext.MyProperty, RelativeSource={RelativeSource AncestorType=MyUserControl}}"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
Since the TextBlock
and the TextBox
specified in the cell templates will be part of the visual tree, you can walk up and find whatever control you need.
In your phone go to Settings->Connect
to PC.
There you will see the option Default Connection Type
. Select it and set it to your preference.
<?php
session_start();
session_unset();
session_destroy();
header("location:home.php");
exit();
?>
There are two major options in matplotlib (pylab) to control the image size:
Normally, you would like to do both, because this way you will have full control over the resulting image size in pixels. For example, if you want to render exactly 800x600 image, you can use DPI=100, and set the size as 8 x 6 in inches:
import matplotlib.pyplot as plt
# plot whatever you need...
# now, before saving to file:
figure = plt.gcf() # get current figure
figure.set_size_inches(8, 6)
# when saving, specify the DPI
plt.savefig("myplot.png", dpi = 100)
One can use any DPI. In fact, you might want to play with various DPI and size values to get the result you like the most. Beware, however, that using very small DPI is not a good idea, because matplotlib may not find a good font to render legend and other text. For example, you cannot set the DPI=1, because there are no fonts with characters rendered with 1 pixel :)
From other comments I understood that other issue you have is proper text rendering. For this, you can also change the font size. For example, you may use 6 pixels per character, instead of 12 pixels per character used by default (effectively, making all text twice smaller).
import matplotlib
#...
matplotlib.rc('font', size=6)
Finally, some references to the original documentation: http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.savefig, http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.gcf, http://matplotlib.sourceforge.net/api/figure_api.html#matplotlib.figure.Figure.set_size_inches, http://matplotlib.sourceforge.net/users/customizing.html#dynamic-rc-settings
P.S. Sorry, I didn't use pylab, but as far as I'm aware, all the code above will work same way in pylab - just replace plt
in my code with the pylab
(or whatever name you assigned when importing pylab). Same for matplotlib
- use pylab
instead.
__dict__
or vars
does not work because it misses out __slots__
.__dict__
and __slots__
does not work because it misses out __slots__
from base classes.dir
does not work because it includes class attributes, such as methods or properties, as well as the object attributes.vars
is equivalent to using __dict__
.This is the best I have:
from typing import Dict
def get_attrs( x : object ) -> Dict[str, object]:
mro = type( x ).mro()
attrs = { }
has_dict = False
sentinel = object()
for klass in mro:
for slot in getattr( klass, "__slots__", () ):
v = getattr( x, slot, sentinel )
if v is sentinel:
continue
if slot == "__dict__":
assert not has_dict, "Multiple __dicts__?"
attrs.update( v )
has_dict = True
else:
attrs[slot] = v
if not has_dict:
attrs.update( getattr( x, "__dict__", { } ) )
return attrs
When you click the Button
if(isset($_POST['save'])){
$sql = "INSERT INTO `members`(`id`, `membership_id`, `email`, `first_name`)
VALUES ('".$_POST["id"]."','".$_POST["membership_id"]."','".$_POST["email"]."','".$_POST["firstname"]."')";
**if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}**
}
This will execute the Query in the variable $sql
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
adding overflow:visible !important;
to the body element worked for me.
Please find the method to validate if char is letter, number or space, otherwise attach underscore (Be free to modified according your needs)
public String CleanStringToLettersNumbers(String data)
{
var result = String.Empty;
foreach (var item in data)
{
var c = '_';
if ((int)item >= 97 && (int)item <= 122 ||
(int)item >= 65 && (int)item <= 90 ||
(int)item >= 48 && (int)item <= 57 ||
(int)item == 32)
{
c = item;
}
result = result + c;
}
return result;
}
Duplicated id
for pairs name
and city
:
select s.id, t.*
from [stuff] s
join (
select name, city, count(*) as qty
from [stuff]
group by name, city
having count(*) > 1
) t on s.name = t.name and s.city = t.city
To add onto the answer from Rishabh and make it able to handle files that are not images that are found in the folder.
import matplotlib.image as mpimg
images = []
folder = './your/folder/'
for filename in os.listdir(folder):
try:
img = mpimg.imread(os.path.join(folder, filename))
if img is not None:
images.append(img)
except:
print('Cant import ' + filename)
images = np.asarray(images)
I like s3fs which lets you use s3 (almost) like a local filesystem.
You can do this:
import s3fs
bytes_to_write = df.to_csv(None).encode()
fs = s3fs.S3FileSystem(key=key, secret=secret)
with fs.open('s3://bucket/path/to/file.csv', 'wb') as f:
f.write(bytes_to_write)
s3fs
supports only rb
and wb
modes of opening the file, that's why I did this bytes_to_write
stuff.
Or you can try this -
Extend your Application class with MultiDexApplication instead of Application !
Update! You can access the Android filesystem via Android Device Monitor. In Android Studio go to Tools >> Android >> Android Device Monitor.
Note that you can run your app in the simulator while using the Android Device Monitor. But you cannot debug you app while using the Android Device Monitor.
Using the Apache Commons IO API https://commons.apache.org/proper/commons-io/ I was able to establish this using FileUtils.readFileToString(file).contains(stringToFind)
The documentation for this function is at https://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/FileUtils.html#readFileToString(java.io.File)
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
/**********************************************************************
Naziv procedure : sp_rfv_FIND
Ime i prezime autora: Srdjan Nadrljanski
Datum kreiranja : 13.06.2013.
Namena : Traži sql objekat na celom serveru
Tabele :
Ulazni parametri :
Izlazni parametri :
Datum zadnje izmene :
Opis izmene :
exec sp_rfv_FIND 'TUN',''
**********************************************************************/
CREATE PROCEDURE [dbo].[sp_rfv_FIND] ( @SEARCHSTRING VARCHAR(255),
@notcontain Varchar(255)
)
AS
declare @text varchar(1500),@textinit varchar (1500)
set @textinit=
'USE @sifra
insert into ##temp2
select ''@sifra''as dbName,a.[Object Name],a.[Object Type]
from(
SELECT DISTINCT sysobjects.name AS [Object Name] ,
case
when sysobjects.xtype = ''C'' then ''CHECK constraint''
when sysobjects.xtype = ''D'' then ''Default or DEFAULT constraint''
when sysobjects.xtype = ''F'' then ''Foreign Key''
when sysobjects.xtype = ''FN'' then ''Scalar function''
when sysobjects.xtype = ''P'' then ''Stored Procedure''
when sysobjects.xtype = ''PK'' then ''PRIMARY KEY constraint''
when sysobjects.xtype = ''S'' then ''System table''
when sysobjects.xtype = ''TF'' then ''Function''
when sysobjects.xtype = ''TR'' then ''Trigger''
when sysobjects.xtype = ''U'' then ''User table''
when sysobjects.xtype = ''UQ'' then ''UNIQUE constraint''
when sysobjects.xtype = ''V'' then ''View''
when sysobjects.xtype = ''X'' then ''Extended stored procedure''
end as [Object Type]
FROM sysobjects
WHERE
sysobjects.type in (''C'',''D'',''F'',''FN'',''P'',''K'',''S'',''TF'',''TR'',''U'',''V'',''X'')
AND sysobjects.category = 0
AND CHARINDEX(''@SEARCHSTRING'',sysobjects.name)>0
AND ((CHARINDEX(''@notcontain'',sysobjects.name)=0 or
CHARINDEX(''@notcontain'',sysobjects.name)<>0))
)a'
set @textinit=replace(@textinit,'@SEARCHSTRING',@SEARCHSTRING)
set @textinit=replace(@textinit,'@notcontain',@notcontain)
SELECT name AS dbName,cast(null as varchar(255)) as ObjectName,cast(null as varchar(255)) as ObjectType
into ##temp1
from master.dbo.sysdatabases order by name
SELECT * INTO ##temp2 FROM ##temp1 WHERE 1 = 0
declare @sifra VARCHAR(255),@suma int,@brojac int
set @suma=(select count(dbName) from ##temp1)
DECLARE c_k CURSOR LOCAL FAST_FORWARD FOR
SELECT dbName FROM ##temp1 ORDER BY dbName DESC
OPEN c_k
FETCH NEXT FROM c_K INTO @sifra
SET @brojac = 1
WHILE (@@fetch_status = 0 ) AND (@brojac <= @suma)
BEGIN
set @text=replace(@textinit,'@sifra',@sifra)
exec (@text)
SET @brojac = @brojac +1
DELETE FROM ##temp1 WHERE dbName = @sifra
FETCH NEXT FROM c_k INTO @sifra
END
close c_k
DEALLOCATE c_k
select * from ##temp2
order by dbName,ObjectType
drop table ##temp2
drop table ##temp1
Try use a regular expression (Regex), which will be quite useful when you want to validate / extract stuff or even do some simple parsing in javascript.
The regex is :
/([a-zA-Z]+):\/\/([\-\w\.]+)(?:\:(\d{0,5}))?/
Demonstration:
function breakURL(url){
matches = /([a-zA-Z]+):\/\/([\-\w\.]+)(?:\:(\d{0,5}))?/.exec(url);
foo = new Array();
if(matches){
for( i = 1; i < matches.length ; i++){ foo.push(matches[i]); }
}
return foo
}
url = "https://www.google.co.uk:55699/search?q=http%3A%2F%2F&oq=http%3A%2F%2F&aqs=chrome..69i57j69i60l3j69i65l2.2342j0j4&sourceid=chrome&ie=UTF-8"
breakURL(url); // [https, www.google.co.uk, 55699]
breakURL(); // []
breakURL("asf"); // []
breakURL("asd://"); // []
breakURL("asd://a"); // [asd, a, undefined]
Now you can do validation as well.
Apple's Auto Layout Guide includes an entire section on Working with Scroll Views. Some relevant snippets:
- Pin the content view’s top, bottom, leading, and trailing edges to the scroll view’s corresponding edges. The content view now defines the scroll view’s content area.
- (Optional) To disable horizontal scrolling, set the content view’s width equal to the scroll view’s width. The content view now fills the scroll view horizontally.
- (Optional) To disable vertical scrolling, set the content view’s height equal to the scroll view’s height. The content view now fills the scroll view horizontally.
Furthermore:
Your layout must fully define the size of the content view (except where defined in steps 5 and 6). … When the content view is taller than the scroll view, the scroll view enables vertical scrolling. When the content view is wider than the scroll view, the scroll view enables horizontal scrolling.
To summarize, the scroll view's content view (in this case, a stack view) must be pinned to its edges and have its width and/or height otherwise constrained. That means that the contents of the stack view must be constrained (directly or indirectly) in the direction(s) in which scrolling is desired, which might mean adding a height constraint to each view inside a vertically scrolling stack view, for example. The following is an example of how to allow for vertical scrolling of a scroll view containing a stack view:
// Pin the edges of the stack view to the edges of the scroll view that contains it
stackView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
stackView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
stackView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
stackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
// Set the width of the stack view to the width of the scroll view for vertical scrolling
stackView.widthAnchor.constraint(equalTo: scrollView.widthAnchor).isActive = true
Try this,
public static Double[][] multiplicar(Double A[][],Double B[][]){
Double[][] C= new Double[2][2];
int i,j,k;
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
C[i][j] = 0.00000;
}
}
for(i=0;i<2;i++){
for(j=0;j<2;j++){
for (k=0;k<2;k++){
C[i][j]+=(A[i][k]*B[k][j]);
}
}
}
return C;
}
This happened to me with a page loaded in via an iframe. The iframe src page had a 404 script reference. Obviously I couldn't find the script reference in the parent page, so it took me a while to find the culprit.
Yes, It's possible with DOUBLE STASH
git stash --keep-index
. This command will create a stash with ALL of your changes (staged and unstaged), but will leave the staged changes in your working directory (still in state staged).git stash push -m "good stash"
"good stash"
has ONLY staged files. Now if you need unstaged files before stash, simply apply first stash (the one created with --keep-index
) and now you can remove files you stashed to "good stash"
.
Enjoy
Just call the "type" built in using three parameters, like this:
ClassName = type("ClassName", (Base1, Base2,...), classdictionary)
update as stated in the comment bellow this is not the answer to this question at all. I will keep it undeleted, since there are hints some people get here trying to dynamically create classes - which is what the line above does.
To create an object of a class one has a reference too, as put in the accepted answer, one just have to call the class:
instance = ClassObject()
The mechanism for instantiation is thus:
Python does not use the new
keyword some languages use - instead it's data model explains the mechanism used to create an instantance of a class when it is called with the same syntax as any other callable:
Its class' __call__
method is invoked (in the case of a class, its class is the "metaclass" - which is usually the built-in type
). The normal behavior of this call is to invoke the (pseudo) static __new__
method on the class being instantiated, followed by its __init__
. The __new__
method is responsible for allocating memory and such, and normally is done by the __new__
of object
which is the class hierarchy root.
So calling ClassObject()
invokes ClassObject.__class__.call()
(which normally will be type.__call__
) this __call__
method will receive ClassObject itself as the first parameter - a Pure Python implementation would be like this: (the cPython version is of course, done in C, and with lots of extra code for cornercases and optimizations)
class type:
...
def __call__(cls, *args, **kw):
constructor = getattr(cls, "__new__")
instance = constructor(cls) if constructor is object.__new__ else constructor(cls, *args, **kw)
instance.__init__(cls, *args, **kw)
return instance
(I don't recall seeing on the docs the exact justification (or mechanism) for suppressing extra parameters to the root __new__
and passing it to other classes - but it is what happen "in real life" - if object.__new__
is called with any extra parameters it raises a type error - however, any custom implementation of a __new__
will get the extra parameters normally)
this
is the DOM element on which the event was hooked. this.id
is its ID. No need to wrap it in a jQuery instance to get it, the id
property reflects the attribute reliably on all browsers.
$("select").change(function() {
alert("Changed: " + this.id);
}
You're not doing this in your code sample, but if you were watching a container with several form elements, that would give you the ID of the container. If you want the ID of the element that triggered the event, you could get that from the event
object's target
property:
$("#container").change(function(event) {
alert("Field " + event.target.id + " changed");
});
(jQuery ensures that the change
event bubbles, even on IE where it doesn't natively.)
Having tried $customer = new WC_Customer();
and global $woocommerce; $customer = $woocommerce->customer;
I was still getting empty address data even when I logged in as a non-admin user.
My solution was as follows:
function mwe_get_formatted_shipping_name_and_address($user_id) {
$address = '';
$address .= get_user_meta( $user_id, 'shipping_first_name', true );
$address .= ' ';
$address .= get_user_meta( $user_id, 'shipping_last_name', true );
$address .= "\n";
$address .= get_user_meta( $user_id, 'shipping_company', true );
$address .= "\n";
$address .= get_user_meta( $user_id, 'shipping_address_1', true );
$address .= "\n";
$address .= get_user_meta( $user_id, 'shipping_address_2', true );
$address .= "\n";
$address .= get_user_meta( $user_id, 'shipping_city', true );
$address .= "\n";
$address .= get_user_meta( $user_id, 'shipping_state', true );
$address .= "\n";
$address .= get_user_meta( $user_id, 'shipping_postcode', true );
$address .= "\n";
$address .= get_user_meta( $user_id, 'shipping_country', true );
return $address;
}
...and this code works regardless of whether you are logged in as admin or not.
In order to pass the parameters you create new intent and put a parameter map:
Intent myIntent = new Intent(this, NewActivityClassName.class);
myIntent.putExtra("firstKeyName","FirstKeyValue");
myIntent.putExtra("secondKeyName","SecondKeyValue");
startActivity(myIntent);
In order to get the parameters values inside the started activity, you must call the get[type]Extra()
on the same intent:
// getIntent() is a method from the started activity
Intent myIntent = getIntent(); // gets the previously created intent
String firstKeyName = myIntent.getStringExtra("firstKeyName"); // will return "FirstKeyValue"
String secondKeyName= myIntent.getStringExtra("secondKeyName"); // will return "SecondKeyValue"
If your parameters are ints you would use getIntExtra()
instead etc.
Now you can use your parameters like you normally would.
Once I developed Chrome (desktop browser) extension and tested Local Storage real max size for this reason.
My results:
Ubuntu 18.04.1 LTS (64-bit)
Chrome 71.0.3578.98 (Official Build) (64-bit)
Local Storage content size 10240 KB (10 MB)
More than 10240 KB
usage returned me the error:
Uncaught DOMException: Failed to execute 'setItem' on 'Storage': Setting the value of 'notes' exceeded the quota.
Edit on Oct 23, 2020
For a Chrome extensions available chrome.storage
API. If you declare the "storage" permission in manifest.js
:
{
"name": "My extension",
...
"permissions": ["storage"],
...
}
You can access it like this:
chrome.storage.local.QUOTA_BYTES // 5242880 (in bytes)
I encountered a similar issue trying to use xlrd in jupyter notebook. I notice you are using a virtual environment and that was the key to my issue as well. I had xlrd installed in my venv, but I had not properly installed a kernel for that virtual environment in my notebook.
To get it to work, I created my virtual environment and activated it.
Then... pip install ipykernel
And then... ipython kernel install --user --name=myproject
Finally, start jupyter notebooks and when you create a new notebook, select the name you created (in this example, 'myproject')
Hope that helps.
When talking about "bad input", you should consider where the input is coming from.
Is the input entered by a user or another external system you don't control, you should expect the input to be invalid, and always validate it. It's perfectly ok to throw a checked exception in this case. Your application should 'recover' from this exception by providing an error message to the user.
If the input originates from your own system, e.g. your database, or some other parts of your application, you should be able to rely on it to be valid (it should have been validated before it got there). In this case it's perfectly ok to throw an unchecked exception like an IllegalArgumentException, which should not be caught (in general you should never catch unchecked exceptions). It is a programmer's error that the invalid value got there in the first place ;) You need to fix it.
As an alternative to the default title
attribute tooltips, you can make your own custom CSS tooltips using :before
/:after
pseudo elements and HTML5 data-*
attributes.
Using the provided CSS, you can add a tooltip to an element using the data-tooltip
attribute.
You can also control the position of the custom tooltip using the data-tooltip-position
attribute (accepted values: top
/right
/bottom
/left
).
For instance, the following will add a tooltop positioned at the bottom of the span element.
<span data-tooltip="Custom tooltip text." data-tooltip-position="bottom">Custom bottom tooltip.</span>
You can display the custom tooltips with pseudo elements by retrieving the custom attribute values using the attr()
function.
[data-tooltip]:before {
content: attr(data-tooltip);
}
In terms of positioning the tooltip, just use the attribute selector and change the placement based on the attribute's value.
Full CSS used in the example - customize this to your needs.
[data-tooltip] {
display: inline-block;
position: relative;
cursor: help;
padding: 4px;
}
/* Tooltip styling */
[data-tooltip]:before {
content: attr(data-tooltip);
display: none;
position: absolute;
background: #000;
color: #fff;
padding: 4px 8px;
font-size: 14px;
line-height: 1.4;
min-width: 100px;
text-align: center;
border-radius: 4px;
}
/* Dynamic horizontal centering */
[data-tooltip-position="top"]:before,
[data-tooltip-position="bottom"]:before {
left: 50%;
-ms-transform: translateX(-50%);
-moz-transform: translateX(-50%);
-webkit-transform: translateX(-50%);
transform: translateX(-50%);
}
/* Dynamic vertical centering */
[data-tooltip-position="right"]:before,
[data-tooltip-position="left"]:before {
top: 50%;
-ms-transform: translateY(-50%);
-moz-transform: translateY(-50%);
-webkit-transform: translateY(-50%);
transform: translateY(-50%);
}
[data-tooltip-position="top"]:before {
bottom: 100%;
margin-bottom: 6px;
}
[data-tooltip-position="right"]:before {
left: 100%;
margin-left: 6px;
}
[data-tooltip-position="bottom"]:before {
top: 100%;
margin-top: 6px;
}
[data-tooltip-position="left"]:before {
right: 100%;
margin-right: 6px;
}
/* Tooltip arrow styling/placement */
[data-tooltip]:after {
content: '';
display: none;
position: absolute;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
}
/* Dynamic horizontal centering for the tooltip */
[data-tooltip-position="top"]:after,
[data-tooltip-position="bottom"]:after {
left: 50%;
margin-left: -6px;
}
/* Dynamic vertical centering for the tooltip */
[data-tooltip-position="right"]:after,
[data-tooltip-position="left"]:after {
top: 50%;
margin-top: -6px;
}
[data-tooltip-position="top"]:after {
bottom: 100%;
border-width: 6px 6px 0;
border-top-color: #000;
}
[data-tooltip-position="right"]:after {
left: 100%;
border-width: 6px 6px 6px 0;
border-right-color: #000;
}
[data-tooltip-position="bottom"]:after {
top: 100%;
border-width: 0 6px 6px;
border-bottom-color: #000;
}
[data-tooltip-position="left"]:after {
right: 100%;
border-width: 6px 0 6px 6px;
border-left-color: #000;
}
/* Show the tooltip when hovering */
[data-tooltip]:hover:before,
[data-tooltip]:hover:after {
display: block;
z-index: 50;
}
setTheArray([...theArray, newElement]);
is the simplest answer but be careful for the mutation of items in theArray. Use deep cloning of array items.
To diagnose what really triggers the error, I would first try to remove = 0
If the error is tripped, then most likely the declaration goes after the code.
If no error, then it may be related to a C-standard enforcement/compile flags OR ...something else.
In any case, declare the variable in the beginning of the current scope. You may then initialize it separately. Indeed, if this variable deserves its own scope - delimit its definition in {}.
If the OP could clarify the context, then a more directed response would follow.
Check out https://github.com/serratus/quaggaJS
"QuaggaJS is a barcode-scanner entirely written in JavaScript supporting real- time localization and decoding of various types of barcodes such as EAN, CODE 128, CODE 39, EAN 8, UPC-A, UPC-C, I2of5, 2of5, CODE 93 and CODABAR. The library is also capable of using getUserMedia to get direct access to the user's camera stream. Although the code relies on heavy image-processing even recent smartphones are capable of locating and decoding barcodes in real-time."
No, you can't change file upload input's text. But there are some tricks to overlay an image over the button.
import java.util.*;
public class ScannerExample {
public static void main(String args[]) {
int a;
String s;
Scanner scan = new Scanner(System.in);
System.out.println("enter a no");
a = scan.nextInt();
System.out.println("no is =" + a);
System.out.println("enter a string");
s = scan.next();
System.out.println("string is=" + s);
}
}
For posterity....I figured out how to get what I needed. Here it is in case it might be useful to somebody else.
$alist = "Name`tAccountName`tDescription`tEmailAddress`tLastLogonDate`tManager`tTitle`tDepartment`tCompany`twhenCreated`tAcctEnabled`tGroups`n"
$userlist = Get-ADUser -Filter * -Properties * | Select-Object -Property Name,SamAccountName,Description,EmailAddress,LastLogonDate,Manager,Title,Department,Company,whenCreated,Enabled,MemberOf | Sort-Object -Property Name
$userlist | ForEach-Object {
$grps = $_.MemberOf | Get-ADGroup | ForEach-Object {$_.Name} | Sort-Object
$arec = $_.Name,$_.SamAccountName,$_.Description,$_.EmailAddress,$_LastLogonDate,$_.Manager,$_.Title,$_.Department,$_.Company,$_.whenCreated,$_.Enabled
$aline = ($arec -join "`t") + "`t" + ($grps -join "`t") + "`n"
$alist += $aline
}
$alist | Out-File D:\Temp\ADUsers.csv
Google's support answer on serving ads over SSL and the grammar in the RFC itself would seem to indicate that you can space delimit the URLs. Not sure how well-supported this is in different browsers.
It's also important to note that MongoDB has the concept of "authentication database", which can be different than the database you are connecting to. For example, if you use the official Docker image for Mongo and specify the environment variables MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD, a user will be created on 'admin' database, which is probably not the database you want to use. In this case, you should specify parameters accordingly on your application.properties file using:
spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27017
spring.data.mongodb.authentication-database=admin
spring.data.mongodb.username=<username specified on MONGO_INITDB_ROOT_USERNAME>
spring.data.mongodb.password=<password specified on MONGO_INITDB_ROOT_PASSWORD>
spring.data.mongodb.database=<the db you want to use>
or you can set pointer-events:none
to your a
element and pointer-event:all
to your a:before
element, and then add hover CSS to a element
a{
pointer-events:none;
}
a:before{
pointer-events:all
}
a:hover:before{
background:blue;
}
private E a[];
private int size;
public GenSet(int elem)
{
size = elem;
a = (E[]) new E[size];
}
Once you have cloned the repo, you have everything: you can then hg up branchname
or hg up tagname
to update your working copy.
UP: hg up
is a shortcut of hg update
, which also has hg checkout
alias for people with git
habits.
One option would be to use the onResume of your first activity.
@Override
public void onResume()
{ // After a pause OR at startup
super.onResume();
//Refresh your stuff here
}
Or you can start Activity for Result:
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);
In secondActivity if you want to send back data:
Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(RESULT_OK,returnIntent);
finish();
if you don't want to return data:
Intent returnIntent = new Intent();
setResult(RESULT_CANCELED, returnIntent);
finish();
Now in your FirstActivity class write following code for onActivityResult()
method
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
//Update List
}
if (resultCode == RESULT_CANCELED) {
//Do nothing?
}
}
}//onActivityResult
Can't think of a only css solution, but couldn't you just had a div between those 2 and set in the css the properties to look like a line like shown in the image? If you are using divs as they were table cells this is a pretty simple solution to the problem
Set return type to Void
instead of void
and return null
// Modify existing method
public static Void displayInt(Integer i) {
System.out.println(i);
return null;
}
OR
// Or use Lambda
myForEach(theList, i -> {System.out.println(i);return null;});
I had a work tree with master and an another branch checked out in two different work folders.
PS C:\rhipheusADO\Build> git worktree list
C:/rhipheusADO/Build 7d32e6e [vyas-cr-core]
C:/rhipheusADO/Build-master 91d418c [master]
PS C:\rhipheusADO\Build> cd ..\Build-master\
PS C:\rhipheusADO\Build-master> git merge 7d32e6e #Or any other intermediary commits
Updating 91d418c..7d32e6e
Fast-forward
Pipeline/CR-MultiPool/azure-pipelines-auc.yml | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
PS C:\rhipheusADO\Build-master> git ls-remote
From https://myorg.visualstudio.com/HelloWorldApp/_git/Build
53060bac18f9d4e7c619e5170c436e6049b63f25 HEAD
7d32e6ec76d5a5271caebc2555d5a3a84b703954 refs/heads/vyas-cr-core
PS C:\rhipheusADO\Build-master> git merge 7d32e6ec76d5a5271caebc2555d5a3a84b703954
Already up-to-date
PS C:\rhipheusADO\Build> git push
Total 0 (delta 0), reused 0 (delta 0)
To https://myorg.visualstudio.com/HelloWorldApp/_git/Build
91d418c..7d32e6e master -> master
If you need to just merge the latest commit:
git merge origin/vyas-cr-core
git push
And is same as what I've always done:
git checkout master # This is needed if you're not using worktrees
git pull origin vyas-cr-core
git push
The following works as of April 2014. Delimiting each component of the URL with +
and &
for spaces and addition statements, respectively.
Full HTML:
<iframe src="http://maps.google.com/maps?q=Scottish+Rite+Hamilton+ON&loc:43.25911+-79.879494&z=15&output=embed"></iframe>
Broken down:
http://maps.google.com/maps?q=
where ?q= starts the general search, which I provide a venue, city, province info using +
for spaces.
Scottish+Rite+Hamilton+ON
Next the geo-data. Lat and lng.
&loc:43.25911+-79.879494
Zoom level
&z=15
Required for iframes:
&output=embed
I believe you need to create a file called __init__.py
in the Models directory so that python treats it as a module.
Then you can do:
from Models.user import User
You can include code in the __init__.py
(for instance initialization code that a few different classes need) or leave it blank. But it must be there.
If you know the cell number, then i would recommend using getDateCellValue() method Here's an example for the same that worked for me - java.util.Date date = row.getCell().getDateCellValue(); System.out.println(date);
you are probably doing it correct, only the dashboard shows just the higher ID taken, and thus the number of "active" nodes, relationships, although there are none. it is just informative.
to be sure you have an empty graph, run this command:
START n=node(*) return count(n);
START r=rel(*) return count(r);
if both give you 0, your deletion was succesfull.
Typical mainframe flow...
Input Disk/Tape/User (runtime) --> Job Control Language (JCL) --> Output Disk/Tape/Screen/Printer
| ^
v |
`--> COBOL Program --------'
Typical Linux flow...
Input Disk/SSD/User (runtime) --> sh/bash/ksh/zsh/... ----------> Output Disk/SSD/Screen/Printer
| ^
v |
`--> Python script --------'
| ^
v |
`--> awk script -----------'
| ^
v |
`--> sed script -----------'
| ^
v |
`--> C/C++ program --------'
| ^
v |
`--- Java program ---------'
| ^
v |
: :
Linux shells like sh/ksh/bash/... provide input/output/flow-control designation facilities much like the old mainframe Job Control Language... but on steroids! They are Turing complete languages in their own right while being optimized to efficiently pass data and control to and from other executing processes written in any language the O/S supports.
Most Linux applications, regardless what language the bulk of the program is written in, depend on shell scripts and Bash has become the most common. Clicking an icon on the desktop usually runs a short Bash script. That script, either directly or indirectly, knows where all the files needed are and sets variables and command line parameters, finally calling the program. That's a shell's simplest use.
Linux as we know it however would hardly be Linux without the thousands of shell scripts that startup the system, respond to events, control execution priorities and compile, configure and run programs. Many of these are quite large and complex.
Shells provide an infrastructure that lets us use pre-built components that are linked together at run time rather than compile time. Those components are free-standing programs in their own right that can be used alone or in other combinations without recompiling. The syntax for calling them is indistinguishable from that of a Bash builtin command, and there are in fact numerous builtin commands for which there is also a stand-alone executable on the system, often having additional options.
There is no language-wide difference between Python and Bash in performance. It entirely depends on how each is coded and which external tools are called.
Any of the well known tools like awk, sed, grep, bc, dc, tr, etc. will leave doing those operations in either language in the dust. Bash then is preferred for anything without a graphical user interface since it is easier and more efficient to call and pass data back from a tool like those with Bash than Python.
It depends on which programs the Bash shell script calls and their suitability for the subtask they are given whether the overall throughput and/or responsiveness will be better or worse than the equivalent Python. To complicate matters Python, like most languages, can also call other executables, though it is more cumbersome and thus not as often used.
One area where Python is the clear winner is user interface. That makes it an excellent language for building local or client-server applications as it natively supports GTK graphics and is far more intuitive than Bash.
Bash only understands text. Other tools must be called for a GUI and data passed back from them. A Python script is one option. Faster but less flexible options are the binaries like YAD, Zenity, and GTKDialog.
While shells like Bash work well with GUIs like Yad, GtkDialog (embedded XML-like interface to GTK+ functions), dialog, and xmessage, Python is much more capable and so better for complex GUI windows.
Building with shell scripts is like assembling a computer with off-the-shelf components the way desktop PCs are.
Building with Python, C++ or most any other language is more like building a computer by soldering the chips (libraries) and other electronic parts together the way smartphones are.
The best results are usually obtained by using a combination of languages where each can do what they do best. One developer calls this "polyglot programming".
printf
allows formatting with width specifiers. For example,
printf( "%-30s %s\n", "Starting initialization...", "Ok." );
You would use a negative width specifier to indicate left-justification because the default is to use right-justification.
It's a bad idea to count the td
elements to get the number of columns in your table, because td
elements can span multiple columns with colspan
.
Here's a simple solution using jquery:
var length = 0;_x000D_
$("tr:first").find("td,th").each(function(){_x000D_
var colspan = $(this).attr("colspan");_x000D_
if(typeof colspan !== "undefined" && colspan > 0){_x000D_
length += parseInt(colspan);_x000D_
}else{_x000D_
length += 1;_x000D_
}_x000D_
});_x000D_
_x000D_
$("div").html("number of columns: "+length);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<table>_x000D_
<tr>_x000D_
<td>single</td>_x000D_
<td colspan="2">double</td>_x000D_
<td>single</td>_x000D_
<td>single</td>_x000D_
</tr>_x000D_
</table>_x000D_
<div></div>
_x000D_
For a plain Javascript solution, see Emilio's answer.
For me, this worked:
rawText.replaceAll("(\\\\r\\\\n|\\\\n)", "\\\n");
Tip: use regex tester for quick testing without compiling in your environment
Mirroring a repository
Create a bare clone of the repository.
git clone --bare https://github.com/exampleuser/old-repository.git
Mirror-push to the new repository.
cd old-repository.git
git push --mirror https://github.com/exampleuser/new-repository.git
Remove the temporary local repository you created in step 1.
cd ..
rm -rf old-repository.git
Mirroring a repository that contains Git Large File Storage objects
Create a bare clone of the repository. Replace the example username with the name of the person or organization who owns the repository, and replace the example repository name with the name of the repository you'd like to duplicate.
git clone --bare https://github.com/exampleuser/old-repository.git
Navigate to the repository you just cloned.
cd old-repository.git
Pull in the repository's Git Large File Storage objects.
git lfs fetch --all
Mirror-push to the new repository.
git push --mirror https://github.com/exampleuser/new-repository.git
Push the repository's Git Large File Storage objects to your mirror.
git lfs push --all https://github.com/exampleuser/new-repository.git
Remove the temporary local repository you created in step 1.
cd ..
rm -rf old-repository.git
Above instruction comes from Github Help: https://help.github.com/articles/duplicating-a-repository/
I spent a while trying to figure this one out and here is what I did. I've broken it down very simply as that is what I needed.
Directly below your ckeditor text area, enter the upload file like this >>>>
<form action="welcomeeditupload.asp" method="post" name="deletechecked">
<div align="center">
<br />
<br />
<label></label>
<textarea class="ckeditor" cols="80" id="editor1" name="editor1" rows="10"><%=(rslegschedule.Fields.Item("welcomevar").Value)%></textarea>
<script type="text/javascript">
//<![CDATA[
CKEDITOR.replace( 'editor1',
{
filebrowserUploadUrl : 'updateimagedone.asp'
});
//]]>
</script>
<br />
<br />
<br />
<input type="submit" value="Update">
</div>
</form>
'and then add your upload file, here is mine which is written in ASP. If you're using PHP, etc. simply replace the ASP with your upload script but make sure the page outputs the same thing.
<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<%
if Request("CKEditorFuncNum")=1 then
Set Upload = Server.CreateObject("Persits.Upload")
Upload.OverwriteFiles = False
Upload.SetMaxSize 5000000, True
Upload.CodePage = 65001
On Error Resume Next
Upload.Save "d:\hosting\belaullach\senate\legislation"
Dim picture
For Each File in Upload.Files
Ext = UCase(Right(File.Path, 3))
If Ext <> "JPG" Then
If Ext <> "BMP" Then
Response.Write "File " & File.Path & " is not a .jpg or .bmp file." & "<BR>"
Response.write "You can only upload .jpg or .bmp files." & "<BR>" & "<BR>"
End if
Else
File.SaveAs Server.MapPath(("/senate/legislation") & "/" & File.fileName)
f1=File.fileName
End If
Next
End if
fnm="/senate/legislation/"&f1
imgop = "<html><body><script type=""text/javascript"">window.parent.CKEDITOR.tools.callFunction('1','"&fnm&"');</script></body></html>;"
'imgop="callFunction('1','"&fnm&"',"");"
Response.write imgop
%>
Create a login for the user
Drop and re-create the user, WITH the login you created.
There are other topics discussing how to replicate the permissions of your user. I recommend that you take the opportunity to define those permissions in a Role and call sp_addrolemember to add the user to the Role.
For loading a file, I like this a lot better
MemoryStream ms = new MemoryStream();
using (FileStream fs = File.OpenRead(file))
{
fs.CopyTo(ms);
}
An array doesn't have an add method. You assign a value to an element of the array with num[i]=value;
.
public static void main(String[] args) {
int[] num = new int[args.length];
for (int i=0; i < num.length; i++){
int neki = Integer.parseInt(args[i]);
num[i]=neki;
}
}
Thank you drifty0pine!
The first solution, it´s works!
[a relative link](../../some/dir/filename.md)
[Link to file in another dir on same drive](/another/dir/filename.md)
[Link to file in another dir on a different drive](/D:/dir/filename.md)
but I had need put more ../
until the folder where was my file, like this:
[FileToOpen](../../../../folderW/folderX/folderY/folderZ/FileToOpen.txt)
@cnicutar and @Pete Becker have already pointed out the possibility of using noskipws
/unsetting skipws
to read a character at a time without skipping over white space characters in the input.
Another possibility would be to use an istreambuf_iterator
to read the data. Along with this, I'd generally use a standard algorithm like std::transform
to do the reading and processing.
Just for example, let's assume we wanted to do a Caesar-like cipher, copying from standard input to standard output, but adding 3 to every upper-case character, so A
would become D
, B
could become E
, etc. (and at the end, it would wrap around so XYZ
converted to ABC
.
If we were going to do that in C, we'd typically use a loop something like this:
int ch;
while (EOF != (ch = getchar())) {
if (isupper(ch))
ch = ((ch - 'A') +3) % 26 + 'A';
putchar(ch);
}
To do the same thing in C++, I'd probably write the code more like this:
std::transform(std::istreambuf_iterator<char>(std::cin),
std::istreambuf_iterator<char>(),
std::ostreambuf_iterator<char>(std::cout),
[](int ch) { return isupper(ch) ? ((ch - 'A') + 3) % 26 + 'A' : ch;});
Doing the job this way, you receive the consecutive characters as the values of the parameter passed to (in this case) the lambda function (though you could use an explicit functor instead of a lambda if you preferred).
I have some virtual directories and I cannot use Directory methods. So, I made a simple split/join function for those interested. Not as safe though.
var splitResult = filePath.Split(new[] {'/', '\\'}, StringSplitOptions.RemoveEmptyEntries);
var newFilePath = Path.Combine(filePath.Take(splitResult.Length - 1).ToArray());
So, if you want to move 4 up, you just need to change the 1
to 4
and add some checks to avoid exceptions.
This is not an answer, but it's hard to read if I put results in comment.
I get these results with a Mac Pro (Westmere 6-Cores Xeon 3.33 GHz). I compiled it with clang -O3 -msse4 -lstdc++ a.cpp -o a
(-O2 get same result).
uint64_t size=atol(argv[1])<<20;
unsigned 41950110000 0.811198 sec 12.9263 GB/s
uint64_t 41950110000 0.622884 sec 16.8342 GB/s
uint64_t size=1<<20;
unsigned 41950110000 0.623406 sec 16.8201 GB/s
uint64_t 41950110000 0.623685 sec 16.8126 GB/s
I also tried to:
for
statement in reverse: for (uint64_t i=size/8;i>0;i-=4)
. This gives the same result and proves the compile is smart enough to not divide size by 8 every iteration (as expected).Here is my wild guess:
The speed factor comes in three parts:
code cache: uint64_t
version has larger code size, but this does not have an effect on my Xeon CPU. This makes the 64-bit version slower.
Instructions used. Note not only the loop count, but the buffer is accessed with a 32-bit and 64-bit index on the two versions. Accessing a pointer with a 64-bit offset requests a dedicated 64-bit register and addressing, while you can use immediate for a 32-bit offset. This may make the 32-bit version faster.
Instructions are only emitted on the 64-bit compile (that is, prefetch). This makes 64-bit faster.
The three factors together match with the observed seemingly conflicting results.
AndroidManifest.xml
example:
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name="com.pritesh.resourceidentifierexample.MainActivity"
android:label="@string/app_name"
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<!--<category android:name="android.intent.category.LAUNCHER"/>-->
</intent-filter>
</activity>
<activity-alias android:label="RED"
android:icon="@drawable/ic_android_red"
android:name="com.pritesh.resourceidentifierexample.MainActivity-Red"
android:enabled="true"
android:targetActivity="com.pritesh.resourceidentifierexample.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
<activity-alias android:label="GREEN"
android:icon="@drawable/ic_android_green"
android:name="com.pritesh.resourceidentifierexample.MainActivity-Green"
android:enabled="false"
android:targetActivity="com.pritesh.resourceidentifierexample.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
<activity-alias android:label="BLUE"
android:icon="@drawable/ic_android_blue"
android:name="com.pritesh.resourceidentifierexample.MainActivity-Blue"
android:enabled="false"
android:targetActivity="com.pritesh.resourceidentifierexample.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
</application>
Then follow below given code in MainActivity
:
ImageView imageView = (ImageView)findViewById(R.id.imageView);
int imageResourceId;
String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
int hours = new Time(System.currentTimeMillis()).getHours();
Log.d("DATE", "onCreate: " + hours);
getPackageManager().setComponentEnabledSetting(
getComponentName(), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
if(hours == 13)
{
imageResourceId = this.getResources().getIdentifier("ic_android_red", "drawable", this.getPackageName());
getPackageManager().setComponentEnabledSetting(
new ComponentName("com.pritesh.resourceidentifierexample", "com.pritesh.resourceidentifierexample.MainActivity-Red"),
PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
}else if(hours == 14)
{
imageResourceId = this.getResources().getIdentifier("ic_android_green", "drawable", this.getPackageName());
getPackageManager().setComponentEnabledSetting(
new ComponentName("com.pritesh.resourceidentifierexample", "com.pritesh.resourceidentifierexample.MainActivity-Green"),
PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
}else
{
imageResourceId = this.getResources().getIdentifier("ic_android_blue", "drawable", this.getPackageName());
getPackageManager().setComponentEnabledSetting(
new ComponentName("com.pritesh.resourceidentifierexample", "com.pritesh.resourceidentifierexample.MainActivity-Blue"),
PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
}
imageView.setImageResource(imageResourceId);
You can try to do something like this,
Getting a bitmap cache from a layout or a view by doing something like
First you gotta setDrawingCacheEnabled
to a layout(a linearlayout or relativelayout, or a view)
then
Bitmap bm = layout.getDrawingCache()
Then you do whatever you want with the bitmap. Either turning it into an image file, or send the bitmap's uri to somewhere else.
Unidirectional. Just add the inversedBy:(Foreign Column Name) to make it Bidirectional.
# config/yaml/ProductStore.dcm.yml
ProductStore:
type: entity
id:
product:
associationKey: true
store:
associationKey: true
fields:
status:
type: integer(1)
createdAt:
type: datetime
updatedAt:
type: datetime
manyToOne:
product:
targetEntity: Product
joinColumn:
name: product_id
referencedColumnName: id
store:
targetEntity: Store
joinColumn:
name: store_id
referencedColumnName: id
I hope it helps. See you.
You could run: mvn exec:exec -Dexec.args="arg1"
.
This will pass the argument arg1 to your program.
You should specify the main class fully qualified, for example, a Main.java that is in a package test would need
mvn exec:java -Dexec.mainClass=test.Main
By using the -f
parameter, as decribed here, you can also run it from other directories.
mvn exec:java -Dexec.mainClass=test.Main -f folder/pom.xm
For multiple arguments, simply separate them with a space as you would at the command line.
mvn exec:java -Dexec.mainClass=test.Main -Dexec.args="arg1 arg2 arg3"
For arguments separated with a space, you can group using 'argument separated with space'
inside the quotation marks.
mvn exec:java -Dexec.mainClass=test.Main -Dexec.args="'argument separated with space' 'another one'"
Is it because some culture format issue?
Yes. Your user must be in a culture where the time separator is a dot. Both ":" and "/" are interpreted in a culture-sensitive way in custom date and time formats.
How can I make sure the result string is delimited by colon instead of dot?
I'd suggest specifying CultureInfo.InvariantCulture
:
string text = dateTime.ToString("MM/dd/yyyy HH:mm:ss.fff",
CultureInfo.InvariantCulture);
Alternatively, you could just quote the time and date separators:
string text = dateTime.ToString("MM'/'dd'/'yyyy HH':'mm':'ss.fff");
... but that will give you "interesting" results that you probably don't expect if you get users running in a culture where the default calendar system isn't the Gregorian calendar. For example, take the following code:
using System;
using System.Globalization;
using System.Threading;
class Test
{
static void Main()
{
DateTime now = DateTime.Now;
CultureInfo culture = new CultureInfo("ar-SA"); // Saudi Arabia
Thread.CurrentThread.CurrentCulture = culture;
Console.WriteLine(now.ToString("yyyy-MM-ddTHH:mm:ss.fff"));
}
}
That produces output (on September 18th 2013) of:
11/12/1434 15:04:31.750
My guess is that your web service would be surprised by that!
I'd actually suggest not only using the invariant culture, but also changing to an ISO-8601 date format:
string text = dateTime.ToString("yyyy-MM-ddTHH:mm:ss.fff");
This is a more globally-accepted format - it's also sortable, and makes the month and day order obvious. (Whereas 06/07/2013 could be interpreted as June 7th or July 6th depending on the reader's culture.)
Use Lookupstage to decide whether to insert or update. Check this link for more info - http://beingoyen.blogspot.com/2010/03/ssis-how-to-update-instead-of-insert.html
Steps to do update:
Under Custom properties select SQLCOMMAND and insert update command ex:
UPDATE table1 SET col1 = ?, col2 = ? where id = ?
map columns in exact order from source to output as in update command
const char* charPointer = "Hello, World!\n";
std::string strFromChar;
strFromChar.append(charPointer);
std::cout<<strFromChar<<std::endl;
what have you tried? it's very simple:
String s = "/abc/def/ghfj.doc";
s.substring(s.lastIndexOf("/") + 1)
It depends on what concrete List class you are using. The abstract class AbstractCollection has a method called containsAll(Collection) that takes another collection ( a List is a collection) and:
Returns true if this collection contains all of the elements in the specified collection.
So if an ArrayList is being passed in you can call this method to see if they are exactly the same.
List foo = new ArrayList();
List bar = new ArrayList();
String str = "foobar";
foo.add(str);
bar.add(str);
foo.containsAll(bar);
The reason for containsAll() is because it iterates through the first list looking for the match in the second list. So if they are out of order equals() will not pick it up.
EDIT: I just want to make a comment here about the amortized running time of performing the various options being offered. Is running time important? Sure. Is it the only thing you should consider? No.
The cost of copying EVERY single element from your lists into other lists takes time, and it also takes up a good chunk of memory (effectively doubling the memory you are using).
So if memory in your JVM isn't a concern (which it should generally be) then you still need to consider the time it takes to copy every element from two lists into two TreeSets. Remember it is sorting every element as it enters them.
My final advice? You need to consider your data set and how many elements you have in your data set, and also how large each object in your data set is before you can make a good decision here. Play around with them, create one each way and see which one runs faster. It's a good exercise.
Here you go:
public static byte[] ConvertToByteArray(string str, Encoding encoding)
{
return encoding.GetBytes(str);
}
public static String ToBinary(Byte[] data)
{
return string.Join(" ", data.Select(byt => Convert.ToString(byt, 2).PadLeft(8, '0')));
}
// Use any sort of encoding you like.
var binaryString = ToBinary(ConvertToByteArray("Welcome, World!", Encoding.ASCII));
This is the most simple, and it worked for me:
In the values-21:
<resources>
<style name="AppTheme" parent="AppTheme.Base">
...
<item name="android:windowTranslucentStatus">true</item>
</style>
<dimen name="topMargin">25dp</dimen>
</resources>
In the values:
<resources>
<dimen name="topMargin">0dp</dimen>
</resources>
And set to your toolbar
android:layout_marginTop="@dimen/topMargin"
The following imports an external CSS file in a React component and outputs the CSS rules in the <head />
of the website.
npm install --save-dev style-loader
npm install --save-dev css-loader
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
]
}
}
import './path/to/file.css';
Try wrapping expression with:
$scope.$apply(function() {
$scope.foo.bar=true;
})
A BufferedReader constructor takes a reader as argument, not an InputStream. You should first create a Reader from your stream, like so:
Reader reader = new InputStreamReader(is);
BufferedReader br = new BufferedReader(reader);
Preferrably, you also provide a Charset or character encoding name to the StreamReader constructor. Since a stream just provides bytes, converting these to text means the encoding must be known. If you don't specify it, the system default is assumed.
The question is about VS 2008 Express.
Microsoft's web page for registering Visual Studio 2008 Express has been dead (404) for some time, so registering it is not possible.
Instead, as a workaround, you can temporarily remove the requirement to register VS2008Exp by deleting (or renaming) the registry key:
HKEY_CURRENT_USER/Software/Microsoft/VCExpress/9.0/Registration
To ensure that this is working beforehand, click Help -> register product within VS2008.
You should see text like
"You have not yet registered your copy of Visual C++ 2008 Express Edition. This product will run for 10 more days before you will be required to register it."
Close the application, delete that key, reopen, click help->register product.
The text should now say
"You have not yet registered your copy of Visual C++ 2008 Express Edition. This product will run for 30 more days before you will be required to register it."
So you have two options - delete that key manually every 30 days, or run it from a batch file that also contains a line like:
reg delete HKCU\Software\Microsoft\VCExpress\9.0\Registration /f
[Edit: User @i486 confirms on testing that this workaround works even after the expiration period has expired]
[Edit2: User @Wyatt8740 has a much more elegant way to prevent the value from reappearing.]
For those using the Angular CLI it's straightforward:
src/polyfills.ts
declare global {
interface Window {
myCustomFn: () => void;
}
}
my-custom-utils.ts
window.myCustomFn = function () {
...
};
If you're using IntelliJ, you also needed to change the following setting in the IDE before your new polyfills pick up:
> File
> Settings
> Languages & Frameworks
> TypeScript
> check 'Use TypeScript Service'.
I use such kind of a Map population thanks to Java 9. In my honest opinion, this approach provides more readability to the code.
public static void main(String[] args) {
Map<Integer, Point2D.Double> map = Map.of(
1, new Point2D.Double(1, 1),
2, new Point2D.Double(2, 2),
3, new Point2D.Double(3, 3),
4, new Point2D.Double(4, 4));
map.entrySet().forEach(System.out::println);
}
I suppose you don't want your textarea-content to be parsed as HTML. In this case, you can just set it as plaintext so the browser doesn't treat it as HTML and doesn't remove newlines No CSS or preprocessing required.
<script>_x000D_
function copycontent(){_x000D_
var content = document.getElementById('ta').value;_x000D_
document.getElementById('target').innerText = content;_x000D_
}_x000D_
</script>_x000D_
<textarea id='ta' rows='3'>_x000D_
line 1_x000D_
line 2_x000D_
line 3_x000D_
</textarea>_x000D_
<button id='btn' onclick='copycontent();'>_x000D_
Copy_x000D_
</button>_x000D_
<p id='target'></p>
_x000D_
Of course.
That is normal and sane behaviour.
Instead of closing and re-opening, you could rewind
the file.
Many of the answers above are opaque. In my opinion the author of this question simply wants to know where session variables are stored by default. According to this:https://canvas.seattlecentral.edu/courses/937693/pages/10-advanced-php-sessions they are simply stored on the server by default. Hopefully, others will find this contribution meaningful.
See this article on SQL Server Helper - SQL Server 2008 Date Format
We need to remember that the {% endif %}
comes after the {% else %}
.
So this is an example:
{% if someTest %}
<p> Something is True </p>
{% else %}
<p> Something is False </p>
{% endif %}
The setCustomValidity let you change the default validation message.Here is a simple exmaple of how to use it.
var age = document.getElementById('age');
age.form.onsubmit = function () {
age.setCustomValidity("This is not a valid age.");
};
Do you have a log4j configuration file ? Just reference it using
-Dlog4j.configuration={path to file}
where {path to file} should be prefixed with file:
Edit: If you are working with log4j2, you need to use
-Dlog4j.configurationFile={path to file}
Taken from answer https://stackoverflow.com/a/34001970/552525
If you know list comprehensions:
lines = [line[5:] for line in file.readlines() if line[:5] == "Path="]
If you have this problem when using an instaled version, when using setup.py
, make sure your module is included inside packages
setup(name='Your program',
version='0.7.0',
description='Your desccription',
packages=['foo', 'foo.bar'], # add `foo.bar` here
I read many topics about this error and the solution to me was to simply restart the postgres with:
sudo service postgresql restart
Which is not mentioned here.
Set the image to be the background of a div, then set the background size to be half the width of the image.
<div class="myimage"></div>
Then in your css, if your image is 300px x 200px:
.myimage {
background: url('images/myimage.png') no-repeat;
background-size:150px;
width:150px;
height:100px;
}