Go to pycharm then go to default setting --> pip (double click) -- pymsqldb..-- > install --after installing use in a program like this
import pymysql as MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","root","root","test" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute SQL query using execute() method.
cursor.execute("show tables")
# Fetch a single row using fetchone() method.
data = cursor.fetchall()
print (data)
# disconnect from server
db.close()
I had the same issue.. I thought I had branch named foo
when I try to:
git checkout foo
I was getting:
error: pathspec 'foo' did not match any file(s) known to git.
Then I tried the full branch name:
git checkout feature/foo
then worked for me.
A bin file is just the bits and bytes that go into the rom or a particular address from which you will run the program. You can take this data and load it directly as is, you need to know what the base address is though as that is normally not in there.
An elf file contains the bin information but it is surrounded by lots of other information, possible debug info, symbols, can distinguish code from data within the binary. Allows for more than one chunk of binary data (when you dump one of these to a bin you get one big bin file with fill data to pad it to the next block). Tells you how much binary you have and how much bss data is there that wants to be initialised to zeros (gnu tools have problems creating bin files correctly).
The elf file format is a standard, arm publishes its enhancements/variations on the standard. I recommend everyone writes an elf parsing program to understand what is in there, dont bother with a library, it is quite simple to just use the information and structures in the spec. Helps to overcome gnu problems in general creating .bin files as well as debugging linker scripts and other things that can help to mess up your bin or elf output.
This difference is due to the behavior of Promises more than fetch()
specifically.
When a .then()
callback returns an additional Promise
, the next .then()
callback in the chain is essentially bound to that Promise, receiving its resolve or reject fulfillment and value.
The 2nd snippet could also have been written as:
iterator.then(response =>
response.json().then(post => document.write(post.title))
);
In both this form and yours, the value of post
is provided by the Promise returned from response.json()
.
When you return a plain Object
, though, .then()
considers that a successful result and resolves itself immediately, similar to:
iterator.then(response =>
Promise.resolve({
data: response.json(),
status: response.status
})
.then(post => document.write(post.data))
);
post
in this case is simply the Object
you created, which holds a Promise
in its data
property. The wait for that promise to be fulfilled is still incomplete.
Most of these solutions depend on there being an odd number of items so that you can take the middle item and center it. What if you have an even number of items that you still want to be evenly distributed? Here's a more general solution. This category will evenly distribute any number of items along either the vertical or horizontal axis.
Example usage to vertically distribute 4 labels within their superview:
[self.view addConstraints:
[NSLayoutConstraint constraintsForEvenDistributionOfItems:@[label1, label2, label3, label4]
relativeToCenterOfItem:self.view
vertically:YES]];
NSLayoutConstraint+EvenDistribution.h
@interface NSLayoutConstraint (EvenDistribution)
/**
* Returns constraints that will cause a set of views to be evenly distributed horizontally
* or vertically relative to the center of another item. This is used to maintain an even
* distribution of subviews even when the superview is resized.
*/
+ (NSArray *) constraintsForEvenDistributionOfItems:(NSArray *)views
relativeToCenterOfItem:(id)toView
vertically:(BOOL)vertically;
@end
NSLayoutConstraint+EvenDistribution.m
@implementation NSLayoutConstraint (EvenDistribution)
+(NSArray *)constraintsForEvenDistributionOfItems:(NSArray *)views
relativeToCenterOfItem:(id)toView vertically:(BOOL)vertically
{
NSMutableArray *constraints = [NSMutableArray new];
NSLayoutAttribute attr = vertically ? NSLayoutAttributeCenterY : NSLayoutAttributeCenterX;
for (NSUInteger i = 0; i < [views count]; i++) {
id view = views[i];
CGFloat multiplier = (2*i + 2) / (CGFloat)([views count] + 1);
NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:view
attribute:attr
relatedBy:NSLayoutRelationEqual
toItem:toView
attribute:attr
multiplier:multiplier
constant:0];
[constraints addObject:constraint];
}
return constraints;
}
@end
In my opinion should the alt text always describe what is visible in the picture, for the case that the image is not displayed.
alt = text [CS] For user agents that cannot display images, forms, or applets, this attribute specifies alternate text. The language of the alternate text is specified by the lang attribute.
Simplified version for Oracle. If you don't want to create OracleParameter
var sql = "Update [User] SET FirstName = :p0 WHERE Id = :p1";
context.Database.ExecuteSqlCommand(sql, firstName, id);
You can try using set operations: MINUS
and INTERSECT
See here for more details:
O'Reilly - Mastering Oracle SQL - Chapter 7 - Set Operations
Try
SELECT EXTRACTVALUE(xmltype(testclob), '/DCResponse/ContextData/Field[@key="Decision"]')
FROM traptabclob;
Here is a sqlfiddle demo
Please note that adding the get_author
function would slow the list_display in the admin, because showing each person would make a SQL query.
To avoid this, you need to modify get_queryset
method in PersonAdmin, for example:
def get_queryset(self, request):
return super(PersonAdmin,self).get_queryset(request).select_related('book')
Before: 73 queries in 36.02ms (67 duplicated queries in admin)
After: 6 queries in 10.81ms
You'll see this in all the directives:
When you use brackets, it means you're passing a bindable property (a variable).
<a [routerLink]="routerLinkVariable"></a>
So this variable (routerLinkVariable) could be defined inside your class and it should have a value like below:
export class myComponent {
public routerLinkVariable = "/home"; // the value of the variable is string!
But with variables, you have the opportunity to make it dynamic right?
export class myComponent {
public routerLinkVariable = "/home"; // the value of the variable is string!
updateRouterLinkVariable(){
this.routerLinkVariable = '/about';
}
Where as without brackets you're passing string only and you can't change it, it's hard coded and it'll be like that throughout your app.
<a routerLink="/home"></a>
UPDATE :
The other speciality about using brackets specifically for routerLink is that you can pass dynamic parameters to the link you're navigating to:
So adding a new variable
export class myComponent {
private dynamicParameter = '129';
public routerLinkVariable = "/home";
Updating the [routerLink]
<a [routerLink]="[routerLinkVariable,dynamicParameter]"></a>
When you want to click on this link, it would become:
<a href="/home/129"></a>
Java 11+:
URI uri = URI.create("http://www.google.com");
HttpRequest request = HttpRequest.newBuilder(uri).build();
String content = HttpClient.newHttpClient().send(request, BodyHandlers.ofString()).body();
For list comprehension lovers, this will write all the key : value
pairs in new lines in dog.txt
my_dict = {'foo': [1,2], 'bar':[3,4]}
# create list of strings
list_of_strings = [ f'{key} : {my_dict[key]}' for key in my_dict ]
# write string one by one adding newline
with open('dog.txt', 'w') as my_file:
[ my_file.write(f'{st}\n') for st in list_of_strings ]
I too had this issue, I would copy the whole piece of code and put in Notepad, before pasting in Notepad, make sure you save the file type as ALL files and save the doc as utf-8 format. then you can paste your code and run, It should work. ?????? obiviously means unreadable characters.
Perhaps something like this for the first problem, you can simply access the columns by their names:
>>> df = pd.DataFrame(np.random.rand(4,5), columns = list('abcde'))
>>> df[df['c']>.5][['b','e']]
b e
1 0.071146 0.132145
2 0.495152 0.420219
For the second problem:
>>> df[df['c']>.5][['b','e']].values
array([[ 0.07114556, 0.13214495],
[ 0.49515157, 0.42021946]])
debug_backtrace()
Just invert the indexes' order like this:
for (int j = 0; j<array[0].length; j++){
for (int i = 0; i<array.length; i++){
because all rows has same amount of columns you can use this condition j < array[0].lengt in first for condition due to the fact you are iterating over a matrix
This type of Notification is deprecated as seen from documents:
@java.lang.Deprecated
public Notification(int icon, java.lang.CharSequence tickerText, long when) { /* compiled code */ }
public Notification(android.os.Parcel parcel) { /* compiled code */ }
@java.lang.Deprecated
public void setLatestEventInfo(android.content.Context context, java.lang.CharSequence contentTitle, java.lang.CharSequence contentText, android.app.PendingIntent contentIntent) { /* compiled code */ }
Better way
You can send a notification like this:
// prepare intent which is triggered if the
// notification is selected
Intent intent = new Intent(this, NotificationReceiver.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
// build notification
// the addAction re-use the same intent to keep the example short
Notification n = new Notification.Builder(this)
.setContentTitle("New mail from " + "[email protected]")
.setContentText("Subject")
.setSmallIcon(R.drawable.icon)
.setContentIntent(pIntent)
.setAutoCancel(true)
.addAction(R.drawable.icon, "Call", pIntent)
.addAction(R.drawable.icon, "More", pIntent)
.addAction(R.drawable.icon, "And more", pIntent).build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, n);
Best way
Code above needs minimum API level 11 (Android 3.0).
If your minimum API level is lower than 11, you should you use support library's NotificationCompat class like this.
So if your minimum target API level is 4+ (Android 1.6+) use this:
import android.support.v4.app.NotificationCompat;
-------------
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.mylogo)
.setContentTitle("My Notification Title")
.setContentText("Something interesting happened");
int NOTIFICATION_ID = 12345;
Intent targetIntent = new Intent(this, MyFavoriteActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
NotificationManager nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nManager.notify(NOTIFICATION_ID, builder.build());
You are not creating datetime index properly,
format = '%Y-%m-%d %H:%M:%S'
df['Datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'], format=format)
df = df.set_index(pd.DatetimeIndex(df['Datetime']))
you have to rename each column
SELECT col1 as MyCol1,
col2 as MyCol2,
.......
FROM `foobar`
Simple, you just open klik file -> import -> General -> existing project into workspace -> browse file in your directory.
(I'am used Eclipse Mars)
You can Enable DBMS_OUTPUT and set the buffer size. The buffer size can be between 1 and 1,000,000.
dbms_output.enable(buffer_size IN INTEGER DEFAULT 20000);
exec dbms_output.enable(1000000);
Check this
EDIT
As per the comment posted by Frank and Mat, you can also enable it with Null
exec dbms_output.enable(NULL);
buffer_size : Upper limit, in bytes, the amount of buffered information. Setting buffer_size to NULL specifies that there should be no limit. The maximum size is 1,000,000, and the minimum is 2,000 when the user specifies buffer_size (NOT NULL).
The DELIMITER statement changes the standard delimiter which is semicolon ( ;) to another. The delimiter is changed from the semicolon( ;) to double-slashes //.
Why do we have to change the delimiter?
Because we want to pass the stored procedure, custom functions etc. to the server as a whole rather than letting mysql tool to interpret each statement at a time.
These three commands have entirely different purposes. They are not even remotely similar.
git revert
This command creates a new commit that undoes the changes from a previous commit. This command adds new history to the project (it doesn't modify existing history).
git checkout
This command checks-out content from the repository and puts it in your work tree. It can also have other effects, depending on how the command was invoked. For instance, it can also change which branch you are currently working on. This command doesn't make any changes to the history.
git reset
This command is a little more complicated. It actually does a couple of different things depending on how it is invoked. It modifies the index (the so-called "staging area"). Or it changes which commit a branch head is currently pointing at. This command may alter existing history (by changing the commit that a branch references).
If a commit has been made somewhere in the project's history, and you later decide that the commit is wrong and should not have been done, then git revert
is the tool for the job. It will undo the changes introduced by the bad commit, recording the "undo" in the history.
If you have modified a file in your working tree, but haven't committed the change, then you can use git checkout
to checkout a fresh-from-repository copy of the file.
If you have made a commit, but haven't shared it with anyone else and you decide you don't want it, then you can use git reset
to rewrite the history so that it looks as though you never made that commit.
These are just some of the possible usage scenarios. There are other commands that can be useful in some situations, and the above three commands have other uses as well.
Any constructor
exposes a property name
, which is the function name. You access the constructor
via an instance (using new
) or a prototype
:
function Person() {
console.log(this.constructor.name); //Person
}
var p = new Person();
console.log(p.constructor.name); //Person
console.log(Person.prototype.constructor.name); //Person
Going off of @Rok Kralj answer (best IMO) to check if any of needles exist in the haystack, you can use (bool)
instead of !!
which sometimes can be confusing during code review.
function in_array_any($needles, $haystack) {
return (bool)array_intersect($needles, $haystack);
}
echo in_array_any( array(3,9), array(5,8,3,1,2) ); // true, since 3 is present
echo in_array_any( array(4,9), array(5,8,3,1,2) ); // false, neither 4 nor 9 is present
https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
var unixTimeZero = Date.parse('01 Jan 1970 00:00:00 GMT');
var javaScriptRelease = Date.parse('04 Dec 1995 00:12:00 GMT');
console.log(unixTimeZero);
// expected output: 0
console.log(javaScriptRelease);
// expected output: 818035920000
Take a look at the Collections.sort(List<T> list)
.
You can simply remove the first element, sort the list and then add it back again.
Thanks, Valter Henrique, with your tip i managed to realise, that i simply entered incorrect path to this image. In one of my tries i use
String pathToImageSortBy = "resources/testDataIcons/filling.png";
ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));
But correct way was use name of my project in path to resource
String pathToImageSortBy = "nameOfProject/resources/testDataIcons/filling.png";
ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));
<form action="myController/myAction" method="POST">
<input type="text" name="valueINeed" />
<input type="submit" value="View Report" />
</form>
controller:
[HttpPost]
public ActionResult myAction(string valueINeed)
{
//....
}
If you're using AForge.NET:
using(var croppedBitmap = new Crop(new Rectangle(10, 10, 10, 10)).Apply(bitmap))
{
// ...
}
The simplest way to do this is to add the .config
file in the deployment section on your unit test.
To do so, open the .testrunconfig
file from your Solution Items. In the Deployment section, add the output .config
files from your project's build directory (presumably bin\Debug
).
Anything listed in the deployment section will be copied into the test project's working folder before the tests are run, so your config-dependent code will run fine.
Edit: I forgot to add, this will not work in all situations, so you may need to include a startup script that renames the output .config
to match the unit test's name.
Centering floats is easy. Just use the style for container:
.pagination{ display: table; margin: 0 auto; }
change the margin for floating elements:
.pagination a{ margin: 0 2px; }
or
.pagination a{ margin-left: 3px; }
.pagination a.first{ margin-left: 0; }
and leave the rest as it is.
It's the best solution for me to display things like menus or pagination.
Strengths:
cross-browser for any elements (blocks, list-items etc.)
simplicity
Weaknesses:
@arnaud576875 Using inline-block elements will work great (cross-browser) in this case as pagination contains just anchors (inline), no list-items or divs:
Strengths:
Weknesses:
gaps between inline-block elements - it works the same way as a space between words. It may cause some troubles calculating the width of the container and styling margins. Gaps width isn't constant but it's browser specific (4-5px). To get rid of this gaps I would add to arnaud576875 code (not fully tested):
.pagination{ word-spacing: -1em; }
.pagination a{ word-spacing: .1em; }
it won't work in IE6/7 on block and list-items elements
The definition of an inline
function doesn't have to be in a header file but, because of the one definition rule (ODR) for inline functions, an identical definition for the function must exist in every translation unit that uses it.
The easiest way to achieve this is by putting the definition in a header file.
If you want to put the definition of a function in a single source file then you shouldn't declare it inline
. A function not declared inline
does not mean that the compiler cannot inline the function.
Whether you should declare a function inline
or not is usually a choice that you should make based on which version of the one definition rules it makes most sense for you to follow; adding inline
and then being restricted by the subsequent constraints makes little sense.
You can call a reset function before appending. Something like this:
function resetNewReviewBoardForm() {
$("#Description").val('');
$("#PersonName").text('');
$("#members").empty(); //this one what worked in my case
$("#EmailNotification").val('False');
}
I use this (again not region independent (UK))
set bklog=%date:~6,4%-%date:~3,2%-%date:~0,2%_%time:~0,2%%time:~3,2%
Another GCD alternative is a barrier:
dispatch_queue_t queue = dispatch_queue_create("com.company.app.queue", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
NSLog(@"start one!\n");
sleep(4);
NSLog(@"end one!\n");
});
dispatch_async(queue, ^{
NSLog(@"start two!\n");
sleep(2);
NSLog(@"end two!\n");
});
dispatch_barrier_async(queue, ^{
NSLog(@"Hi, I'm the final block!\n");
});
Just create a concurrent queue, dispatch your two blocks, and then dispatch the final block with barrier, which will make it wait for the other two to finish.
If compareParents(s1, s2) == -1
then compareParents(s2, s1) == 1
is expected. With your code it's not always true.
Specifically if s1.getParent() == s2 && s2.getParent() == s1
.
It's just one of the possible problems.
I had the same error message and, like you mentioned, it was due to different versions of the Newtonsoft.Json.dll being referenced.
Some projects in my MVC solution used the NuGet package for version 4 of that dll.
I then added a NuGet package (for Salesforce in my case) that brought Newtonsoft.Json version 6 with it as a dependency to one of the projects. That was what triggered the problem for me.
To clean things up, I used the Updates section in the NuGet Package Manager for the solution (off Tools menu or solution right-click) to update the Json.Net package throughout the solution so it was the same version for all projects.
After that I just checked the App Config files to ensure any binding redirect lines were going to my chosen version as below.
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
What you should get as output with this code is:
Array ()
... this is exactly how you get just one row, you don't need a while loop. Are you sure you're printing the right variable?
Ran into the similar problem not exactly the same, A case of Database already existed the issue was solved by following code.
<add name="DefaultConnection" connectionString="Data Source=.;AttachDbFilename=|DataDirectory|\aspnet-EjournalParsing-20180925054839.mdf;Initial Catalog=aspnet-EjournalParsing-20180925054839;Integrated Security=True"_x000D_
providerName="System.Data.SqlClient" />
_x000D_
While several answers are similar, I still had an issue - the user would click the button several times, playing the audio over itself (either it was clicked by accident or they were just 'playing'....)
An easy fix:
var music = new Audio();
function playMusic(file) {
music.pause();
music = new Audio(file);
music.play();
}
Setting up the audio on load allowed 'music' to be paused every time the function is called - effectively stopping the 'noise' even if they user clicks the button several times (and there is also no need to turn off the button, though for user experience it may be something you want to do).
Neither submit()
nor click()
is good enough. However, it works fine if you follow it with an ENTER key:
search_form = driver.find_element_by_id(elem_id)
search_form.send_keys(search_string)
search_form.click()
from selenium.webdriver.common.keys import Keys
search_form.send_keys(Keys.ENTER)
Tested on Mac 10.11, python 2.7.9, Selenium 2.53.5. This runs in parallel, meaning returns after entering the ENTER key, doesn't wait for page to load.
On newer versions of Symfony2 (using a parameters.yml
instead of parameters.ini
), you can store objects or arrays instead of key-value pairs, so you can manage your globals this way:
config.yml (edited only once):
# app/config/config.yml
twig:
globals:
project: %project%
parameters.yml:
# app/config/parameters.yml
project:
name: myproject.com
version: 1.1.42
And then in a twig file, you can use {{ project.version }}
or {{ project.name }}
.
Note: I personally dislike adding things to app
, just because that's the Symfony's variable and I don't know what will be stored there in the future.
I'll have a go at this complicated subject.
The origin itself is the name of a host (scheme, hostname, and port) i.g. https://www.google.com
or could be a locally opened file file://
etc.. It is where something (i.g. a web page) originated from. When you open your web browser and go to https://www.google.com
, the origin of the web page that is displayed to you is https://www.google.com
. You can see this in Chrome Dev Tools under Security
:
The same applies for if you open a local HTML file via your file explorer (which is not served via a server):
When you open your browser and go to https://website.com
, that website will have the origin of https://website.com
. This website will most likely only fetch images, icons, js files and do API calls towards https://website.com
, basically it is calling the same server as it was served from. It is doing calls to the same origin.
If you open your web browser and open a local HTML file and in that html file there is javascript which wants to do a request to google for example, you get the following error:
The same-origin policy tells the browser to block cross-origin requests. In this instance origin null
is trying to do a request to https://www.google.com
(a cross-origin request). The browser will not allow this because of the CORS Policy which is set and that policy is that cross-origin requests is not allowed.
Same applies for if my page was served from a server on localhost:
If we host our own localhost API server running on localhost:3000 with the following code:
const express = require('express')
const app = express()
app.use(express.static('public'))
app.get('/hello', function (req, res) {
// res.header("Access-Control-Allow-Origin", "*");
res.send('Hello World');
})
app.listen(3000, () => {
console.log('alive');
})
And open a HTML file (that does a request to the localhost:3000 server) directory from the file explorer the following error will happen:
Since the web page was not served from the localhost server on localhost:3000 and via the file explorer the origin is not the same as the server API origin, hence a cross-origin request is being attempted. The browser is stopping this attempt due to CORS Policy.
But if we uncomment the commented line:
const express = require('express')
const app = express()
app.use(express.static('public'))
app.get('/hello', function (req, res) {
res.header("Access-Control-Allow-Origin", "*");
res.send('Hello World');
})
app.listen(3000, () => {
console.log('alive');
})
And now try again:
It works, because the server which sends the HTTP response included now a header stating that it is ok for cross-origin requests to happen to the server, this means the browser will let it happen, hence no error.
Following is taken from: https://web.dev/cross-origin-resource-sharing/#how-does-cors-work
Remember, the same-origin policy tells the browser to block cross-origin requests. When you want to get a public resource from a different origin, the resource-providing server needs to tell the browser "This origin where the request is coming from can access my resource". The browser remembers that and allows cross-origin resource sharing.
Step 1: client (browser) request When the browser is making a cross-origin request, the browser adds an Origin header with the current origin (scheme, host, and port).
Step 2: server response On the server side, when a server sees this header, and wants to allow access, it needs to add an Access-Control-Allow-Origin header to the response specifying the requesting origin (or * to allow any origin.)
Step 3: browser receives response When the browser sees this response with an appropriate Access-Control-Allow-Origin header, the browser allows the response data to be shared with the client site.
Here is another good answer, more detailed as to what is happening: https://stackoverflow.com/a/10636765/1137669
Here is what I learned: PYTHONPATH is a directory to add to the Python import search path "sys.path", which is made up of current dir. CWD, PYTHONPATH, standard and shared library, and customer library. For example:
% python3 -c "import sys;print(sys.path)"
['',
'/home/username/Documents/DjangoTutorial/mySite',
'/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages']
where the first path '' denotes the current dir., the 2nd path is via
%export PYTHONPATH=/home/username/Documents/DjangoTutorial/mySite
which can be added to ~/.bashrc to make it permanent, and the rest are Python standard and dynamic shared library plus third-party library such as django.
As said not to mess with PYTHONHOME, even setting it to '' or 'None' will cause python3 shell to stop working:
% export PYTHONHOME=''
% python3
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ModuleNotFoundError: No module named 'encodings'
Current thread 0x00007f18a44ff740 (most recent call first):
Aborted (core dumped)
Note that if you start a Python script, the CWD will be the script's directory. For example:
username@bud:~/Documents/DjangoTutorial% python3 mySite/manage.py runserver
==== Printing sys.path ====
/home/username/Documents/DjangoTutorial/mySite # CWD is where manage.py resides
/usr/lib/python3.6
/usr/lib/python3.6/lib-dynload
/usr/local/lib/python3.6/dist-packages
/usr/lib/python3/dist-packages
You can also append a path to sys.path at run-time: Suppose you have a file Fibonacci.py in ~/Documents/Python directory:
username@bud:~/Documents/DjangoTutorial% python3
>>> sys.path.append("/home/username/Documents")
>>> print(sys.path)
['', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages',
'/home/username/Documents']
>>> from Python import Fibonacci as fibo
or via
% PYTHONPATH=/home/username/Documents:$PYTHONPATH
% python3
>>> print(sys.path)
['',
'/home/username/Documents', '/home/username/Documents/DjangoTutorial/mySite',
'/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages']
>>> from Python import Fibonacci as fibo
Yes, #id
selectors combined with a multiple selector (comma) is perfectly valid in both jQuery and CSS.
However, for your example, since <script>
comes before the elements, you need a document.ready
handler, so it waits until the elements are in the DOM to go looking for them, like this:
<script>
$(function() {
$("#segement1,#segement2,#segement3").hide()
});
</script>
<div id="segement1"></div>
<div id="segement2"></div>
<div id="segement3"></div>
Don't know who looks at your file, but if you open it in wordpad instead of notepad, the linebreaks will show correct. In case you're using a special file extension, associate it with wordpad and you're done with it. Or use any other more advanced text editor.
your thinking about this program below
#include <stdio.h>
#include <string.h>
int main ()
{
char str[][5] = { "R2D2" , "C3PO" , "R2A6" };
int n;
puts ("Looking for R2 astromech droids...");
for (n=0 ; n<3 ; n++)
if (strncmp (str[n],"R2xx",2) == 0)
{
printf ("found %s\n",str[n]);
}
return 0;
}
//outputs:
//
//Looking for R2 astromech droids...
//found R2D2
//found R2A6
when you should be thinking about inputting something into an array & then use strcmp functions like the program above ... check out a modified program below
#include <iostream>
#include<cctype>
#include <string.h>
#include <string>
using namespace std;
int main()
{
int Students=2;
int Projects=3, Avg2=0, Sum2=0, SumT2=0, AvgT2=0, i=0, j=0;
int Grades[Students][Projects];
for(int j=0; j<=Projects-1; j++){
for(int i=0; i<=Students; i++) {
cout <<"Please give grade of student "<< j <<"in project "<< i << ":";
cin >> Grades[j][i];
}
Sum2 = Sum2 + Grades[i][j];
Avg2 = Sum2/Students;
}
SumT2 = SumT2 + Avg2;
AvgT2 = SumT2/Projects;
cout << "avg is : " << AvgT2 << " and sum : " << SumT2 << ":";
return 0;
}
change to string except it only reads 1 input and throws the rest out maybe need two for loops and two pointers
#include <cstring>
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
int main()
{
char name[100];
//string userInput[26];
int i=0, n=0, m=0;
cout<<"your name? ";
cin>>name;
cout<<"Hello "<<name<< endl;
char *ptr=name;
for (i = 0; i < 20; i++)
{
cout<<i<<" "<<ptr[i]<<" "<<(int)ptr[i]<<endl;
}
int length = 0;
while(name[length] != '\0')
{
length++;
}
for(n=0; n<4; n++)
{
if (strncmp(ptr, "snit", 4) == 0)
{
cout << "you found the snitch " << ptr[i];
}
}
cout<<name <<"is"<<length<<"chars long";
}
You can call tail +[line number] [file]
and pipe it to grep -n
which shows the line number:
tail +[line number] [file] | grep -n /regex/
The only problem with this method is the line numbers reported by grep -n
will be [line number] - 1
less than the actual line number in [file]
.
I downloaded a different installer "SQL Server 2014 Express with Advanced Services" and found Instance Features in it. Thanks for Alberto Solano's answer, it was really helpful.
My first installer was "SQL Server 2014 Express". It installed only SQL Management Studio and tools without Instance features. After installation "SQL Server 2014 Express with Advanced Services" my LocalDB is now alive!!!
Here is the syntax to create a trigger:
CREATE TRIGGER trigger_name
ON { table | view }
[ WITH ENCRYPTION ]
{
{ { FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }
[ WITH APPEND ]
[ NOT FOR REPLICATION ]
AS
[ { IF UPDATE ( column )
[ { AND | OR } UPDATE ( column ) ]
[ ...n ]
| IF ( COLUMNS_UPDATED ( ) { bitwise_operator } updated_bitmask )
{ comparison_operator } column_bitmask [ ...n ]
} ]
sql_statement [ ...n ]
}
}
If you want to use On Update you only can do it with the IF UPDATE ( column )
section. That's not possible to do what you are asking.
Just write:
min-height: xxx;
overflow: hidden;
then div
will automatically take the height of the content.
https://jsfiddle.net/sudheernunna/tug98nfm/1/
var days = {};
days["monday"] = true;
days["tuesday"] = true;
days["wednesday"] = false;
days["thursday"] = true;
days["friday"] = false;
days["saturday"] = true;
days["sunday"] = false;
var userfalse=0,usertrue=0;
for(value in days)
{
if(days[value]){
usertrue++;
}else{
userfalse++;
}
console.log(days[value]);
}
alert("false",userfalse);
alert("true",usertrue);
I had the same problem, I think in Chart.js 2.x.x the approach is slightly different like below.
ticks: {
callback: function(label, index, labels) {
return label/1000+'k';
}
}
More in details
var options = {
scales: {
yAxes: [
{
ticks: {
callback: function(label, index, labels) {
return label/1000+'k';
}
},
scaleLabel: {
display: true,
labelString: '1k = 1000'
}
}
]
}
}
You can also customize the card theme globally with ThemeData.cardTheme
:
MaterialApp(
title: 'savvy',
theme: ThemeData(
cardTheme: CardTheme(
shape: RoundedRectangleBorder(
borderRadius: const BorderRadius.all(
Radius.circular(8.0),
),
),
),
// ...
You can get this error in the context of, e.g. a Travis build that, by default, checks code out with git clone --depth=50 --branch=master
. To the best of my knowledge, you can control --depth
via .travis.yml
but not the --branch
. Since that results in only a single branch being tracked by the remote, you need to independently update the remote to track the desired remote's refs.
Before:
$ git branch -a
* master
remotes/origin/HEAD -> origin/master
remotes/origin/master
The fix:
$ git remote set-branches --add origin branch-1
$ git remote set-branches --add origin branch-2
$ git fetch
After:
$ git branch -a
* master
remotes/origin/HEAD -> origin/master
remotes/origin/branch-1
remotes/origin/branch-2
remotes/origin/master
Run the following code:
du -sh /var/log/mysql
Perhaps mysql binary logs filled the memory, If so, follow the removal of old logs and restart the server. Also add in my.cnf:
expire_logs_days = 3
I think the true answer is that jQuery was developed long before querySelector/querySelectorAll
became available in all major browsers.
Initial release of jQuery was in 2006. In fact, even jQuery was not the first which implemented CSS selectors.
IE was the last browser to implement querySelector/querySelectorAll
. Its 8th version was released in 2009.
So now, DOM elements selectors is not the strongest point of jQuery anymore. However, it still has a lot of goodies up its sleeve, like shortcuts to change element's css and html content, animations, events binding, ajax.
Note: If you have broad knowledge already about rebase then use below one liner for fast rebase. Solution: Assuming you are on your working branch and you are the only person working on it.
git fetch && git rebase origin/master
Resolve any conflicts, test your code, commit and push new changes to remote branch.
~: For noobs :~
The following steps might help anyone who are new to git rebase
and wanted to do it without hassle
Step 1: Assuming that there are no commits and changes to be made on YourBranch at this point. We are visiting YourBranch.
git checkout YourBranch
git pull --rebase
What happened? Pulls all changes made by other developers working on your branch and rebases your changes on top of it.
Step 2: Resolve any conflicts that presents.
Step 3:
git checkout master
git pull --rebase
What happened? Pulls all the latest changes from remote master and rebases local master on remote master. I always keep remote master clean and release ready! And, prefer only to work on master or branches locally. I recommend in doing this until you gets a hand on git changes or commits. Note: This step is not needed if you are not maintaining local master, instead you can do a fetch and rebase remote master directly on local branch directly. As I mentioned in single step in the start.
Step 4: Resolve any conflicts that presents.
Step 5:
git checkout YourBranch
git rebase master
What happened? Rebase on master happens
Step 6: Resolve any conflicts, if there are conflicts. Use git rebase --continue
to continue rebase after adding the resolved conflicts. At any time you can use git rebase --abort
to abort the rebase.
Step 7:
git push --force-with-lease
What happened? Pushing changes to your remote YourBranch. --force-with-lease
will make sure whether there are any other incoming changes for YourBranch from other developers while you rebasing. This is super useful rather than force push. In case any incoming changes then fetch them to update your local YourBranch before pushing changes.
Why do I need to push changes? To rewrite the commit message in remote YourBranch after proper rebase or If there are any conflicts resolved? Then you need to push the changes you resolved in local repo to the remote repo of YourBranch
Yahoooo...! You are succesfully done with rebasing.
You might also be looking into doing:
git checkout master
git merge YourBranch
When and Why? Merge your branch into master if done with changes by you and other co-developers. Which makes YourBranch up-to-date with master when you wanted to work on same branch later.
~: (?o 3 o)? rebase :~
Set the listview adapter to "simple_list_item_multiple_choice"
ArrayAdapter<String> adapter;
List<String> values; // put values in this
//Put in listview
adapter = new ArrayAdapter<UserProfile>(
this,
android.R.layout.simple_list_item_multiple_choice,
values);
setListAdapter(adapter);
Basically comes down to Windows standard: \r\n and Unix based systems using: \n
Visual Studio 2010 has the "Navigate To" command, which might be what you are looking for. The default keyboard shortcut is CTRL + ,. Here is an overview of some of the options for navigating in Visual Studio 2010.
Make sure that your project is targeting the .NET framework 4.0. Visual Studio 2010 supports .NET 3.5 framework target also, but .NET 3.5 does not support the dynamic
keyword.
You can adjust the framework version in the project properties. See http://msdn.microsoft.com/en-us/library/bb398202.aspx for more info.
I did it using String map (if you're working with String Map).
for (Object obj : dados.entrySet()) {
Map.Entry<String, String> entry = (Map.Entry) obj;
System.out.print("Key: " + entry.getKey());
System.out.println(", Value: " + entry.getValue());
}
You might try to use CSS transforms for indenting a whole tr:
tr.indent {
-webkit-transform: translate(20px,0);
-moz-transform: translate(20px,0);
}
I think this is a valid solution. Seems to work fine in Firefox 16, Chrome 23 and Safari 6 on my OSX.
If you are receiving this error in a WebSphere container, then make sure you set your Apps class loading policy correctly. I had to change mine from the default to 'parent last' and also ‘Single class loader for application’ for the WAR policy. This is because in my case the commons-io*.jar was packaged with in the application, so it had to be loaded first.
You can also try this.
File file = new File(strDirectoy,imgname);
OutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
usernames = []
for i in names:
if " " in i:
i = i.replace(" ", "_")
print(i)
Output: Joey_Tribbiani Monica_Geller Chandler_Bing Phoebe_Buffay
public static void main(String[] args){
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1.equals(s2));
////
System.out.println(s1 == s2);
System.out.println("-----------------------------");
String s3 = "hello";
String s4 = "hello";
System.out.println(s3.equals(s4));
////
System.out.println(s3 == s4);
}
Here in this code u can campare the both '==' and '.equals'
here .equals is used to compare the reference objects and '==' is used to compare state of objects..
This will return the time-Only
For SQL Server:
SELECT convert(varchar(8), getdate(), 108)
Explanation:
getDate()
is giving current date and time.
108
is formatting/giving us the required portion i.e time in this case.
varchar(8)
gives us the number of characters from that portion.
Like:
If you wrote varchar(7)
there, it will give you 00:00:0
If you wrote varchar(6)
there, it will give you 00:00:
If you wrote varchar(15)
there, it will still give you 00:00:00
because it is giving output of just time portion.
SQLFiddle Demo
For MySQL:
SELECT DATE_FORMAT(NOW(), '%H:%i:%s')
Another alternative is using SDKMAN! See https://wimdeblauwe.wordpress.com/2018/09/26/switching-between-jdk-8-and-11-using-sdkman/
First install SDKMAN: https://sdkman.io/install and then...
sdk install java 8.0.181-oracle
sdk install java 11.0.0-open
To switch:
sdk use java 8.0.181-oracle
sdk use java 11.0.0-open
To set a default:
sdk default java 8.0.181-oracle
sdk default java 11.0.0-open
I was needing to find out just which version of .NET framework I had on my computer, and all I did was go to the control panel and select the "Uninstall a Program" option. After that, I sorted the programs by name, and found Microsoft .NET Framework 4 Client Profile.
Example java code:
//DATA//
//get from: https://console.aws.amazon.com/iam/home?#/security_credentials -> Access keys (access key ID and secret access key) -> Generate key if not exists
String accessKey;
String secretKey;
Regions region = Regions.AP_SOUTH_1; //get from "https://ap-south-1.console.aws.amazon.com/lambda/" > your function > ARN at top right
//CODE//
AWSLambda awsLambda = AWSLambdaClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey)))
.withRegion(region)
.build();
List<FunctionConfiguration> functionList= awsLambda.listFunctions().getFunctions();
for (FunctionConfiguration functConfig : functionList) {
System.out.println("FunctionName="+functConfig.getFunctionName());
}
A BusyBox port for Windows has both a diff and patch command, but they only support unified format.
Try to add the path to tnsnames.ora to the config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<oracle.manageddataaccess.client>
<version number="4.112.3.60">
<settings>
<setting name="TNS_ADMIN" value="C:\oracle\product\10.2.0\client_1\NETWORK\ADMIN\" />
</settings>
</version>
</oracle.manageddataaccess.client>
</configuration>
Try this JQuery code to dynamically include form, field, and delete/remove behavior:
$(document).ready(function() {_x000D_
var max_fields = 10;_x000D_
var wrapper = $(".container1");_x000D_
var add_button = $(".add_form_field");_x000D_
_x000D_
var x = 1;_x000D_
$(add_button).click(function(e) {_x000D_
e.preventDefault();_x000D_
if (x < max_fields) {_x000D_
x++;_x000D_
$(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="delete">Delete</a></div>'); //add input box_x000D_
} else {_x000D_
alert('You Reached the limits')_x000D_
}_x000D_
});_x000D_
_x000D_
$(wrapper).on("click", ".delete", function(e) {_x000D_
e.preventDefault();_x000D_
$(this).parent('div').remove();_x000D_
x--;_x000D_
})_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="container1">_x000D_
<button class="add_form_field">Add New Field _x000D_
<span style="font-size:16px; font-weight:bold;">+ </span>_x000D_
</button>_x000D_
<div><input type="text" name="mytext[]"></div>_x000D_
</div>
_x000D_
Refer Demo Here
When using a VM, I use these steps to inspect changes to the registry:
HKLM\SYSTEM
or HKLM\SOFTWARE
Now use your favourite diff program to compare the 'before' and 'after' snapshots.
It's pretty trivial to implement with native addon, so someone did that: https://github.com/ErikDubbelboer/node-sleep.git
1) You can use standard java utility xjc - ([your java home dir]\bin\xjc.exe). But you need to create .bat (or .sh) script for using it.
e.g. generate.bat:
[your java home dir]\bin\xjc.exe %1 %2 %3
e.g. test-scheme.xsd:
<?xml version="1.0"?>
<xs:schema version="1.0"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified"
targetNamespace="http://myprojects.net/xsd/TestScheme"
xmlns="http://myprojects.net/xsd/TestScheme">
<xs:element name="employee" type="PersonInfoType"/>
<xs:complexType name="PersonInfoType">
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
Run .bat file with parameters: generate.bat test-scheme.xsd -d [your src dir]
For more info use this documentation - http://docs.oracle.com/javaee/5/tutorial/doc/bnazg.html
and this - http://docs.oracle.com/javase/6/docs/technotes/tools/share/xjc.html
2) JAXB (xjc utility) is installed together with JDK6 by default.
I recommend CsvHelper from Nuget.
PS: Regarding other more upvoted answers, I'm sorry but adding a reference to Microsoft.VisualBasic
is:
A ScrollView is a special type of FrameLayout in that it allows users to scroll through a list of views that occupy more space than the physical display.I just add some attributes .
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true"
android:scrollbars = "vertical"
android:scrollbarStyle="insideInset"
>
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="1"
>
<!-- Add here which you want -->
</TableLayout>
</ScrollView>
import random
random.shuffle(array)
For leading and trailing whitespace:
s = ' foo \t '
print s.strip() # prints "foo"
Otherwise, a regular expression works:
import re
pat = re.compile(r'\s+')
s = ' \t foo \t bar \t '
print pat.sub('', s) # prints "foobar"
git reset --soft
is just for that: it is like git reset --hard
, but doesn't touch the files.
<%= link_to "http://www.facebook.com/sharer.php?u=" + article_url(article, :text => article.title), :class => "btn btn-primary" do %> <i class="fa fa-facebook"> Facebook Share </i> <%end%>
I am assuming that current_article_url
is http://0.0.0.0:4567/link_to_title
You don't need to use the clipboard, you can export directly the whole resultset (not just what you see) to a file :
The export runs in the background, a popup will appear when it's done.
In newer versions of DBeaver you can just :
The export runs in the background, a popup will appear when it's done.
Compared to the previous way of doing exports, this saves you step 1 (executing the query) which can be handy with time/resource intensive queries.
Try this:
function removeClassDelayed(jqObj, c, to) {
setTimeout(function() { jqObj.removeClass(c); }, to);
}
removeClassDelayed($("#div"), "error", 1000);
Valid numbers for ports are: 0 to 2^16-1 = 0 to 65535
That is because a port number is 16 bit length.
However ports are divided into:
Well-known ports: 0 to 1023 (used for system services e.g. HTTP, FTP, SSH, DHCP ...)
Registered/user ports: 1024 to 49151 (you can use it for your server, but be careful some famous applications: like Microsoft SQL Server database management system (MSSQL) server or Apache Derby Network Server are already taking from this range i.e. it is not recommended to assign the port of MSSQL to your server otherwise if MSSQL is running then your server most probably will not run because of port conflict )
Dynamic/private ports: 49152 to 65535. (not used for the servers rather the clients e.g. in NATing service)
In programming you can use any numbers 0 to 65535 for your server, however you should stick to the ranges mentioned above, otherwise some system services or some applications will not run because of port conflict.
Check the list of most ports here: https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers
I have tried it, it works for you.
String mainWinHander = webDriver.getWindowHandle();
// code for clicking button to open new window is ommited
//Now the window opened. So here reture the handle with size = 2
Set<String> handles = webDriver.getWindowHandles();
for(String handle : handles)
{
if(!mainWinHander.equals(handle))
{
// Here will block for ever. No exception and timeout!
WebDriver popup = webDriver.switchTo().window(handle);
// do something with popup
popup.close();
}
}
You can change it in you php-configuration on your webserver.
Search in php.ini
for
session.gc_maxlifetime()
The value is set in Seconds.
16x16 pixels, *.ico format.
You can use express-error-handler to use static html pages for error handling and to avoid defining a view handler.
The error was probably caused by a 404, maybe a missing favicon (apparent if you had included the previous console message). The 'view handler' of 'html' doesn't seem to be valid in 4.x express.
Regardless of the cause, you can avoid defining a (valid) view handler as long as you modify additional elements of your configuration.
Your options are to fix this problem are:
http://expressjs.com/en/api.html#res.render
Using render without a filepath automatically invokes a view handler as with the following two lines from your configuration:
res.render('404', { url: req.url });
and:
res.render('500);
Make sure you install express-error-handler with:
npm install --save express-error-handler
Then import it in your app.js
var ErrorHandler = require('express-error-handler');
Then change your error handling to use:
// define below all other routes
var errorHandler = ErrorHandler({
static: {
'404': 'error.html' // put this file in your Public folder
'500': 'error.html' // ditto
});
// any unresolved requests will 404
app.use(function(req,res,next) {
var err = new Error('Not Found');
err.status(404);
next(err);
}
app.use(errorHandler);
If you need something like:
¦ A ¦ B
--+--------------------------------+---
1 ¦ #My comment, something else ¦
2 ¦ 1 ¦ 2
Your CSV may contain the following lines:
"#My comment, something else"
1,2
Pay close attention at the 'quotes' in the first line.
When converting your text to columns using the Excel wizard, remember checking the 'Treat consecutive delimiters as one', setting it to use 'quotes' as delimiter.
Thus, Excel will split the text at the commas, keeping the 'comment' line as a single column value (and it will remove the quotes).
solution is
import time
import datetime
d = datetime.date(2015,1,5)
unixtime = time.mktime(d.timetuple())
That name looks derived from an object URL GUID. Do the following to get the object URL that the name was derived from.
var URL = self.URL || self.webkitURL || self;
var object_url = URL.createObjectURL(blob);
URL.revokeObjectURL(object_url);
object_url
will be formatted as blob:{origin}{GUID}
in Google Chrome and moz-filedata:{GUID}
in Firefox. An origin is the protocol+host+non-standard port for the protocol. For example, blob:http://stackoverflow.com/e7bc644d-d174-4d5e-b85d-beeb89c17743
or blob:http://[::1]:123/15111656-e46c-411d-a697-a09d23ec9a99
. You probably want to extract the GUID and strip any dashes.
Thanks to this post, I use this style to remove the red border that appears automatically with bootstrap when a required field is displayed, but user didn't have a chance to input anything already:
input.ng-pristine.ng-invalid {
-webkit-box-shadow: none;
-ms-box-shadow: none;
box-shadow:none;
}
I had trouble with changing the JFrame background as well and the above responses did not solve it entirely. I am using Eclipse. Adding a layout fixed the issue.
public class SampleProgram extends JFrame {
public SampleProgram() {
setSize(400,400);
setTitle("Sample");
getContentPane().setLayout(new FlowLayout());//specify a layout manager
getContentPane().setBackground(Color.red);
setVisible(true);
}
Try this:
mynewlist = [s for s in mylist if s.isdigit()]
From the docs:
str.isdigit()
Return true if all characters in the string are digits and there is at least one character, false otherwise.
For 8-bit strings, this method is locale-dependent.
As noted in the comments, isdigit()
returning True
does not necessarily indicate that the string can be parsed as an int via the int()
function, and it returning False
does not necessarily indicate that it cannot be. Nevertheless, the approach above should work in your case.
Use capitals letter for hours HH = 24 hour format an hh = 12 hour format
$('#fecha').datetimepicker({_x000D_
format : 'DD/MM/YYYY HH:mm'_x000D_
});
_x000D_
This is a one line to solve the complete original question:
params.select { |k,_| k[/choice/]}.values.join('\t')
But most the solutions above are solving a case where you need to know the keys ahead of time, using slice
or simple regexp.
Here is another approach that works for simple and more complex use cases, that is swappable at runtime
data = {}
matcher = ->(key,value) { COMPLEX LOGIC HERE }
data.select(&matcher)
Now not only this allows for more complex logic on matching the keys or the values, but it is also easier to test, and you can swap the matching logic at runtime.
Ex to solve the original issue:
def some_method(hash, matcher)
hash.select(&matcher).values.join('\t')
end
params = { :irrelevant => "A String",
:choice1 => "Oh look, another one",
:choice2 => "Even more strings",
:choice3 => "But wait",
:irrelevant2 => "The last string" }
some_method(params, ->(k,_) { k[/choice/]}) # => "Oh look, another one\\tEven more strings\\tBut wait"
some_method(params, ->(_,v) { v[/string/]}) # => "Even more strings\\tThe last string"
enumerate
is what you want:
for i, s in enumerate(S):
print s, i
To start multiple containers with the only particular container id's $ docker restart contianer-id1 container-id2 container-id3 ...
I got the same error and looked into activity. Where I found that I had two package lock files which was causing the error.
building on @ltamar's answer:
Use summary and munge the output into something useful!
library(tidyr)
library(dplyr)
df %>%
summary %>%
data.frame %>%
select(-Var1) %>%
separate(data=.,col=Freq,into = c('metric','value'),sep = ':') %>%
rename(column_name=Var2) %>%
mutate(value=as.numeric(value),
metric = trimws(metric,'both')
) %>%
filter(!is.na(value)) -> metrics
It's not pretty and it is certainly not fast but it gets the job done!
My problem was caused by the exact opposite of @ehacinom. My Laravel generated API didn't like the trailing '/' on POST requests. Worked fine on localhost but didn't work when uploaded to server.
If for some reason you have extended a custom Activity located in some external library that do not call the super you will need to manually call the Fragment super.onRequestPermissionsResult yourself in your Activity onRequestPermissionsResult.
YourActivity extends SomeActivityNotCallingSuperOnRequestPermissionsResult{
Fragment requestingFragment;//the fragment requesting the permission
...
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestingFragment!=null)
requestingFragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
...
I follow the Python Idioms and Efficiency guidelines, by Rob Knight. I think they are exactly the same as PEP 8, but are more synthetic and based on examples.
If you are using wxPython you might also want to check Style Guide for wxPython code, by Chris Barker, as well.
It looks like you're missing a return false
.
Try this :
import urllib, urllib2, json
url = 'http://openligadb-json.heroku.com/api/teams_by_league_saison?league_saison=2012&league_shortcut=bl1'
request = urllib2.Request(url)
request.add_header('User-Agent','Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')
request.add_header('Content-Type','application/json')
response = urllib2.urlopen(request)
json_object = json.load(response)
#print json_object['results']
if json_object['team'] == []:
print 'No Data!'
else:
for rows in json_object['team']:
print 'Team ID:' + rows['team_id']
print 'Team Name:' + rows['team_name']
print 'Team URL:' + rows['team_icon_url']
Another (albeit non-free) option is to install VMware Fusion or Parallels Desktop on the Mac and run Windows with Visual Studio in a VM.
This works really pretty well. The downsides are:
The upside is that you and the student don't need to hassle with differences in the IDE that may not be accounted for in your instruction materials.
A union query can only have one master ORDER BY
clause, IIRC. To get this, in each query making up the greater UNION
query, add a field that will be the one field you sort by for the UNION
's ORDER BY
.
For instance, you might have something like
SELECT field1, field2, '1' AS union_sort
UNION SELECT field1, field2, '2' AS union_sort
UNION SELECT field1, field2, '3' AS union_sort
ORDER BY union_sort
That union_sort
field can be anything you may want to sort by. In this example, it just happens to put results from the first table first, second table second, etc.
You should also mind the references to other objects.
If the table was highly referenced by other tables than it’s probably also highly referenced by other objects such as views, stored procedures, functions and more.
I’d really recommend GUI tool such as ‘view dependencies’ dialog in SSMS or free tool like ApexSQL Search for this because searching for dependencies in other objects can be error prone if you want to do it only with SQL.
If SQL is the only option you could try doing it like this.
select O.name as [Object_Name], C.text as [Object_Definition]
from sys.syscomments C
inner join sys.all_objects O ON C.id = O.object_id
where C.text like '%table_name%'
If you are creating an array whose main feature is it's length, rather than the value of each index, defining an array as var a=Array(length);
is appropriate.
eg-
String.prototype.repeat= function(n){
n= n || 1;
return Array(n+1).join(this);
}
Then NumPy sum
function takes an optional axis argument that specifies along which axis you would like the sum performed:
>>> a = numpy.arange(12).reshape(4,3)
>>> a.sum(0)
array([18, 22, 26])
Or, equivalently:
>>> numpy.sum(a, 0)
array([18, 22, 26])
When the above solution doesn’t work try this:
<IfModule mod_security.c>
SecRuleEngine Off
SecFilterInheritance Off
SecFilterEngine Off
SecFilterScanPOST Off
SecRuleRemoveById 300015 3000016 3000017
</IfModule>
First get the instance of SharedPreferences using
SharedPreferences userDetails = context.getSharedPreferences("userdetails", MODE_PRIVATE);
Now to save the values in the SharedPreferences
Editor edit = userDetails.edit();
edit.putString("username", username.getText().toString().trim());
edit.putString("password", password.getText().toString().trim());
edit.apply();
Above lines will write username and password to preference
Now to to retrieve saved values from preference, you can follow below lines of code
String userName = userDetails.getString("username", "");
String password = userDetails.getString("password", "");
(NOTE: SAVING PASSWORD IN THE APP IS NOT RECOMMENDED. YOU SHOULD EITHER ENCRYPT THE PASSWORD BEFORE SAVING OR SKIP THE SAVING THE PASSWORD)
Similar to one post above, (except I was using admin credentials) to get S3 uploads to work with large 50M file.
Initially my error was:
An error occurred (AccessDenied) when calling the CreateMultipartUpload operation: Access Denied
I switched the multipart_threshold to be above the 50M
aws configure set default.s3.multipart_threshold 64MB
and I got:
An error occurred (AccessDenied) when calling the PutObject operation: Access Denied
I checked bucket public access settings and all was allowed. So I found that public access can be blocked on account level for all S3 buckets:
If you are trying to loop over a cell array and apply something to each element in the cell, check out cellfun
. There's also arrayfun
, bsxfun
, and structfun
which may simplify your program.
$_
is a variable created by the system usually inside block expressions that are referenced by cmdlets that are used with pipe such as Where-Object
and ForEach-Object
.
But it can be used also in other types of expressions, for example with Select-Object
combined with expression properties. Get-ChildItem | Select-Object @{Name="Name";Expression={$_.Name}}
. In this case the $_
represents the item being piped but multiple expressions can exist.
It can also be referenced by custom parameter validation, where a script block is used to validate a value. In this case the $_
represents the parameter value as received from the invocation.
The closest analogy to c# and java is the lamda expression. If you break down powershell to basics then everything is a script block including a script file a, functions and cmdlets. You can define your own parameters but in some occasions one is created by the system for you that represents the input item to process/evaluate. In those situations the automatic variable is $_
.
The easiest and quickest I find is this
ALTER TABLE mydb.mytable
ADD COLUMN mycolumnname INT NOT NULL AUTO_INCREMENT AFTER updated,
ADD UNIQUE INDEX mycolumnname_UNIQUE (mycolumname ASC);
This will happen to some files while also open in Excel.
Covert .ppk to id_rsa using tool PuttyGen, (http://mydailyfindingsit.blogspot.in/2015/08/create-keys-for-your-linux-machine.html) and
scp -C -i ./id_rsa -r /var/www/* [email protected]:/var/www
it should work !
If it’s there, they’ll take it all.
The IRS matches with this regex: .*
$50,000
This will match everything!
See here for an example: Greedy-example
If I ask for a tax refund, the IRS sudden becomes non-greedy, and they use this quantifier:
(.{2,5}?)([0-9]*)
against this input: $50,000
The first group is non-needy and only matches $5
– so I get a $5
refund against the $50,000 input. They're non-greedy. They take as little as possible.
See here: Non-greedy-example.
It becomes important if you are trying to match certain parts of an expression. Sometimes you don't want to match everything.
Hopefully that analogy will help you remember!
Take a look at this tutorial on MDN: https://developer.mozilla.org/en/HTML/Canvas/Drawing_DOM_objects_into_a_canvas (archived)
Alternate Link (2019) : https://reference.codeproject.com/book/dom/canvas_api/drawing_dom_objects_into_a_canvas
It uses a temporary SVG image to include the HTML content as a "foreign element", then renders said SVG image into a canvas element. There are significant restrictions on what you can include in an SVG image in this way, however. (See the "Security" section for details.)
Perhaps Layout Engine v0.7.0 is a good solution for your situation. It uses browser feature detection and can detect not only IE11 and IE10, but also IE9, IE8, and IE7. It also detects other popular browsers, including some mobile browsers. It adds a class to the html tag, is easy to use, and it's performed well under some fairly deep testing.
Use a grep
analog to find the strings oldnamespace
and Jenine
inside the files in your whole project folder. Then you'd know what step to do next.
Well, It's quite easy.
Open your local project.
Add a README.md
file (If you don't have anything to add yet)
Click on Publish on Github
Choose as you wish
Choose the files you want to include in firt commit.
Note: If you don't select a file or folder it will added to .gitignore
file
You are good to go. it is published.
P.S. If this was you first time. A prompt will ask for for your Github Credentials fill those and you are good to go. It is published.
For unicode characters, it is :
preg_replace("/[^[:alnum:][:space:]]/u", '', $string);
Try This and you can adjust date formate accordingly:
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
var myDate= dd + '-' + mm + '-' + yyyy;
The --no-ff
option is useful when you want to have a clear notion of your feature branch. So even if in the meantime no commits were made, FF is possible - you still want sometimes to have each commit in the mainline correspond to one feature. So you treat a feature branch with a bunch of commits as a single unit, and merge them as a single unit. It is clear from your history when you do feature branch merging with --no-ff
.
If you do not care about such thing - you could probably get away with FF whenever it is possible. Thus you will have more svn-like feeling of workflow.
For example, the author of this article thinks that --no-ff
option should be default and his reasoning is close to that I outlined above:
Consider the situation where a series of minor commits on the "feature" branch collectively make up one new feature: If you just do "git merge feature_branch" without --no-ff
, "it is impossible to see from the Git history which of the commit objects together have implemented a feature—you would have to manually read all the log messages. Reverting a whole feature (i.e. a group of commits), is a true headache [if --no-ff
is not used], whereas it is easily done if the --no-ff
flag was used [because it's just one commit]."
if qs.count()==1:
print('cart id exists')
if ....
else:
return render(request,"carts/home.html",{})
Such type of code will also return you the same error this is because of the intents as the return statement should be for else not for if statement.
above code can be changed to
if qs.count()==1:
print('cart id exists')
if ....
else:
return render(request,"carts/home.html",{})
This may solve such issues
add the line to your .bashrc
or .profile
. The variables set in $HOME/.profile
are active for the current user, the ones in /etc/profile
are global. The .bashrc
is pulled on each bash session start.
dd if=/dev/zero of=my_file.txt count=12345
If you don't need it to be human-readable/editable, the easiest solution is to just use pickle
.
To write:
with open(the_filename, 'wb') as f:
pickle.dump(my_list, f)
To read:
with open(the_filename, 'rb') as f:
my_list = pickle.load(f)
If you do need them to be human-readable, we need more information.
If my_list
is guaranteed to be a list of strings with no embedded newlines, just write them one per line:
with open(the_filename, 'w') as f:
for s in my_list:
f.write(s + '\n')
with open(the_filename, 'r') as f:
my_list = [line.rstrip('\n') for line in f]
If they're Unicode strings rather than byte strings, you'll want to encode
them. (Or, worse, if they're byte strings, but not necessarily in the same encoding as your system default.)
If they might have newlines, or non-printable characters, etc., you can use escaping or quoting. Python has a variety of different kinds of escaping built into the stdlib.
Let's use unicode-escape
here to solve both of the above problems at once:
with open(the_filename, 'w') as f:
for s in my_list:
f.write((s + u'\n').encode('unicode-escape'))
with open(the_filename, 'r') as f:
my_list = [line.decode('unicode-escape').rstrip(u'\n') for line in f]
You can also use the 3.x-style solution in 2.x, with either the codecs
module or the io
module:*
import io
with io.open(the_filename, 'w', encoding='unicode-escape') as f:
f.writelines(line + u'\n' for line in my_list)
with open(the_filename, 'r') as f:
my_list = [line.rstrip(u'\n') for line in f]
* TOOWTDI, so which is the one obvious way? It depends… For the short version: if you need to work with Python versions before 2.6, use codecs
; if not, use io
.
who still facing the problem on linux and didnt find it on trash try this solution
https://github.com/Microsoft/vscode/issues/32078#issuecomment-434393058
find / -name "delete_file_name"
You can do that:
function formatAMPM(date) { // This is to display 12 hour format like you asked
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
var myDate = new Date();
var displayDate = myDate.getMonth()+ '/' +myDate.getDate()+ '/' +myDate.getFullYear()+ ' ' +formatAMPM(myDate);
console.log(displayDate);
You can configure patterns to hide files and folders from the explorer and searches.
File > Preferences > Settings
). This will open the setting screen.files:exclude
in the search at the top.node_modules/
then click OK. The pattern syntax is powerful. You can find pattern matching details under the Search Across Files topic. When you are done it should look something like this:
If you want to directly edit the settings file: For example to hide a top level node_modules folder in your workspace:
"files.exclude": {
"node_modules/": true
}
To hide all files that start with ._
such as ._.DS_Store
files found on OSX:
"files.exclude": {
"**/._*": true
}
You also have the ability to change Workspace Settings (Main menu: File > Preferences > Workspace Settings
). Workspace settings will create a .vscode/settings.json
file in your current workspace and will only be applied to that workspace. User Settings will be applied globally to any instance of VS Code you open, but they won't override Workspace Settings if present. Read more on customizing User and Workspace Settings.
Use the double-star (aka double-splat?) operator:
func(**{'type':'Event'})
is equivalent to
func(type='Event')
In Apache 2.4, the authorization configuration syntax has changed, and the Order
, Deny
or Allow
directives should no longer be used.
The new way to do this would be:
<VirtualHost *:8080>
<Location />
Require ip 192.168.1.0
</Location>
...
</VirtualHost>
Further examples using the new syntax can be found in the Apache documentation: Upgrading to 2.4 from 2.2
Follow the below steps,
You can insert new data into table by two ways.
Here's a version of the SQL that returns the correct records:
select distinct u.*
from Users u, CompanyRolesToUsers c
where u.Id = c.UserId --join just specified here, perfectly fine
and u.firstname like '%amy%'
and c.CompanyRoleId in (2,3,4)
Also, note that (2,3,4) is a list selected from a checkbox list by the web app user, and I forgot to mention that I just hardcoded that for simplicity. Really it's an array of CompanyRoleId values, so it could be (1) or (2,5) or (1,2,3,4,6,7,99).
Also the other thing that I should specify more clearly, is that the PredicateExtensions are used to dynamically add predicate clauses to the Where for the query, depending on which form fields the web app user has filled in. So the tricky part for me is how to transform the working query into a LINQ Expression that I can attach to the dynamic list of expressions.
I'll give some of the sample LINQ queries a shot and see if I can integrate them with our code, and then get post my results. Thanks!
marcel
To clear only certain parameters, you can use:
[:param1, :param2, :param3].each { |k| session.delete(k) }
You can also use named arguments which are optional and can be given in any order.
Set namedArguments = WScript.Arguments.Named
Here's a little helper function:
Function GetNamedArgument(ByVal argumentName, ByVal defaultValue)
If WScript.Arguments.Named.Exists(argumentName) Then
GetNamedArgument = WScript.Arguments.Named.Item(argumentName)
Else
GetNamedArgument = defaultValue
End If
End Function
Example VBS:
'[test.vbs]
testArg = GetNamedArgument("testArg", "-unknown-")
wscript.Echo now &": "& testArg
Example Usage:
test.vbs /testArg:123
I struggled with this on Mac OS X where the find command doesn't support -printf
.
A solution that I found, that admittedly relies on the 'group' for all files being 'staff' was...
ls -l -R | sed 's/\(.*\)staff *\([0-9]*\)..............\(.*\)/\2 \3/'
This splits the ls long output into three tokens
And then outputs tokens 2 and 3, i.e. output is number of bytes and then filename
8071 sections.php
54681 services.php
37961 style.css
13260 thumb.php
70951 workshops.php
I had the same question, the solutions proposed were almost working but they had some issue. In the end the regex I used is:
^(?!red|green|blue).*
I tested it in Javascript and .NET.
.* should't be placed inside the negative lookahead like this: ^(?!.*red|green|blue) or it would make the first element behave different from the rest (i.e. "anotherred" wouldn't be matched while "anothergreen" would)
Try this test:
any(substring in string for substring in substring_list)
It will return True
if any of the substrings in substring_list
is contained in string
.
Note that there is a Python analogue of Marc Gravell's answer in the linked question:
from itertools import imap
any(imap(string.__contains__, substring_list))
In Python 3, you can use map
directly instead:
any(map(string.__contains__, substring_list))
Probably the above version using a generator expression is more clear though.
In addition to the provided answers, if you want to convert Enumerable#max into a max method that can call a variable number or arguments, like in some other programming languages, you could write:
def max(*values)
values.max
end
Output:
max(7, 1234, 9, -78, 156)
=> 1234
This abuses the properties of the splat operator to create an array object containing all the arguments provided, or an empty array object if no arguments were provided. In the latter case, the method will return nil
, since calling Enumerable#max on an empty array object returns nil
.
If you want to define this method on the Math module, this should do the trick:
module Math
def self.max(*values)
values.max
end
end
Note that Enumerable.max is, at least, two times slower compared to the ternary operator (?:
). See Dave Morse's answer for a simpler and faster method.
If you want to use a tiny component (466 Byte gzipped) that already exists for this functionality then you can check out this library react-outclick.
The good thing about the library is that it also lets you detect clicks outside of a component and inside of another. It also supports detecting other types of events.
It's not like WAMP. You need to start mongoDB database with a command after directory has been created C:/database_mongo
mongod --dbpath=C:/database_mongo/
you can then connect to mongodb using commands.
A simple  
; between input fields would do the job easily...
You could try using float:left;
or display:inline-block;
.
Both of these will change the element's behaviour from defaulting to 100% width to defaulting to the natural width of its contents.
However, note that they'll also both have an impact on the layout of the surrounding elements as well. I would suggest that inline-block
will have less of an impact though, so probably best to try that first.
The following will produce, in the output directory,
But it does not contain all .NET Core runtime assemblies.
<PropertyGroup>
<Temp>$(SolutionDir)\packaging\</Temp>
</PropertyGroup>
<ItemGroup>
<BootStrapFiles Include="$(Temp)hostpolicy.dll;$(Temp)$(ProjectName).exe;$(Temp)hostfxr.dll;"/>
</ItemGroup>
<Target Name="GenerateNetcoreExe"
AfterTargets="Build"
Condition="'$(IsNestedBuild)' != 'true'">
<RemoveDir Directories="$(Temp)" />
<Exec
ConsoleToMSBuild="true"
Command="dotnet build $(ProjectPath) -r win-x64 /p:CopyLocalLockFileAssemblies=false;IsNestedBuild=true --output $(Temp)" >
<Output TaskParameter="ConsoleOutput" PropertyName="OutputOfExec" />
</Exec>
<Copy
SourceFiles="@(BootStrapFiles)"
DestinationFolder="$(OutputPath)"
/>
</Target>
I wrapped it up in a sample here: https://github.com/SimonCropp/NetCoreConsole
A convenient solution in your case would be to include the configs in a yaml file named
**your_config_name.yml**
which would look like this:
path1: "D:\test1\first"
path2: "D:\test2\second"
path3: "D:\test2\third"
In your python code you can then load the config params into a dictionary by doing this:
import yaml
with open('your_config_name.yml') as stream:
config = yaml.safe_load(stream)
You then access e.g. path1 like this from your dictionary config:
config['path1']
To import yaml you first have to install the package as such: pip install pyyaml
into your chosen virtual environment.
var streetaddress= addy.substr(0, addy.indexOf(','));
While it's not the best place for definitive information on what each method does (mozilla developer network is better for that) w3schools.com is good for introducing you to syntax.
Here's a gotcha that I just discovered - perhaps it might help someone else. If using windows the classes folder must not have encryption enabled! Tomcat doesn't seem to like that. Right click on the classes folder, select "Properties" and then click the "Advanced..." button. Make sure the "Encrypt contents to secure data" checkbox is cleared. Restart Tomcat.
It worked for me so here's hoping it helps someone else, too.
Code:
ListItem removeItem= myDropDown.Items.FindByValue("TextToFind");
drpCategory.Items.Remove(removeItem);
Replace "TextToFind" with the item you want to remove.
In tandem with what Pedro Fontez said a few replies up, you seemed to never call the sys module initially, nor did you manage to stick the required () at the end of sys.exit:
so:
import sys
and when finished:
sys.exit()
<htmltag id=’elementId’ data-ZZZZ’=’@Html.Raw(Json.Encode(Model))’ />
Refer https://highspeedlowdrag.wordpress.com/2014/08/23/mvc-data-to-jquery-data/
I did below and it works like charm.
<input id="hdnElement" class="hdnElement" type="hidden" value='@Html.Raw(Json.Encode(Model))'>
Say you want to know all methods associated with list class Just Type The following
print (dir(list))
Above will give you all methods of list class
When this happened to me, it was because I'd blindly copied my settings.xml from a template and it still had the blank <localRepository/>
element. This means that there's no local repository used when resolving dependencies (though your installed artifacts do still get put in the default location). When I'd replaced that with <localRepository>${user.home}\.m2\repository</localRepository>
it started working.
For *nix, that would be <localRepository>${user.home}/.m2/repository</localRepository>
, I suppose.
I've made my own head hurt over nothing! The Answer was very simple- I just went back to the basics...
some_Entities e2 = new some_Entities(); //your entity.
add this line below after you update/delete - you're re-loading your entity-no fancy system methods.
e2 = new some_Entities(); //reset.
The settings you need are "Local echo" and "Line editing" under the "Terminal" category on the left.
To get the characters to display on the screen as you enter them, set "Local echo" to "Force on".
To get the terminal to not send the command until you press Enter, set "Local line editing" to "Force on".
Explanation:
From the PuTTY User Manual (Found by clicking on the "Help" button in PuTTY):
4.3.8 ‘Local echo’
With local echo disabled, characters you type into the PuTTY window are not echoed in the window by PuTTY. They are simply sent to the server. (The server might choose to echo them back to you; this can't be controlled from the PuTTY control panel.)
Some types of session need local echo, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local echo is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local echo to be turned on, or force it to be turned off, instead of relying on the automatic detection.
4.3.9 ‘Local line editing’ Normally, every character you type into the PuTTY window is sent immediately to the server the moment you type it.
If you enable local line editing, this changes. PuTTY will let you edit a whole line at a time locally, and the line will only be sent to the server when you press Return. If you make a mistake, you can use the Backspace key to correct it before you press Return, and the server will never see the mistake.
Since it is hard to edit a line locally without being able to see it, local line editing is mostly used in conjunction with local echo (section 4.3.8). This makes it ideal for use in raw mode or when connecting to MUDs or talkers. (Although some more advanced MUDs do occasionally turn local line editing on and turn local echo off, in order to accept a password from the user.)
Some types of session need local line editing, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local line editing is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local line editing to be turned on, or force it to be turned off, instead of relying on the automatic detection.
Putty sometimes makes wrong choices when "Auto" is enabled for these options because it tries to detect the connection configuration. Applied to serial line, this is a bit trickier to do.
For simplicity's sake: newList = list(set(oldList))
But there are better options out there if you'd like to get speed/ordering/optimization instead: http://www.peterbe.com/plog/uniqifiers-benchmark
I'm using Altova DiffDog which has options to compare XML files structurally (ignoring string data).
This means that (if checking the 'ignore text' option):
<foo a="xxx" b="xxx">xxx</foo>
and
<foo b="yyy" a="yyy">yyy</foo>
are equal in the sense that they have structural equality. This is handy if you have example files that differ in data, but not structure!
For those new to Maven (like me) here is the whole config that goes in the build section of your pom. Cheers.
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19</version>
<configuration>
<argLine>-Xmx1024m</argLine>
</configuration>
</plugin>
</plugins>
</build>
http://www.exocortex.org/dsp/ is an open-source C# mathematics library with FFT algorithms.
I got the same error when using %
as a percent character in my format string. The solution to this is to double up the %%
.
You can use the <button>
tag. For a submit, simply add type="submit"
. Then use a background image when you want the button to appear as a graphic.
Like so:
<button type="submit" style="border: 0; background: transparent">
<img src="/images/Btn.PNG" width="90" height="50" alt="submit" />
</button>
or just use for date strings 2015-05-20 or 2015.05.20
date.split(/\.|-/);
Here is my experience with Jenkins version 1.636: as long as I have only one "Install automatically" JDK configured in Jenkins JDK section, I don't see "JDK" dropdown in Job=>Configure section, but as soon as I added second JDK in Jenkins config, JDK dropdown appeared in Job=>Configure section with 3 options [(System), JDK1, JDK2]
Here is a link that will help answer your questions. In short:
count(*) is the correct way to write it and count(1) is OPTIMIZED TO BE count(*) internally -- since
a) count the rows where 1 is not null is less efficient than
b) count the rows
If you would like a software tool to do this, you might like to check out this step-by-step guide:
"How to Validate and Import Excel spreadsheet to SQL Server database"
Remove runat="server" parts of data posting/posted .aspx page.
I checked all the above solutions, they don't work. The only possible solution is to catch 'onkeydown' event for each input of the form. You need to attach disableAllInputs to onload of the page or via jquery ready()
/*
* Prevents default behavior of pushing enter button. This method doesn't work,
* if bind it to the 'onkeydown' of the document|form, or to the 'onkeypress' of
* the input. So method should be attached directly to the input 'onkeydown'
*/
function preventEnterKey(e) {
// W3C (Chrome|FF) || IE
e = e || window.event;
var keycode = e.which || e.keyCode;
if (keycode == 13) { // Key code of enter button
// Cancel default action
if (e.preventDefault) { // W3C
e.preventDefault();
} else { // IE
e.returnValue = false;
}
// Cancel visible action
if (e.stopPropagation) { // W3C
e.stopPropagation();
} else { // IE
e.cancelBubble = true;
}
// We don't need anything else
return false;
}
}
/* Disable enter key for all inputs of the document */
function disableAllInputs() {
try {
var els = document.getElementsByTagName('input');
if (els) {
for ( var i = 0; i < els.length; i++) {
els[i].onkeydown = preventEnterKey;
}
}
} catch (e) {
}
}
It allows servlets to have multiple servlet mappings:
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-path>foo.Servlet</servlet-path>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/enroll</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/pay</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/bill</url-pattern>
</servlet-mapping>
It allows filters to be mapped on the particular servlet:
<filter-mapping>
<filter-name>Filter1</filter-name>
<servlet-name>Servlet1</servlet-name>
</filter-mapping>
Your proposal would support neither of them. Note that the web.xml
is read and parsed only once during application's startup, not on every HTTP request as you seem to think.
Since Servlet 3.0, there's the @WebServlet
annotation which minimizes this boilerplate:
@WebServlet("/enroll")
public class Servlet1 extends HttpServlet {
The top answer is a very bad practice, one should never ever link to an empty hash as it can create problems down the road.
Best is to bind an event handler to the element as numerous other people have stated, however, <a href="javascript:doStuff();">do stuff</a>
works perfectly in every modern browser, and I use it extensively when rendering templates to avoid having to rebind for each instance. In some cases, this approach offers better performance. YMMV
Another interesting tid-bit....
onclick
& href
have different behaviors when calling javascript directly.
onclick
will pass this
context correctly, whereas href
won't, or in other words <a href="javascript:doStuff(this)">no context</a>
won't work, whereas <a onclick="javascript:doStuff(this)">no context</a>
will.
Yes, I omitted the href
. While that doesn't follow the spec, it will work in all browsers, although, ideally it should include a href="javascript:void(0);"
for good measure
You need a little statistical knowledge to see this. R squared between two vectors is just the square of their correlation. So you can define you function as:
rsq <- function (x, y) cor(x, y) ^ 2
Sandipan's answer will return you exactly the same result (see the following proof), but as it stands it appears more readable (due to the evident $r.squared
).
Basically we fit a linear regression of y
over x
, and compute the ratio of regression sum of squares to total sum of squares.
lemma 1: a regression y ~ x
is equivalent to y - mean(y) ~ x - mean(x)
lemma 2: beta = cov(x, y) / var(x)
lemma 3: R.square = cor(x, y) ^ 2
R squared between two arbitrary vectors x
and y
(of the same length) is just a goodness measure of their linear relationship. Think twice!! R squared between x + a
and y + b
are identical for any constant shift a
and b
. So it is a weak or even useless measure on "goodness of prediction". Use MSE or RMSE instead:
I agree with 42-'s comment:
The R squared is reported by summary functions associated with regression functions. But only when such an estimate is statistically justified.
R squared can be a (but not the best) measure of "goodness of fit". But there is no justification that it can measure the goodness of out-of-sample prediction. If you split your data into training and testing parts and fit a regression model on the training one, you can get a valid R squared value on training part, but you can't legitimately compute an R squared on the test part. Some people did this, but I don't agree with it.
Here is very extreme example:
preds <- 1:4/4
actual <- 1:4
The R squared between those two vectors is 1. Yes of course, one is just a linear rescaling of the other so they have a perfect linear relationship. But, do you really think that the preds
is a good prediction on actual
??
Thanks for your comments 1, 2 and your answer of details.
You probably misunderstood the procedure. Given two vectors x
and y
, we first fit a regression line y ~ x
then compute regression sum of squares and total sum of squares. It looks like you skip this regression step and go straight to the sum of square computation. That is false, since the partition of sum of squares does not hold and you can't compute R squared in a consistent way.
As you demonstrated, this is just one way for computing R squared:
preds <- c(1, 2, 3)
actual <- c(2, 2, 4)
rss <- sum((preds - actual) ^ 2) ## residual sum of squares
tss <- sum((actual - mean(actual)) ^ 2) ## total sum of squares
rsq <- 1 - rss/tss
#[1] 0.25
But there is another:
regss <- sum((preds - mean(preds)) ^ 2) ## regression sum of squares
regss / tss
#[1] 0.75
Also, your formula can give a negative value (the proper value should be 1 as mentioned above in the Warning section).
preds <- 1:4 / 4
actual <- 1:4
rss <- sum((preds - actual) ^ 2) ## residual sum of squares
tss <- sum((actual - mean(actual)) ^ 2) ## total sum of squares
rsq <- 1 - rss/tss
#[1] -2.375
I had never expected that this answer could eventually be so long when I posted my initial answer 2 years ago. However, given the high views of this thread, I feel obliged to add more statistical details and discussions. I don't want to mislead people that just because they can compute an R squared so easily, they can use R squared everywhere.
build it with string.Join
instead:
var parameters = sl.SelProds.Select(x=>"productID="+x.prodID).ToArray();
paramstr = string.Join("&", parameters);
string.Join
takes a seperator ("&"
) and and array of strings (parameters
), and inserts the seperator between each element of the array.
A character encoding is a way to encode characters so that they fit in memory. That is, if the charset is ISO-8859-15, the euro symbol, €, will be encoded as 0xa4, and in UTF-8, it will be 0xe282ac.
The collation is how to compare characters, in latin9, there are letters as e é è ê f
, if sorted by their binary representation, it will go e f é ê è
but if the collation is set to, for example, French, you'll have them in the order you thought they would be, which is all of e é è ê
are equal, and then f
.
abs()
:
Returns the absolute value as per the argument i.e. if argument is int then it returns int, if argument is float it returns float.
Also it works on complex variable also i.e. abs(a+bj)
also works and returns absolute value i.e.math.sqrt(((a)**2)+((b)**2)
math.fabs()
:
It only works on the integer or float values. Always returns the absolute float value no matter what is the argument type(except for the complex numbers).
50% of C++ programmers like to set their pointers to null after a delete:
template<typename T>
void moronic_delete(T*& p)
{
delete p;
p = nullptr;
}
Without the reference, you would only be changing a local copy of the pointer, not affecting the caller.
I came up with a very effective, (I think) readable way to do this.
1. create a temp table and put the records you want to iterate in there
2. use WHILE @@ROWCOUNT <> 0 to do the iterating
3. to get one row at a time do, SELECT TOP 1 <fieldnames>
b. save the unique ID for that row in a variable
4. Do Stuff, then delete the row from the temp table based on the ID saved at step 3b.
Here's the code. Sorry, its using my variable names instead of the ones in the question.
declare @tempPFRunStops TABLE (ProformaRunStopsID int,ProformaRunMasterID int, CompanyLocationID int, StopSequence int );
INSERT @tempPFRunStops (ProformaRunStopsID,ProformaRunMasterID, CompanyLocationID, StopSequence)
SELECT ProformaRunStopsID, ProformaRunMasterID, CompanyLocationID, StopSequence from ProformaRunStops
WHERE ProformaRunMasterID IN ( SELECT ProformaRunMasterID FROM ProformaRunMaster WHERE ProformaId = 15 )
-- SELECT * FROM @tempPFRunStops
WHILE @@ROWCOUNT <> 0 -- << I dont know how this works
BEGIN
SELECT TOP 1 * FROM @tempPFRunStops
-- I could have put the unique ID into a variable here
SELECT 'Ha' -- Do Stuff
DELETE @tempPFRunStops WHERE ProformaRunStopsID = (SELECT TOP 1 ProformaRunStopsID FROM @tempPFRunStops)
END
You could do something with APIs.
Private Const SW_SHOW = 5
Private Const GW_HWNDNEXT = 2
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" _
(ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function ShowWindow Lib "user32" _
(ByVal hWnd As Long, ByVal nCmdShow As Long) As Long
Private Declare Function GetWindow Lib "user32" _
(ByVal hWnd As Long, ByVal wCmd As Long) As Long
Private Declare Function GetClassName Lib "user32" Alias "GetClassNameA" _
(ByVal hWnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long
Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" _
(ByVal hWnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Function FindWindowPartialX(ByVal Title As String) As Long
Dim hWndThis As Long
hWndThis = FindWindow(vbNullString, vbNullString)
While hWndThis
Dim sTitle As String, sClass As String
sTitle = Space$(255)
sTitle = Left$(sTitle, GetWindowText(hWndThis, sTitle, Len(sTitle)))
sClass = Space$(255)
sClass = Left$(sClass, GetClassName(hWndThis, sClass, Len(sClass)))
If InStr(sTitle, Title) > 0 Then
FindWindowPartialX = hWndThis
Exit Function
End If
hWndThis = GetWindow(hWndThis, GW_HWNDNEXT)
Wend
End Function
Sub CopySheet()
Dim objXL As Excel.Application
' A suitable portion of the window title such as file name '
WinHandle = FindWindowPartialX("LTD.xls")
ShowWindow WinHandle, SW_SHOW
Set objXL = GetObject(, "Excel.Application")
objXL.Worksheets("Source").Activate
objXL.ActiveSheet.UsedRange.Copy
Application.ActiveSheet.Paste
End Sub
unfortunately, with "mvim -v", ALT plus arrow windows still does not work. I have not found any way to enable it :-(
For spring boot framework version 2.0.4.RELEASE+
. Add this line to application.properties
server.servlet.context-path=/api
The ~/Library/Developer/Xcode/iOS DeviceSupport
folder is basically only needed to symbolicate crash logs.
You could completely purge the entire folder. Of course the next time you connect one of your devices, Xcode would redownload the symbol data from the device.
I clean out that folder once a year or so by deleting folders for versions of iOS I no longer support or expect to ever have to symbolicate a crash log for.
If you are only trying to change the include paths for a project and not for all solutions then in Visual Studio 2008 do this: Right-click on the name of the project in the Solution Navigator. From the popup menu select Properties. In the property pages dialog select Configuration Properties->C/C++/General. Click in the text box next to the "Additional Include Files" label and browse for the appropriate directory. Select OK.
What annoys me is that some of the answers to the original question asked do not apply to the version of Visual Studio that was mentioned.
"In the default mode, Dot (.) matches any character except a newline. If the DOTALL flag has been specified, this matches any character including a newline." (python Doc)
So, if you want to evaluate dot literaly, I think you should put it in square brackets:
>>> p = re.compile(r'\b(\w+[.]\w+)')
>>> resp = p.search("blah blah blah [email protected] blah blah")
>>> resp.group()
'test.this'
A good rule of thumb when constructing arguments for use in conditional statements (IF, WHILE, etc.) is to always use the &&/|| forms, unless there's a very good reason not to. There are two reasons...
Doing this, rather than relying on MATLAB's resolution of vectors in & and |, leads to code that's a little bit more verbose, but a LOT safer and easier to maintain.
Alternatively you can do:
Statement stmt = db.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
numero = stmt.executeUpdate();
ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()){
risultato=rs.getString(1);
}
But use Sean Bright's answer instead for your scenario.
In the constructor of Startup class, you can access appsettings.json and many other settings using the injected IConfiguration object:
Startup.cs Constructor
public Startup(IConfiguration configuration)
{
Configuration = configuration;
//here you go
var myvalue = Configuration["Grandfather:Father:Child"];
}
public IConfiguration Configuration { get; }
Contents of appsettings.json
{
"Grandfather": {
"Father": {
"Child": "myvalue"
}
}
Write a function lensort to sort a list of strings based on length.
def lensort(a):
n = len(a)
for i in range(n):
for j in range(i+1,n):
if len(a[i]) > len(a[j]):
temp = a[i]
a[i] = a[j]
a[j] = temp
return a
print lensort(["hello","bye","good"])
Press Ctrl-Alt-S > Uncheck "Android Support" plugin
(I wish I could tell you exactly why this works, but I can't. If you want to develop for Android, try using Android Studio, which is also made by Jetbrains.)
You can add nulls to the ArrayList
, and you will have to check for nulls in the loop:
for(Item i : itemList) {
if (i != null) {
}
}
itemsList.size();
would take the null
into account.
List<Integer> list = new ArrayList<Integer>();
list.add(null);
list.add (5);
System.out.println (list.size());
for (Integer value : list) {
if (value == null)
System.out.println ("null value");
else
System.out.println (value);
}
Output :
2
null value
5
Try this.. vagrant ubuntu 14.04 This worked for me.
scp -r -P 2222 vagrant@localhost:/home .
I have run into the same problem and I worked with a simple extension to allow Named services. You can find it here:
It allows you to add as many (named) services as you want like this:
var serviceCollection = new ServiceCollection();
serviceCollection.Add(typeof(IMyService), typeof(MyServiceA), "A", ServiceLifetime.Transient);
serviceCollection.Add(typeof(IMyService), typeof(MyServiceB), "B", ServiceLifetime.Transient);
var serviceProvider = serviceCollection.BuildServiceProvider();
var myServiceA = serviceProvider.GetService<IMyService>("A");
var myServiceB = serviceProvider.GetService<IMyService>("B");
The library also allows you to easy implement a "factory pattern" like this:
[Test]
public void FactoryPatternTest()
{
var serviceCollection = new ServiceCollection();
serviceCollection.Add(typeof(IMyService), typeof(MyServiceA), MyEnum.A.GetName(), ServiceLifetime.Transient);
serviceCollection.Add(typeof(IMyService), typeof(MyServiceB), MyEnum.B.GetName(), ServiceLifetime.Transient);
serviceCollection.AddTransient<IMyServiceFactoryPatternResolver, MyServiceFactoryPatternResolver>();
var serviceProvider = serviceCollection.BuildServiceProvider();
var factoryPatternResolver = serviceProvider.GetService<IMyServiceFactoryPatternResolver>();
var myServiceA = factoryPatternResolver.Resolve(MyEnum.A);
Assert.NotNull(myServiceA);
Assert.IsInstanceOf<MyServiceA>(myServiceA);
var myServiceB = factoryPatternResolver.Resolve(MyEnum.B);
Assert.NotNull(myServiceB);
Assert.IsInstanceOf<MyServiceB>(myServiceB);
}
public interface IMyServiceFactoryPatternResolver : IFactoryPatternResolver<IMyService, MyEnum>
{
}
public class MyServiceFactoryPatternResolver : FactoryPatternResolver<IMyService, MyEnum>, IMyServiceFactoryPatternResolver
{
public MyServiceFactoryPatternResolver(IServiceProvider serviceProvider)
: base(serviceProvider)
{
}
}
public enum MyEnum
{
A = 1,
B = 2
}
Hope it helps