You can add the src
folder to build path by:
- Select Java perspective.
- Right click on
src
folder. - Select Build Path > Use a source folder.
And you are done. Hope this help.
EDIT: Refer to the Eclipse documentation
Make a copy of existing list and iterate over new copy.
for (String str : new ArrayList<String>(listOfStr))
{
listOfStr.remove(/* object reference or index */);
}
HTML:
<tr>
<th>Language</th>
<th>Skill Level</th>
<th> </th>
</tr>
CSS:
tr, th {
padding: 10px;
text-align: center;
}
The way I usually do it, is with the following css:
div#submitForm input {
background: url("../images/buttonbg.png") no-repeat scroll 0 0 transparent;
color: #000000;
cursor: pointer;
font-weight: bold;
height: 20px;
padding-bottom: 2px;
width: 75px;
}
and the markup:
<div id="submitForm">
<input type="submit" value="Submit" name="submit">
</div>
If things look different in the various browsers I implore you to use a reset style sheet which sets all margins, padding and maybe even borders to zero.
>>> h = enumerate(range(2000, 2005))
>>> [(tup[0]+1, tup[1]) for tup in h]
[(1, 2000), (2, 2001), (3, 2002), (4, 2003), (5, 2004)]
Since this is somewhat verbose, I'd recommend writing your own function to generalize it:
def enumerate_at(xs, start):
return ((tup[0]+start, tup[1]) for tup in enumerate(xs))
Simple add
textAlign: "center"
in your styleSheet, that's it. Hope this would help.
edit: "center"
With numpy, you can pass a slice for each component of the index - so, your x[0:2,0:2]
example above works.
If you just want to evenly skip columns or rows, you can pass slices with three components (i.e. start, stop, step).
Again, for your example above:
>>> x[1:4:2, 1:4:2]
array([[ 5, 7],
[13, 15]])
Which is basically: slice in the first dimension, with start at index 1, stop when index is equal or greater than 4, and add 2 to the index in each pass. The same for the second dimension. Again: this only works for constant steps.
The syntax you got to do something quite different internally - what x[[1,3]][:,[1,3]]
actually does is create a new array including only rows 1 and 3 from the original array (done with the x[[1,3]]
part), and then re-slice that - creating a third array - including only columns 1 and 3 of the previous array.
Anybody can try the following (mailto function only accepts plaintext but here i show how to use HTML innertext properties and how to add an anchor as mailto body params):
//Create as many html elements you need.
const titleElement = document.createElement("DIV");
titleElement.innerHTML = this.shareInformation.title; // Just some string
//Here I create an <a> so I can use href property
const titleLinkElement = document.createElement("a");
titleLinkElement.href = this.shareInformation.link; // This is a url
...
let mail = document.createElement("a");
// Using es6 template literals add the html innerText property and anchor element created to mailto body parameter
mail.href =
`mailto:?subject=${titleElement.innerText}&body=${titleLinkElement}%0D%0A${abstractElement.innerText}`;
mail.click();
// Notice how I use ${titleLinkElement} that is an anchor element, so mailto uses its href and renders the url I needed
Try the click library written by the Mozart of Python, Armin Ronacher.
$ pip install click # both 2 and 3 compatible
To create a simple progress bar:
import click
with click.progressbar(range(1000000)) as bar:
for i in bar:
pass
This is what it looks like:
# [###-------------------------------] 9% 00:01:14
Customize to your hearts content:
import click, sys
with click.progressbar(range(100000), file=sys.stderr, show_pos=True, width=70, bar_template='(_(_)=%(bar)sD(_(_| %(info)s', fill_char='=', empty_char=' ') as bar:
for i in bar:
pass
Custom look:
(_(_)===================================D(_(_| 100000/100000 00:00:02
There are even more options, see the API docs:
click.progressbar(iterable=None, length=None, label=None, show_eta=True, show_percent=None, show_pos=False, item_show_func=None, fill_char='#', empty_char='-', bar_template='%(label)s [%(bar)s] %(info)s', info_sep=' ', width=36, file=None, color=None)
End of the user session means when the browser is shut down.
Read this: http://en.wikipedia.org/wiki/HTTP_cookie#Expires_and_Max-Age
Just leave it empty: 'default_charset' in WHM :::::: default_charset =''
p.s. - In WHM go --------) Home »Service Configuration »PHP Configuration Editor ----) click 'Advanced Mode' ----) find 'default_charset' and leave it blank ---- just nothing, not utf8, not ISO
Maybe the problem only in your IDE encoding settings. Try to set UTF-8 everywhere:
Why not just
$q->where("a = 1");
$q->andWhere("b = 1 OR b = 2");
$q->andWhere("c = 1 OR d = 2");
EDIT: You can also use the Expr class (Doctrine2).
If anyone's still stuck on this, the easiest solution I found was to "Retarget Solution". In my case, the project was built of SDK 8.1, upgrading to VS2017 brought with it SDK 10.0.xxx.
To retarget solution: Project->Retarget Solution->"Select whichever SDK you have installed"->OK
From there on you can simply build/debug your solution. Hope it helps
Team Foundation Sidekicks worked fine for me.
The file didn't unlock so I did a undo on pending changes and after that I could delete the file.
It's 2017, and now you can use object-fit which has decent support. It works in the same way as a div's background-size
but on the element itself, and on any element including images.
.your-img {
max-width: 100%;
max-height: 100%;
object-fit: contain;
}
You seem to be using Python as if it were the shell. Whenever I've needed to do something like what you're doing, I've used os.walk()
For example, as explained here: [x[0] for x in os.walk(directory)]
should give you all of the subdirectories, recursively.
Since favorites is an array, you just need to splice it off and save the document.
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var favorite = new Schema({
cn: String,
favorites: Array
});
module.exports = mongoose.model('Favorite', favorite);
exports.deleteFavorite = function (req, res, next) {
if (req.params.callback !== null) {
res.contentType = 'application/javascript';
}
// Changed to findOne instead of find to get a single document with the favorites.
Favorite.findOne({cn: req.params.name}, function (error, doc) {
if (error) {
res.send(null, 500);
} else if (doc) {
var records = {'records': doc};
// find the delete uid in the favorites array
var idx = doc.favorites ? doc.favorites.indexOf(req.params.deleteUid) : -1;
// is it valid?
if (idx !== -1) {
// remove it from the array.
doc.favorites.splice(idx, 1);
// save the doc
doc.save(function(error) {
if (error) {
console.log(error);
res.send(null, 500);
} else {
// send the records
res.send(records);
}
});
// stop here, otherwise 404
return;
}
}
// send 404 not found
res.send(null, 404);
});
};
Another option:
string s2 = String.Join("," + Environment.NewLine, s1.Split(','));
(JavaScript) Using regexp, this checks for alphanumeric palindrome and disregards space and punctuation.
function palindrome(str) {
str = str.match(/[A-Za-z0-9]/gi).join("").toLowerCase();
// (/[A-Za-z0-9]/gi) above makes str alphanumeric
for(var i = 0; i < Math.floor(str.length/2); i++) { //only need to run for half the string length
if(str.charAt(i) !== str.charAt(str.length-i-1)) { // uses !== to compare characters one-by-one from the beginning and end
return "Try again.";
}
}
return "Palindrome!";
}
palindrome("A man, a plan, a canal. Panama.");
//palindrome("4_2 (: /-\ :) 2-4"); // This solution would also work on something like this.
Just adding a point to previous answers that in MySQL we can either use
table_factor syntax
OR
joined_table syntax
Table_factor example
SELECT prd.name, b.name
FROM products prd, buyers b
Joined Table example
SELECT prd.name, b.name
FROM products prd
left join buyers b on b.bid = prd.bid;
FYI: Please ignore the fact the the left join on the joined table example doesnot make much sense (in reality we would use some sort of join table to link buyer to the product table instead of saving buyerID in product table).
echo [string] | sed "s/[original]/[target]/g"
I think the canonical method is:
while IFS=, read field1 field2 field3 field4 field5 field6; do
do stuff
done < CSV.file
If you don't know or don't care about how many fields there are:
IFS=,
while read line; do
# split into an array
field=( $line )
for word in "${field[@]}"; do echo "$word"; done
# or use the positional parameters
set -- $line
for word in "$@"; do echo "$word"; done
done < CSV.file
Your Delivery
class is internal (the default visibility for classes), however the property (and presumably the containing class) are public, so the property is more accessible than the Delivery
class. You need to either make Delivery
public, or restrict the visibility of the thelivery
property.
I have spent two solid days working on this so I just thought I'd share my solution as well. As of 26/11/10 the current branch is 1.2.X so that means you'll have to have the following in you settings.py:
MEDIA_ROOT = "<path_to_files>" (i.e. /home/project/django/app/templates/static)
MEDIA_URL = "http://localhost:8000/static/"
*(remember that MEDIA_ROOT is where the files are and MEDIA_URL is a constant that you use in your templates.)*
Then in you url.py place the following:
import settings
# stuff
(r'^static/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}),
Then in your html you can use:
<img src="{{ MEDIA_URL }}foo.jpg">
The way django works (as far as I can figure is:
ad 1. It does not implement its methods.
ad 4. The purpose of one interface extending, not implementing another, is to build a more specific interface. For example, SortedMap
is an interface that extends Map
. A client not interested in the sorting aspect can code against Map
and handle all the instances of for example TreeMap
, which implements SortedMap
. At the same time, another client interested in the sorted aspect can use those same instances through the SortedMap
interface.
In your example you are repeating the methods from the superinterface. While legal, it's unnecessary and doesn't change anything in the end result. The compiled code will be exactly the same whether these methods are there or not. Whatever Eclipse's hover says is irrelevant to the basic truth that an interface does not implement anything.
I think the best way is to typing well your variables. You can do this by using the "typing" library.
Example:
from typing import NewType
UserId = NewType ('UserId', int)
some_id = UserId (524313
)`
Haven't seen this solution yet so here's how I did it without using read_csv:
df.rename(columns={'A':'','B':''})
If you rename all your column names to empty strings your table will return without a header.
And if you have a lot of columns in your table you can just create a dictionary first instead of renaming manually:
df_dict = dict.fromkeys(df.columns, '')
df.rename(columns = df_dict)
I'm with Git downloaded from https://git-scm.com/ and set up ssh follow to the answer for instructions https://stackoverflow.com/a/26130250/4058484.
Once the generated public key is verified in my Bitbucket account, and by referring to the steps as explaned on http://www.bohyunkim.net/blog/archives/2518 I found that just 'git push' is working:
git clone https://[email protected]/me/test.git
cd test
cp -R ../dummy/* .
git add .
git pull origin master
git commit . -m "my first git commit"
git config --global push.default simple
git push
Shell respond are as below:
$ git push
Counting objects: 39, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (39/39), done.
Writing objects: 100% (39/39), 2.23 MiB | 5.00 KiB/s, done.
Total 39 (delta 1), reused 0 (delta 0)
To https://[email protected]/me/test.git 992b294..93835ca master -> master
It even works for to push on merging master to gh-pages in GitHub
git checkout gh-pages
git merge master
git push
Please see @jlareau answer here: https://stackoverflow.com/questions/11534710/angularjs-how-to-use-routeparams-in-generating-the-templateurl
You can use a function to generate the template string:
var app = angular.module('app',[]);
app.config(
function($routeProvider) {
$routeProvider.
when('/', {templateUrl:'/home'}).
when('/users/:user_id',
{
controller:UserView,
templateUrl: function(params){ return '/users/view/' + params.user_id; }
}
).
otherwise({redirectTo:'/'});
}
);
I had such problem. In my case problem was in data - my column 'information' contained 1 unique value and it caused error
UPDATE: to correct work 'pivot' pairs (id_user,information) cannot have duplicates
It works:
df2 = pd.DataFrame({'id_user':[1,2,3,4,4,5,5],
'information':['phon','phon','phone','phone1','phone','phone1','phone'],
'value': [1, '01.01.00', '01.02.00', 2, '01.03.00', 3, '01.04.00']})
df2.pivot(index='id_user', columns='information', values='value')
it doesn't work:
df2 = pd.DataFrame({'id_user':[1,2,3,4,4,5,5],
'information':['phone','phone','phone','phone','phone','phone','phone'],
'value': [1, '01.01.00', '01.02.00', 2, '01.03.00', 3, '01.04.00']})
df2.pivot(index='id_user', columns='information', values='value')
@Override
public String toString() {
return String.format("%15s /n %15d /n %15s /n %15s", name, age, Occupation, status);
}
You can use
Trace.WriteLine("text");
This will output to the "Output" window in Visual Studio (when debugging).
make sure to have the Diagnostics assembly included:
using System.Diagnostics;
Here is the most concise solution so far:
function isArrayOfStrings(value: any): boolean {
return Array.isArray(value) && value.every(item => typeof item === "string");
}
Note that value.every
will return true
for an empty array. If you need to return false
for an empty array, you should add value.length
to the condition clause:
function isNonEmptyArrayOfStrings(value: any): boolean {
return Array.isArray(value) && value.length && value.every(item => typeof item === "string");
}
There is no any run-time type information in TypeScript (and there won't be, see TypeScript Design Goals > Non goals, 5), so there is no way to get the type of an empty array. For a non-empty array all you can do is to check the type of its items, one by one.
The method argument specifies the parameter of the smooth statistic. You can see stat_smooth
for the list of all possible arguments to the method argument.
The other solutions with window.location
didn't work for me since they didn't make it refresh at all, so what I did was that I used an empty form to pass new and empty postdata to the same page. This is a way to do that based on this answer:
function refreshAndClearPost() {
var form = document.createElement("form");
form.method = "POST";
form.action = location.href;
form.style.display = "none";
document.body.appendChild(form);
form.submit(); //since the form is empty, it will pass empty postdata
document.body.removeChild(form);
}
A .NET dictionary does only have a 1-to-1 relationship for keys and values. But that doesn't mean that a value can't be another array/list/dictionary.
I can't think of a reason to have a 1 to many relationship in a dictionary, but obviously there is one.
If you have different types of data that you want to store to a key, then that sounds like the ideal time to create your own class. Then you have a 1 to 1, but you have the value class storing more that 1 piece of data.
I don't know how to test SET NOCOUNT ON between client and SQL, so I tested a similar behavior for other SET command "SET TRANSACTION ISOLATION LEVEL READ UNCIMMITTED"
I sent a command from my connection changing the default behavior of SQL (READ COMMITTED), and it was changed for the next commands. When I changed the ISOLATION level inside a stored procedure, it didn't change the connection behavior for the next command.
Current conclusion,
I think this is relevant to other SET command such like "SET NOCOUNT ON"
Using .on()
you can define your function once, and it will execute for any dynamically added elements.
for example
$('#staticDiv').on('click', 'yourSelector', function() {
//do something
});
I'm using a message service that wraps an rxjs Subject
(TypeScript)
Plunker example: Message Service
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Subscription } from 'rxjs/Subscription';
import 'rxjs/add/operator/filter'
import 'rxjs/add/operator/map'
interface Message {
type: string;
payload: any;
}
type MessageCallback = (payload: any) => void;
@Injectable()
export class MessageService {
private handler = new Subject<Message>();
broadcast(type: string, payload: any) {
this.handler.next({ type, payload });
}
subscribe(type: string, callback: MessageCallback): Subscription {
return this.handler
.filter(message => message.type === type)
.map(message => message.payload)
.subscribe(callback);
}
}
Components can subscribe and broadcast events (sender):
import { Component, OnDestroy } from '@angular/core'
import { MessageService } from './message.service'
import { Subscription } from 'rxjs/Subscription'
@Component({
selector: 'sender',
template: ...
})
export class SenderComponent implements OnDestroy {
private subscription: Subscription;
private messages = [];
private messageNum = 0;
private name = 'sender'
constructor(private messageService: MessageService) {
this.subscription = messageService.subscribe(this.name, (payload) => {
this.messages.push(payload);
});
}
send() {
let payload = {
text: `Message ${++this.messageNum}`,
respondEvent: this.name
}
this.messageService.broadcast('receiver', payload);
}
clear() {
this.messages = [];
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
(receiver)
import { Component, OnDestroy } from '@angular/core'
import { MessageService } from './message.service'
import { Subscription } from 'rxjs/Subscription'
@Component({
selector: 'receiver',
template: ...
})
export class ReceiverComponent implements OnDestroy {
private subscription: Subscription;
private messages = [];
constructor(private messageService: MessageService) {
this.subscription = messageService.subscribe('receiver', (payload) => {
this.messages.push(payload);
});
}
send(message: {text: string, respondEvent: string}) {
this.messageService.broadcast(message.respondEvent, message.text);
}
clear() {
this.messages = [];
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
The subscribe
method of MessageService
returns an rxjs Subscription
object, which can be unsubscribed from like so:
import { Subscription } from 'rxjs/Subscription';
...
export class SomeListener {
subscription: Subscription;
constructor(private messageService: MessageService) {
this.subscription = messageService.subscribe('someMessage', (payload) => {
console.log(payload);
this.subscription.unsubscribe();
});
}
}
Also see this answer: https://stackoverflow.com/a/36782616/1861779
You can use download.js (https://github.com/rndme/download and http://danml.com/download.html). If the file is in an external URL, you must make an Ajax request, but if it is not, then you can use the function:
download(Path, name, mime)
Read their documentation for more details in the GitHub.
You could just try the scandir(Path)
function. it is fast and easy to implement
Syntax:
$files = scandir("somePath");
This Function returns a list of file into an Array.
to view the result, you can try
var_dump($files);
Or
foreach($files as $file)
{
echo $file."< br>";
}
If you copy something from disk A to disk B in explorer, Windows employs DMA. That means for most of the copy process, the CPU will basically do nothing other than telling the disk controller where to put, and get data from, eliminating a whole step in the chain, and one that is not at all optimized for moving large amounts of data - and I mean hardware.
What you do involves the CPU a lot. I want to point you to the "Some calculations to fill a[]" part. Which I think is essential. You generate a[], then you copy from a[] to an output buffer (thats what fstream::write does), then you generate again, etc.
What to do? Multithreading! (I hope you have a multi-core processor)
I use Privoxy and cURL to scrape Tor pages:
<?php
$ch = curl_init('http://jhiwjjlqpyawmpjx.onion'); // Tormail URL
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
curl_setopt($ch, CURLOPT_PROXY, "localhost:8118"); // Default privoxy port
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
curl_exec($ch);
curl_close($ch);
?>
After installing Privoxy you need to add this line to the configuration file (/etc/privoxy/config
). Note the space and '.' a the end of line.
forward-socks4a / localhost:9050 .
Then restart Privoxy.
/etc/init.d/privoxy restart
U can try below code snippet
public Uri getUri(ContentResolver cr, String path){
Uri mediaUri = MediaStore.Files.getContentUri(VOLUME_NAME);
Cursor ca = cr.query(mediaUri, new String[] { MediaStore.MediaColumns._ID }, MediaStore.MediaColumns.DATA + "=?", new String[] {path}, null);
if (ca != null && ca.moveToFirst()) {
int id = ca.getInt(ca.getColumnIndex(MediaStore.MediaColumns._ID));
ca.close();
return MediaStore.Files.getContentUri(VOLUME_NAME,id);
}
if(ca != null) {
ca.close();
}
return null;
}
You can create dummy variables to handle the categorical data
# Creating dummy variables for categorical datatypes
trainDfDummies = pd.get_dummies(trainDf, columns=['Col1', 'Col2', 'Col3', 'Col4'])
This will drop the original columns in trainDf and append the column with dummy variables at the end of the trainDfDummies dataframe.
It automatically creates the column names by appending the values at the end of the original column name.
You need to add another \
before your carbon class to start in the root namespace.
$current_time = \Carbon\Carbon::now()->toDateTimeString();
Also, make sure Carbon is loaded in your composer.json
.
When one wants elements to be added with zero-based element indexing, I guess this will work as well:
// adding elements to an array with zero-based index
$matrix= array();
$matrix[count($matrix)]= 'element 1';
$matrix[count($matrix)]= 'element 2';
...
$matrix[count($matrix)]= 'element N';
You can try this. It is working fine for me.
SELECT IFNULL(table_schema,'Total') "Database",TableCount
FROM (SELECT COUNT(1) TableCount,table_schema
FROM information_schema.tables
WHERE table_schema NOT IN ('information_schema','mysql')
GROUP BY table_schema WITH ROLLUP) A;
This should work:
select
id
,action_heading
,case when action_type='Income' then action_amount else 0 end
,case when action_type='Expense' then expense_amount else 0 end
from tbl_transaction
From RFC 6750, Section 1.2:
Bearer Token
A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).
The Bearer Token or Refresh token is created for you by the Authentication server. When a user authenticates your application (client) the authentication server then goes and generates for your a Bearer Token (refresh token) which you can then use to get an access token.
The Bearer Token is normally some kind of cryptic value created by the authentication server, it isn't random it is created based upon the user giving you access and the client your application getting access.
See also: Mozilla MDN Header Information.
Simple method to sending data using java script and ajex call.
First right your form like this
<form id="frm_details" method="post" name="frm_details">
<input id="email" name="email" placeholder="Your Email id" type="text" />
<button class="subscribe-box__btn" type="submit">Need Assistance</button>
</form>
javascript logic target on form id #frm_details after sumbit
$(function(){
$("#frm_details").on("submit", function(event) {
event.preventDefault();
var formData = {
'email': $('input[name=email]').val() //for get email
};
console.log(formData);
$.ajax({
url: "/tsmisc/api/subscribe-newsletter",
type: "post",
data: formData,
success: function(d) {
alert(d);
}
});
});
})
General
Request URL:https://test.abc
Request Method:POST
Status Code:200
Remote Address:13.76.33.57:443
From Data
email:[email protected]
You will get this error when your AppID prefix does not match the prefix of the previously installed app. If your app is already in the App Store, you will not be able to submit updates without restoring the original AppID prefix or contacting Apple.
Apple's instructions for handling this problem: https://developer.apple.com/library/content/technotes/tn2319/_index.html#//apple_ref/doc/uid/DTS40013778-CH1-ERRORMESSAGES-UPGRADE_S_APPLICATION_IDENTIFIER_DOES_NOT_MATCH_THE_INSTALLED_APP
If you did not intend to change the AppID prefix then Xcode is signing your app with the wrong provisioning profile.
If you do intend to change the AppID prefix (because the app was transferred to a new developer, or you are migrating from an old pre-2011 AppID) you must contact Apple to migrate an existing AppID to a new prefix.
You must also add the previous-application-identifiers
entitlement to your app, listing all previous AppIDs (with old prefixes). And you must ask Apple to generate a provisioning profile for you that includes the previous-application-identifiers
entitlement.
To be clear there are 4 types of caches you can clear depending upon your case.
php artisan cache:clear
You can run the above statement in your console when you wish to clear the application cache. What it does is that this statement clears all caches inside storage\framework\cache.
php artisan route:cache
This clears your route cache. So if you have added a new route or have changed a route controller or action you can use this one to reload the same.
php artisan config:cache
This will clear the caching of the env file and reload it
php artisan view:clear
This will clear the compiled view files of your application.
Most of the shared hosting providers don't provide SSH access to the systems. In such a case you will need to create a route and call the following line as below:
Route::get('/clear-cache', function() {
Artisan::call('cache:clear');
return "All cache cleared";
});
Use this :
PackageManager pm = getPackageManager();
Intent intent = pm.getLaunchIntentForPackage("com.package.name");
startActivity(intent);
The other answers have explained in C99 or later, division of integers involving negative operands always truncate towards zero.
Note that, in C89, whether the result round upward or downward is implementation-defined. Because (a/b) * b + a%b
equals a
in all standards, the result of %
involving negative operands is also implementation-defined in C89.
The aliases you give are for the output of the query - they are not available within the query itself.
You can either repeat the expression:
SELECT neededfield, CONCAT(firstname, ' ', lastname) as firstlast
FROM users
WHERE CONCAT(firstname, ' ', lastname) = "Bob Michael Jones"
or wrap the query
SELECT * FROM (
SELECT neededfield, CONCAT(firstname, ' ', lastname) as firstlast
FROM users) base
WHERE firstLast = "Bob Michael Jones"
All of the answers are way too complicated. OP requested a way to do this from CMD.
Here you go (from cmd file):
powershell.exe /c "$(New-Object -ComObject Shell.Application).NameSpace(0xA).Items() | %%{Remove-Item $_.Path -Recurse -Confirm:$false"
And yes, it will update in explorer.
Use the \n
for a newline character.
document.write("\n");
You can also have more than one:
document.write("\n\n\n"); // 3 new lines! My oh my!
However, if this is rendering to HTML, you will want to use the HTML tag for a newline:
document.write("<br>");
The string Hello\n\nTest
in your source will look like this:
Hello!
Test
The string Hello<br><br>Test
will look like this in HTML source:
Hello<br><br>Test
The HTML one will render as line breaks for the person viewing the page, the \n
just drops the text to the next line in the source (if it's on an HTML page).
No, and the fact that you want to seems like a bad idea. Do you really need a default constructor like this?
PHP runs on the server. It outputs some text (usually). This is then parsed by the client.
During and after the parsing on the client, JavaScript runs. At this stage it is too late for the PHP script to do anything.
If you want to get anything back to PHP you need to make a new HTTP request and include the data in it (either in the query string (GET data) or message body (POST data).
You can do this by:
FormElement.submit()
method)Which ever option you choose, the PHP is essentially the same. Read from $_GET
or $_POST
, run your database code, then return some data to the client.
You can do this too:
oldIFS="$IFS"
IFS=$'\n' arr=($(<file))
IFS="$oldIFS"
echo "${arr[1]}" # It will print `A Dog`.
Note:
Filename expansion still occurs. For example, if there's a line with a literal *
it will expand to all the files in current folder. So use it only if your file is free of this kind of scenario.
The answer here worked better for me as it isolates the search on the hashtag, not just returning results that contain the search string. In the answer above you would still need to parse the JSON response to see if the entities.hashtags array is not empty.
You can use IN operator as below
select * from dbo.books where isbn IN
(select isbn from dbo.lending where lended_date between @fdate and @tdate)
Another reason to use object
over iframe is that object
sub resources (when an <object>
performs HTTP
requests) are considered as passive/display
in terms of Mixed content
, which means it's more secure when you must have Mixed content
.
Mixed content means that when you have https
but your resource is from http
.
Reference: https://developer.mozilla.org/en-US/docs/Web/Security/Mixed_content
I always avoid multiple return statements. Even in small functions. Small functions can become larger, and tracking the multiple return paths makes it harder (to my small mind) to keep track of what is going on. A single return also makes debugging easier. I've seen people post that the only alternative to multiple return statements is a messy arrow of nested IF statements 10 levels deep. While I certain agree that such coding does occur, it isn't the only option. I wouldn't make the choice between a multiple return statements and a nest of IFs, I'd refactor it so you'd eliminate both. And that is how I code. The following code eliminates both issues and, in my mind, is very easy to read:
public string GetResult()
{
string rv = null;
bool okay = false;
okay = PerformTest(1);
if (okay)
{
okay = PerformTest(2);
}
if (okay)
{
okay = PerformTest(3);
}
if (okay)
{
okay = PerformTest(4);
};
if (okay)
{
okay = PerformTest(5);
}
if (okay)
{
rv = "All Tests Passed";
}
return rv;
}
Multiple SQL statements must be executed with the mysqli_multi_query()
function.
Example (MySQLi Object-oriented):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO names (firstname, lastname)
VALUES ('inpute value here', 'inpute value here');";
$sql .= "INSERT INTO phones (landphone, mobile)
VALUES ('inpute value here', 'inpute value here');";
if ($conn->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
You can delay your code using setTimeout
to execute after click
function changeLink(){
setTimeout(function() {
var link = document.getElementById("mylink");
link.setAttribute('href', "http://facebook.com");
document.getElementById("mylink").innerHTML = "facebook";
}, 100);
}
I wanted to have two separate instances of Chrome running, each using its own profile. I wanted to be able to start them from Spotlight, as is my habit for starting Mac apps. In other words, I needed two regular Mac applications, regChrome
for normal browsing and altChrome
to use the special profile, to be easily started by keying ?-space to bring up Spotlight, then 'reg' or 'alt', then Enter.
I suppose the brute-force way to accomplish the above goal would be to make two copies of the Google Chrome application bundle under the respective names. But that's ugly and complicates updating.
What I ended up with was two AppleScript applications containing two commands each. Here is the one for altChrome
:
do shell script "cd /Applications/Google\\ Chrome.app/Contents/Resources/; rm app.icns; ln /Users/garbuck/local/chromeLaunchers/Chrome-swirl.icns app.icns"
do shell script "/Applications/Google\\ Chrome.app/Contents/MacOS/Google\\ Chrome --user-data-dir=/Users/garbuck/altChrome >/dev/null 2>&1 &"
The second line starts Chrome with the alternate profile (the --user-data-dir
parameter).
The first line is an unsuccessful attempt to give the two applications distinct icons. Initially, it appears to work fine. However, sooner or later, Chrome rereads its icon file and gets the one corresponding to whichever of the two apps was started last, resulting in two running applications with the same icon. But I haven't bothered to try to fix it — I keep the two browsers on separate desktops, and navigating between them hasn't been a problem.
You can use isin
method:
In [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})
In [2]: df
Out[2]:
A B
0 5 1
1 6 2
2 3 3
3 4 5
In [3]: df[df['A'].isin([3, 6])]
Out[3]:
A B
1 6 2
2 3 3
And to get the opposite use ~
:
In [4]: df[~df['A'].isin([3, 6])]
Out[4]:
A B
0 5 1
3 4 5
I don't see the need for Indirect, especially for conditional formatting.
The simplest way to self-reference a cell, row or column is to refer to it normally, e.g., "=A1" in cell A1, and make the reference partly or completely relative. For example, in a conditional formatting formula for checking whether there's a value in the first column of various cells' rows, enter the following with A1 highlighted and copy as necessary. The conditional formatting will always refer to column A for the row of each cell:
= $A1 <> ""
I tried all of the above but found out it was a missing windows compiler.
Downloading and installing this fixed the issue. To see if this is your problem, try to run PHP from command line.
msvcr110.dll is missing from computer error while installing PHP
So normally you would create a backing variable in the class and toggle it on click and tie a class binding to the variable. Something like:
@Component(
selector:'foo',
template:`<a (click)="onClick()"
[class.selected]="wasClicked">Link</a>
`)
export class MyComponent {
wasClicked = false;
onClick() {
this.wasClicked= !this.wasClicked;
}
}
Great question. This is really something missing from the Javascript browser API. I'm also working on a WebGL game with my team, and we need this feature. I opened an issue on Firefox's bugzilla so that we can start talking about the possibility of having an API to allow for mouse locking. This is going to be useful for all HTML5/WebGL game developers out there.
If you like, come over and leave a comment with your feedback, and upvote the issue:
https://bugzilla.mozilla.org/show_bug.cgi?id=630979
Thanks!
If you want a formula to do it then:
=IF(ISNUMBER(SEARCH("*texts are *",A1)),LEFT(A1,FIND("texts are ",A1) + 9) & "WORD",A1)
This will do it. Change `"WORD" To the word you want.
Have the certificate and bundle copied in one .crt file and make sure that there is a blank line between the certificates in the file.
This worked for me on a GitLab server after trying everything on the Internet.
I moved my home directory from one mac to another (Mountain Lion to Yosemite) and didn't realize about the broken virtualenv until I lost hold of the old laptop. I had the virtualenv point to Python 2.7 installed by brew
and since Yosemite came with Python 2.7, I wanted to update my virtualenv to the system python. When I ran virtualenv
on top of the existing directory, I was getting OSError: [Errno 17] File exists: '/Users/hdara/bin/python2.7/lib/python2.7/config'
error. By trial and error, I worked around this issue by removing a few links and fixing up a few more manually. This is what I finally did (similar to what @Rockalite did, but simpler):
cd <virtualenv-root>
rm lib/python2.7/config
rm lib/python2.7/lib-dynload
rm include/python2.7
rm .Python
cd lib/python2.7
gfind . -type l -xtype l | while read f; do ln -s -f /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/${f#./} $f; done
After this, I was able to just run virtualenv on top of the existing directory.
Use the CONCAT function available in SQL Server 2012 onward.
SELECT CONCAT([FirstName], ' , ' , [LastName]) FROM YOURTABLE
If you have a relatively- (or otherwise-) positioned div you can center something inside it with margin:auto
Vertical centering is a bit tricker, but possible.
The following approach can be used to get any path of a pathname:
some_path=a/b/c
echo $(basename $some_path)
echo $(basename $(dirname $some_path))
echo $(basename $(dirname $(dirname $some_path)))
Output:
c
b
a
This is in answer to your question...
I'd also like to know how to make it open up in Sublime Text 2 instead
For Windows:
git config --global core.editor "'C:/Program Files/Sublime Text 2/sublime_text.exe'"
Check that the path for sublime_text.exe
is correct and adjust if needed.
For Mac/Linux:
git config --global core.editor "subl -n -w"
If you get an error message such as:
error: There was a problem with the editor 'subl -n -w'.
Create the alias for subl
sudo ln -s /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl /usr/local/bin/subl
Again check that the path matches for your machine.
For Sublime Text simply save cmd S
and close the window cmd W
to return to git.
No Root and no ADB tools required method. Install MyAppSharer app from the play store.
If you like short and self descriptive parameters or if you don't want to use splice
and go with a straight forward filter or if you are simply a SQL person like me:
function removeFromArrayOfHash(p_array_of_hash, p_key, p_value_to_remove){
return p_array_of_hash.filter((l_cur_row) => {return l_cur_row[p_key] != p_value_to_remove});
}
And a sample usage:
l_test_arr =
[
{
post_id: 1,
post_content: "Hey I am the first hash with id 1"
},
{
post_id: 2,
post_content: "This is item 2"
},
{
post_id: 1,
post_content: "And I am the second hash with id 1"
},
{
post_id: 3,
post_content: "This is item 3"
},
];
l_test_arr = removeFromArrayOfHash(l_test_arr, "post_id", 2); // gives both of the post_id 1 hashes and the post_id 3
l_test_arr = removeFromArrayOfHash(l_test_arr, "post_id", 1); // gives only post_id 3 (since 1 was removed in previous line)
Press CMD + SHIFT + P
(MAC) and search for Toggle Editor Group
You need to wrap the forward slash to avoid cross browser issues or //commenting out.
str = 'this/that and/if';
var newstr = str.replace(/[/]/g, 'ForwardSlash');
There are other differences. For instance, {'time': datetime.now()}
cannot be serialized to JSON, but can be converted to string. You should use one of these tools depending on the purpose (i.e. will the result later be decoded).
Using python-dateutil:
In [1]: import dateutil.parser as dparser
In [18]: dparser.parse("monkey 2010-07-10 love banana",fuzzy=True)
Out[18]: datetime.datetime(2010, 7, 10, 0, 0)
Invalid dates raise a ValueError
:
In [19]: dparser.parse("monkey 2010-07-32 love banana",fuzzy=True)
# ValueError: day is out of range for month
It can recognize dates in many formats:
In [20]: dparser.parse("monkey 20/01/1980 love banana",fuzzy=True)
Out[20]: datetime.datetime(1980, 1, 20, 0, 0)
Note that it makes a guess if the date is ambiguous:
In [23]: dparser.parse("monkey 10/01/1980 love banana",fuzzy=True)
Out[23]: datetime.datetime(1980, 10, 1, 0, 0)
But the way it parses ambiguous dates is customizable:
In [21]: dparser.parse("monkey 10/01/1980 love banana",fuzzy=True, dayfirst=True)
Out[21]: datetime.datetime(1980, 1, 10, 0, 0)
That is because imgButton is null. Try this instead:
findViewById(R.id.imgButton).setBackgroundResource(R.drawable.ic_action_search);
or much easier to read:
imgButton = (Button) findViewById(R.id.imgButton);
imgButton.setOnClickListener(imgButtonHandler);
then in onClick: imgButton.setBackgroundResource(R.drawable.ic_action_search);
The correct config key is retention.ms
$ bin/kafka-topics.sh --zookeeper zk.prod.yoursite.com --alter --topic as-access --config retention.ms=86400000
Updated config for topic "my-topic".
((TextBox)GridView1.Rows[e.NewEditIndex].Cells[3].Controls[0]).Enabled = false;
In my case the problem was in parameters arrangement. Initially I had --name
parameter after environment parameters and then volume and attach_dbs
parameters, and image at the end of command like below.
docker run -p 1433:1433 -e sa_password=myComplexPwd -e ACCEPT_EULA=Y --name sql1 -v c:/temp/:c:/temp/ attach_dbs="[{'dbName':'TestDb','dbFiles':['c:\\temp\\TestDb.mdf','c:\\temp\\TestDb_log.ldf']}]" -d microsoft/mssql-server-windows-express
After rearranging the parameters like below everything worked fine (basically putting --name
parameter followed by image name).
docker run -d -p 1433:1433 -e sa_password=myComplexPwd -e ACCEPT_EULA=Y --name sql1 microsoft/mssql-server-windows-express -v C:/temp/:C:/temp/ attach_dbs="[{'dbName':'TestDb','dbFiles':['C:\\temp\\TestDb.mdf','C:\\temp\\TestDb_log.ldf']}]"
To suppress output, use redirection to NUL
.
There are two kinds of output that console commands use:
standard output, or stdout
,
standard error, or stderr
.
Of the two, stdout
is used more often, both by internal commands, like copy
, and by console utilities, or external commands, like find
and others, as well as by third-party console programs.
>NUL
suppresses the standard output and works fine e.g. for suppressing the 1 file(s) copied.
message of the copy
command. An alternative syntax is 1>NUL
. So,
COPY file1 file2 >NUL
or
COPY file1 file2 1>NUL
or
>NUL COPY file1 file2
or
1>NUL COPY file1 file2
suppresses all of COPY
's standard output.
To suppress error messages, which are typically printed to stderr
, use 2>NUL
instead. So, to suppress a File Not Found
message that DEL
prints when, well, the specified file is not found, just add 2>NUL
either at the beginning or at the end of the command line:
DEL file 2>NUL
or
2>NUL DEL file
Although sometimes it may be a better idea to actually verify whether the file exists before trying to delete it, like you are doing in your own solution. Note, however, that you don't need to delete the files one by one, using a loop. You can use a single command to delete the lot:
IF EXIST "%scriptDirectory%*.noext" DEL "%scriptDirectory%*.noext"
I wouldn't use a Regex for this, but rather just split the string and check that the date is valid:
list($year, $month, $day, $hour, $minute, $second) = preg_split('%( |-|:)%', $mydatestring);
if(!checkdate($month, $day, $year)) {
/* print error */
}
/* check $hour, $minute and $second etc */
The following also worked for me. ISO 8859-1 is going to save a lot, hahaha - mainly if using Speech Recognition APIs.
Example:
file = open('../Resources/' + filename, 'r', encoding="ISO-8859-1");
Use num_holes=None
as a default, instead. Then check for whether num_holes is None
, and if so, randomize. That's what I generally see, anyway.
More radically different construction methods may warrant a classmethod that returns an instance of cls
.
for set empty all input such textarea select and input run this code:
$('#message').val('').change();
You can also use the tab character '\t'
to represent a tab, instead of "\t"
.
char c ='t';
char c =(char)9;
Check this link
and import these clases UIImage+animatedGIF.h,UIImage+animatedGIF.m
Use this code
NSURL *urlZif = [[NSBundle mainBundle] URLForResource:@"dots64" withExtension:@"gif"];
NSString *path=[[NSBundle mainBundle]pathForResource:@"bar180" ofType:@"gif"];
NSURL *url=[[NSURL alloc] initFileURLWithPath:path];
imageVw.image= [UIImage animatedImageWithAnimatedGIFURL:url];
Hope this is helpfull
Well, the JVM memory model works something like this: values are stored on one pile of memory stack and objects are stored on another pile of memory called the heap. The garbage collector looks for garbage by looking at a list of objects you've made and seeing which ones aren't pointed at by anything. This is where setting an object to null
comes in; all nonprimitive (think of classes) variables are really references that point to the object on the stack, so by setting the reference you have to null
the garbage collector can see that there's nothing else pointing at the object and it can decide to garbage collect it. All Java objects are stored on the heap so they can be seen and collected by the garbage collector.
Nonprimitive (int
s, char
s, double
s, those sort of things) values, however, aren't stored on the heap. They're created and stored temporarily as they're needed and there's not much you can do there, but thankfully the compilers nowadays are really efficient and will avoid needed to store them on the JVM stack unless they absolutely need to.
On a bytecode level, that's basically how it works. The JVM is based on a stack-based machine, with a couple instructions to create allocate objects on the heap as well, and a ton of instructions to manipulate, push and pop values, off the stack. Local variables are stored on the stack, allocated variables on the heap.* These are the heap and the stack I'm referring to above. Here's a pretty good starting point if you want to get into the nitty gritty details.
In the resulting compiled code, there's a bit of leeway in terms of implementing the heap and stack. Allocation's implemented as allocation, there's really not a way around doing so. Thus the virtual machine heap becomes an actual heap, and allocations in the bytecode are allocations in actual memory. But you can get around using a stack to some extent, since instead of storing the values on a stack (and accessing a ton of memory), you can stored them on registers on the CPU which can be up to a hundred times (maybe even a thousand) faster than storing it on memory. But there's cases where this isn't possible (look up register spilling for one example of when this may happen), and using a stack to implement a stack kind of makes a lot of sense.
And quite frankly in your case a few integers probably won't matter. The compiler will probably optimize them out by itself in this case anyways. Optimization should always happen after you get it running and notice it's a tad slower than you'd prefer it to be. Worry about making simple, elegant, working code first then later make it fast (and hopefully) simple, elegant, working code.
Java's actually very nicely made so that you shouldn't have to worry about null
ing variables very often. Whenever you stop needing to use something, it will usually incidentally be disappearing from the scope of your program (and thus becoming eligible for garbage collection). So I guess the real lesson here is to use local variables as often as you can.
*There's also a constant pool, a local variable pool, and a couple other things in memory but you have close to no control over the size of those things and I want to keep this fairly simple.
Performance test for in_array vs array_intersect:
$a1 = array(2,4,8,11,12,13,14,15,16,17,18,19,20);
$a2 = array(3,20);
$intersect_times = array();
$in_array_times = array();
for($j = 0; $j < 10; $j++)
{
/***** TEST ONE array_intersect *******/
$t = microtime(true);
for($i = 0; $i < 100000; $i++)
{
$x = array_intersect($a1,$a2);
$x = empty($x);
}
$intersect_times[] = microtime(true) - $t;
/***** TEST TWO in_array *******/
$t2 = microtime(true);
for($i = 0; $i < 100000; $i++)
{
$x = false;
foreach($a2 as $v){
if(in_array($v,$a1))
{
$x = true;
break;
}
}
}
$in_array_times[] = microtime(true) - $t2;
}
echo '<hr><br>'.implode('<br>',$intersect_times).'<br>array_intersect avg: '.(array_sum($intersect_times) / count($intersect_times));
echo '<hr><br>'.implode('<br>',$in_array_times).'<br>in_array avg: '.(array_sum($in_array_times) / count($in_array_times));
exit;
Here are the results:
0.26520013809204
0.15600109100342
0.15599989891052
0.15599989891052
0.1560001373291
0.1560001373291
0.15599989891052
0.15599989891052
0.15599989891052
0.1560001373291
array_intersect avg: 0.16692011356354
0.015599966049194
0.031199932098389
0.031200170516968
0.031199932098389
0.031200885772705
0.031199932098389
0.031200170516968
0.031201124191284
0.031199932098389
0.031199932098389
in_array avg: 0.029640197753906
in_array is at least 5 times faster. Note that we "break" as soon as a result is found.
If you could not find Local DTC in the component services try to run this PowerShell script first:
$DTCSettings = @(
"NetworkDtcAccess", # Network DTC Access
"NetworkDtcAccessClients", # Allow Remote Clients ( Client and Administration)
"NetworkDtcAccessAdmin", # Allow Remote Administration ( Client and Administration)
"NetworkDtcAccessTransactions", # (Transaction Manager Communication )
"NetworkDtcAccessInbound", # Allow Inbound (Transaction Manager Communication )
"NetworkDtcAccessOutbound" , # Allow Outbound (Transaction Manager Communication )
"XaTransactions", # Enable XA Transactions
"LuTransactions" # Enable SNA LU 6.2 Transactions
)
foreach($setting in $DTCSettings)
{
Set-ItemProperty -Path HKLM:\Software\Microsoft\MSDTC\Security -Name $setting -Value 1
}
Restart-Service msdtc
And it appears!
Source: The partner transaction manager has disabled its support for remote/network transactions
I've resolved this kind of problem with a regular expression pattern. They tend to be slower than regular queries but it's an easy way to retrieve data in a comma-delimited query column
SELECT *
FROM `TABLE`
WHERE `field` REGEXP ',?[SEARCHED-VALUE],?';
the greedy question mark helps to search at the beggining or the end of the string.
Hope that helps for anyone in the future
If this happens in visual studio then clean your project and run it again.
Build --> Clean Solution
Run (or F5)
Here's a pure CSS solution. No need for jQuery. It won't show a tooltip, instead it'll just expand the content to its full length on mouseover.
Works great if you have content that gets replaced. Then you don't have to run a jQuery function every time.
.might-overflow {
text-overflow: ellipsis;
overflow : hidden;
white-space: nowrap;
}
.might-overflow:hover {
text-overflow: clip;
white-space: normal;
word-break: break-all;
}
You can use CurrentDirectory property.
Dim WshShell, strCurDir
Set WshShell = CreateObject("WScript.Shell")
strCurDir = WshShell.CurrentDirectory
WshShell.Run strCurDir & "\attribute.exe", 0
Set WshShell = Nothing
Depends what you mean by a pattern. If you're thinking Person/Company/Transaction/Product and such, then yes - there are a lot of generic database schemas already available.
If you're thinking Factory, Singleton... then no - you don't need any of these as they're too low level for DB programming.
If you're thinking database object naming, then it's under the category of conventions, not design per se.
BTW, S.Lott, one-to-many and many-to-many relationships aren't "patterns". They're the basic building blocks of the relational model.
All i did was duplicate my Application Loader.app in /Applications and ran both Application loaders at the same time.
this solution is out there, it used to work for me, but today not even that! what I did and worked is that (2 instances) + uploading with XCode (organizer). Had to try a couple of times and it worked.
hope this helps someone, this bug has been there for quite a lot of time now() an apple doesn't seem to care too much
You need to delegate event to the document level
$(document).on('submit','form.remember',function(){
// code
});
$('form.remember').on('submit'
work same as $('form.remember').submit(
but when you use $(document).on('submit','form.remember'
then it will also work for the DOM added later.
The solution tbaxter120 suggested worked for me but I needed something that will be supported both in MySQL & Oracle & MSSQL, and here it is:
WHERE (CONCAT(',' ,CONCAT(RTRIM(MyColumn), ','))) LIKE CONCAT('%,' , CONCAT(@search , ',%'))
Leaving a reply (and an answer to the question title), For the future googlers...
You can use .length
to get the length of a string.
var x = 'Mozilla'; var empty = '';
console.log('Mozilla is ' + x.length + ' code units long');
/*"Mozilla is 7 code units long" */
console.log('The empty string has a length of ' + empty.length);
/*"The empty string has a length of 0" */
If you intend to get the length of a textarea
say id="txtarea"
then you can use the following code.
txtarea = document.getElementById('txtarea');
console.log(txtarea.value.length);
You should be able to get away with using this with BMP Unicode symbols. If you want to support "non BMP Symbols" like (), then its an edge case, and you need to find some work around.
By default, Maven doesn't bundle dependencies in the JAR file it builds, and you're not providing them on the classpath when you're trying to execute your JAR file at the command-line. This is why the Java VM can't find the library class files when trying to execute your code.
You could manually specify the libraries on the classpath with the -cp
parameter, but that quickly becomes tiresome.
A better solution is to "shade" the library code into your output JAR file. There is a Maven plugin called the maven-shade-plugin to do this. You need to register it in your POM, and it will automatically build an "uber-JAR" containing your classes and the classes for your library code too when you run mvn package
.
To simply bundle all required libraries, add the following to your POM:
<project>
...
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
...
</project>
Once this is done, you can rerun the commands you used above:
$ mvn package
$ java -cp target/bil138_4-0.0.1-SNAPSHOT.jar tr.edu.hacettepe.cs.b21127113.bil138_4.App
If you want to do further configuration of the shade plugin in terms of what JARs should be included, specifying a Main-Class for an executable JAR file, and so on, see the "Examples" section on the maven-shade-plugin site.
I had a similar problem due to a password protected proxy server and couldn't find much in the way of information out there - hopefully this helps someone. I wanted to pick up the credentials as used by the customer's browser. However, the CredentialCache.DefaultCredentials and DefaultNetworkCredentials aren't working when the proxy has it's own username and password even though I had entered these details to ensure thatInternet explorer and Edge had access.
The solution for me in the end was to use a nuget package called "CredentialManagement.Standard" and the below code:
using WebClient webClient = new WebClient();
var request = WebRequest.Create("http://google.co.uk");
var proxy = request.Proxy.GetProxy(new Uri("http://google.co.uk"));
var cmgr = new CredentialManagement.Credential() { Target = proxy.Host };
if (cmgr.Load())
{
var credentials = new NetworkCredential(cmgr.Username, cmgr.Password);
webClient.Proxy.Credentials = credentials;
webClient.Credentials = credentials;
}
This grabs credentials from 'Credentials Manager' - which can be found via Windows - click Start then search for 'Credentials Manager'. Credentials for the proxy that were manually entered when prompted by the browser will be in the Windows Credentials section.
In Swift 4, you don't have to use characters
to use map()
. Just do map()
on String.
let letters = "ABC".map { String($0) }
print(letters) // ["A", "B", "C"]
print(type(of: letters)) // Array<String>
Or if you'd prefer shorter: "ABC".map(String.init)
(2-bytes )
In Swift 2 and Swift 3, You can use map()
function to characters
property.
let letters = "ABC".characters.map { String($0) }
print(letters) // ["A", "B", "C"]
Accepted answer doesn't seem to be the best, because sequence-converted String
is not a String
sequence, but Character
:
$ swift
Welcome to Swift! Type :help for assistance.
1> Array("ABC")
$R0: [Character] = 3 values {
[0] = "A"
[1] = "B"
[2] = "C"
}
This below works for me:
let str = "ABC"
let arr = map(str) { s -> String in String(s) }
Reference for a global function map()
is here: http://swifter.natecook.com/func/map/
Here is short example of how serialization works. I was also learning about the same and I found two links useful. What Serialization is and how it can be done in .NET.
A sample program explaining serialization
If you don't understand the above program a much simple program with explanation is given here.
Change
CREATE DEFINER = `root`@`localhost` FUNCTION `fnc_calcWalkedDistance` (
By
FUNCTION `fnc_calcWalkedDistance` (
You can use the u
option for jar
From the Java Tutorials:
jar uf jar-file input-file(s)
"Any files already in the archive having the same pathname as a file being added will be overwritten."
See Updating a JAR File.
Much better than making the whole jar all over again. Invoking this from within your program sounds possible too. Try Running Command Line in Java
var myElem = document.getElementById('myElementId');
if (myElem === null) alert('does not exist!');
If you do not use precompiled headers in your project, set the Create/Use Precompiled Header property of source files to Not Using Precompiled Headers. To set this compiler option, follow these steps:
Properties
.C/C++
folder.Precompiled Headers
node.Create/Use Precompiled Header
, and then click Not Using Precompiled Headers
.Actually
{
@synchronized(self) {
return [[myString retain] autorelease];
}
}
transforms directly into:
// needs #import <objc/objc-sync.h>
{
objc_sync_enter(self)
id retVal = [[myString retain] autorelease];
objc_sync_exit(self);
return retVal;
}
This API available since iOS 2.0 and imported using...
#import <objc/objc-sync.h>
Like a lot of functions, this one can be used in many different ways to solve many different problems, I think of it as yet another tool in our toolbelts.
So far, the discussion has focused heavily on simply hiding an ID, but that is only one value, why not use it for lots of values! That is what I am doing, I use it to load up the values in a class only one view at a time, because html.beginform creates a new object and if your model object for that view already had some values passed to it, those values will be lost unless you provide a reference to those values in the beginform.
To see a great motivation for the html.hiddenfor, I recommend you see Passing data from a View to a Controller in .NET MVC - "@model" not highlighting
I am not adding a new answer. I am just putting the best marked answer in a better format.
I can see that the best answer by rating is using sys.stdout.write(someString)
. You can try this out:
import sys
Print = sys.stdout.write
Print("Hello")
Print("World")
will yield:
HelloWorld
That is all.
All the above answers are correct. Just providing with your dataset to find perfect divisor:
#include <stdio.h>
int main()
{
int arr[7] = {3,5,7,8,9,17,19};
int j = 51;
int i = 0;
for (i=0 ; i < 7; i++) {
if (j % arr[i] == 0)
printf("%d is the perfect divisor of %d\n", arr[i], j);
}
return 0;
}
VLOOKUP deosnt work for String literals
The text inside $type is substituted directly into the insert string, therefore MySQL gets this:
... VALUES(testing, 'john', 'whatever')
Notice that there are no quotes around testing, you need to put these in like so:
$type = 'testing';
mysql_query("INSERT INTO contents (type, reporter, description) VALUES('$type', 'john', 'whatever')");
I also recommend you read up on SQL injection, as this sort of parameter passing is prone to hacking attempts if you do not sanitize the data being used:
You can use CAST and CONVERT to switch between different types of encodings. See: http://dev.mysql.com/doc/refman/5.0/en/charset-convert.html
SELECT column1, CONVERT(column2 USING utf8)
FROM my_table
WHERE my_condition;
Try using the non-breaking hyphen ‑
. I've replaced the dash with that character in your jsfiddle, shrunk the frame down as small as it can go, and the line doesn't split there any more.
In my case the error was showing because system java version was different from intellijj/eclipse java version. System and user had diff java versions. If you compile your code using one version and tried to run using a different version, it will error out.
#The system java version is 1.7.131
$ java -version
java version "1.7.0_131"
Long story short, make sure your code is compiled and ran by the same java version.
Kindly customize below command according to demand and find any string recursively from files.
grep -i hack $(find /etc/ -type f)
I just run npm install
and then ok.
My following JS solution is better than the other approaches here because it ensures that it will always say 'open' when the target is closed, and vice versa.
HTML:
<a href="#collapseExample" class="btn btn-primary" data-toggle="collapse" data-toggle-secondary="Close">
Open
</a>
<div class="collapse" id="collapseExample">
<div class="well">
...
</div>
</div>
JS:
$('[data-toggle-secondary]').each(function() {
var $toggle = $(this);
var originalText = $toggle.text();
var secondaryText = $toggle.data('toggle-secondary');
var $target = $($toggle.attr('href'));
$target.on('show.bs.collapse hide.bs.collapse', function() {
if ($toggle.text() == originalText) {
$toggle.text(secondaryText);
} else {
$toggle.text(originalText);
}
});
});
$('[data-toggle-secondary]').each(function() {_x000D_
var $toggle = $(this);_x000D_
var originalText = $toggle.text();_x000D_
var secondaryText = $toggle.data('toggle-secondary');_x000D_
var $target = $($toggle.attr('href'));_x000D_
_x000D_
$target.on('show.bs.collapse hide.bs.collapse', function() {_x000D_
if ($toggle.text() == originalText) {_x000D_
$toggle.text(secondaryText);_x000D_
} else {_x000D_
$toggle.text(originalText);_x000D_
}_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet"/>_x000D_
<script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/js/bootstrap.min.js"></script>_x000D_
_x000D_
<a href="#collapseExample" class="btn btn-primary" data-toggle="collapse" data-toggle-secondary="Close">_x000D_
Open_x000D_
</a>_x000D_
<div class="collapse" id="collapseExample">_x000D_
<div class="well">_x000D_
..._x000D_
</div>_x000D_
</div>
_x000D_
data-toggle-secondary
attributeAs already pointed out it's not obvious to tell subdomains in the practical sense (e.g. .co.uk
domains). We use this regex to validate domains which occur in the wild. It covers all practical use cases I know of. New ones are welcome. According to our guidelines it avoids non-capturing groups and greedy matching.
^(?!.*?_.*?)(?!(?:[\d\w]+?\.)?\-[\w\d\.\-]*?)(?![\w\d]+?\-\.(?:[\d\w\.\-]+?))(?=[\w\d])(?=[\w\d\.\-]*?\.+[\w\d\.\-]*?)(?![\w\d\.\-]{254})(?!(?:\.?[\w\d\-\.]*?[\w\d\-]{64,}\.)+?)[\w\d\.\-]+?(?<![\w\d\-\.]*?\.[\d]+?)(?<=[\w\d\-]{2,})(?<![\w\d\-]{25})$
Proof, explanation and examples: https://regex101.com/r/FLA9Bv/9 (Note: currently only works in Chrome because the regex uses lookbehinds which are only supported in ECMA2018)
There're two approaches to choose from when validating domains.
By-the-books FQDN matching (theoretical definition, rarely encountered in practice):
Practical / conservative FQDN matching (practical definition, expected and supported in practice):
[a-zA-Z0-9.-]
Here there is an explanation: http://bytes.com/topic/python/answers/444733-why-there-no-post-pre-increment-operator-python
However the absence of this operator is in the python philosophy increases consistency and avoids implicitness.
In addition, this kind of increments are not widely used in python code because python have a strong implementation of the iterator pattern plus the function enumerate.
Simply, the excel file is corrupt. Best solution is change/repair the file.(make a copy of the existing file and rename it)
You can see some reports in SSMS:
Right-click the instance name / reports / standard / top sessions
You can see top CPU consuming sessions. This may shed some light on what SQL processes are using resources. There are a few other CPU related reports if you look around. I was going to point to some more DMVs but if you've looked into that already I'll skip it.
You can use sp_BlitzCache to find the top CPU consuming queries. You can also sort by IO and other things as well. This is using DMV info which accumulates between restarts.
This article looks promising.
Some stackoverflow goodness from Mr. Ozar.
edit: A little more advice... A query running for 'only' 5 seconds can be a problem. It could be using all your cores and really running 8 cores times 5 seconds - 40 seconds of 'virtual' time. I like to use some DMVs to see how many executions have happened for that code to see what that 5 seconds adds up to.
The general approach is to convert the data to long format (using melt()
from package reshape
or reshape2
) or gather()
/pivot_longer()
from the tidyr
package:
library("reshape2")
library("ggplot2")
test_data_long <- melt(test_data, id="date") # convert to long format
ggplot(data=test_data_long,
aes(x=date, y=value, colour=variable)) +
geom_line()
Also see this question on reshaping data from wide to long.
as simple as:
tmpHM.each{ key, value ->
doSomethingWithKeyAndValue key, value
}
Add yourself to the vboxsf
group within the guest VM.
Solution 1
Run sudo adduser $USER vboxsf
from terminal.
(On Suse it's sudo usermod --append --groups vboxsf $USER
)
To take effect you should log out and then log in, or you may need to reboot.
Solution 2
Edit the file /etc/group
(you will need root privileges). Look for the line vboxsf:x:999
and add at the end :yourusername
-- use this solution if you don't have sudo.
To take effect you should log out and then log in, or you may need to reboot.
There are indeed global variables in javascript. You can learn more about scopes, which are helpful in this situation.
Your code could look like this:
<script>
var count = 1;
function setColor(btn, color) {
var property = document.getElementById(btn);
if (count == 0) {
property.style.backgroundColor = "#FFFFFF"
count = 1;
}
else {
property.style.backgroundColor = "#7FFF00"
count = 0;
}
}
</script>
Hope this helps.
Well if you really wanted to make it one line without importing anything you could do:
eval('*'.join(str(item) for item in list))
But don't.
There is a firewall blocking the connection or the process that is hosting the service is not listening on that port. Or it is listening on a different port.
Here's one example, given to me by @jleahy: Suppose you have a collection of tasks, executed asynchronously, and managed by an std::shared_ptr<Task>
. You may want to do something with those tasks periodically, so a timer event may traverse a std::vector<std::weak_ptr<Task>>
and give the tasks something to do. However, simultaneously a task may have concurrently decided that it is no longer needed and die. The timer can thus check whether the task is still alive by making a shared pointer from the weak pointer and using that shared pointer, provided it isn't null.
Just some background... The newly minted Server Communication dev guide (finally) discusses/mentions/explains this:
The RxJS library is quite large. Size matters when we build a production application and deploy it to mobile devices. We should include only those features that we actually need.
Accordingly, Angular exposes a stripped down version of
Observable
in therxjs/Observable
module, a version that lacks almost all operators including the ones we'd like to use here such as themap
method.It's up to us to add the operators we need. We could add each operator, one-by-one, until we had a custom Observable implementation tuned precisely to our requirements.
So as @Thierry already answered, we can just pull in the operators we need:
import 'rxjs/add/operator/map';
import 'rxjs/operator/delay';
import 'rxjs/operator/mergeMap';
import 'rxjs/operator/switchMap';
Or, if we're lazy we can pull in the full set of operators. WARNING: this will add all 50+ operators to your app bundle, and will effect load times
import 'rxjs/Rx';
Try this one:
echo '' | sudo -S my_command
Executing seq(1, 10, 1)
does what 1:10
does. You can change the last parameter of seq
, i.e. by
, to be the step of whatever size you like.
> #a vector of even numbers
> seq(0, 10, by=2) # Explicitly specifying "by" only to increase readability
> [1] 0 2 4 6 8 10
So if condition equals the value you want then the php document will run "include" and include will add that document to the current window for example:
`
<?php
$isARequest = true;
if ($isARequest){include('request.html');}/*So because $isARequest is true then it will include request.html but if its not a request then it will insert isNotARequest;*/
else if (!$isARequest) {include('isNotARequest.html')}
?>
`
use this URL : "https://twitter.com/(userName)/profile_image?size=original"
If you are using TWitter SDK you can get the user name when logged in, with TWTRAPIClient
, using TWTRAuthSession
.
This is the code snipe for iOS:
if let twitterId = session.userID{
let twitterClient = TWTRAPIClient(userID: twitterId)
twitterClient.loadUser(withID: twitterId) {(user, error) in
if let userName = user?.screenName{
let url = "https://twitter.com/\(userName)/profile_image?size=original")
}
}
}
That's the error you get when the DLL itself requires another COM server to be registered first or has a dependency on another DLL that's not available. The Regsvr32.exe tool does very little, it calls LoadLibrary() to load the DLL that's passed in the command line argument. Then GetProcAddress() to find the DllRegisterServer() entry point in the DLL. And calls it to leave it up to the COM server to register itself.
What that code does is fairly unguessable. The diagnostic you got is however pretty self-evident from the error code, for some reason this COM server needs another one to be registered first. The error message is crappy, it doesn't tell you what other server it needs. A sad side-effect of the way COM error handling works.
To troubleshoot this, use SysInternals' ProcMon tool. It shows you what registry keys Regsvr32.exe (actually: the COM server) is opening to find the server. Look for accesses to the CLSID key. That gives you a hint what {guid} it is looking for. That still doesn't quite tell you the server DLL, you should compare the trace with one you get from a machine that works. The InprocServer32 key has the DLL path.
The following code checks if a given value is in the array and returns its zero-based offset:
A=("one" "two" "three four")
VALUE="two"
if [[ "$(declare -p A)" =~ '['([0-9]+)']="'$VALUE'"' ]];then
echo "Found $VALUE at offset ${BASH_REMATCH[1]}"
else
echo "Couldn't find $VALUE"
fi
The match is done on the complete values, therefore setting VALUE="three" would not match.
URLs are not resolved based on the file structure in the server side. URLs are resolved based on the real public web addresses of the resources in question. It's namely the webbrowser who has got to invoke them, not the webserver.
There are several ways to soften the pain:
JSF EL offers a shorthand to ${pageContext.request}
in flavor of #{request}
:
<li><a href="#{request.contextPath}/index.xhtml">Home</a></li>
<li><a href="#{request.contextPath}/about_us.xhtml">About us</a></li>
You can if necessary use <c:set>
tag to make it yet shorter. Put it somewhere in the master template, it'll be available to all pages:
<c:set var="root" value="#{request.contextPath}/" />
...
<li><a href="#{root}index.xhtml">Home</a></li>
<li><a href="#{root}about_us.xhtml">About us</a></li>
JSF 2.x offers the <h:link>
which can take a view ID relative to the context root in outcome
and it will append the context path and FacesServlet
mapping automatically:
<li><h:link value="Home" outcome="index" /></li>
<li><h:link value="About us" outcome="about_us" /></li>
HTML offers the <base>
tag which makes all relative URLs in the document relative to this base. You could make use of it. Put it in the <h:head>
.
<base href="#{request.requestURL.substring(0, request.requestURL.length() - request.requestURI.length())}#{request.contextPath}/" />
...
<li><a href="index.xhtml">Home</a></li>
<li><a href="about_us.xhtml">About us</a></li>
(note: this requires EL 2.2, otherwise you'd better use JSTL fn:substring()
, see also this answer)
This should end up in the generated HTML something like as
<base href="http://example.com/webname/" />
Note that the <base>
tag has a caveat: it makes all jump anchors in the page like <a href="#top">
relative to it as well! See also Is it recommended to use the <base> html tag? In JSF you could solve it like <a href="#{request.requestURI}#top">top</a>
or <h:link value="top" fragment="top" />
.
You could use smth like this in WPF. I've created example method. Check below.
public string getFolderPath()
{
// Create OpenFileDialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Multiselect = false;
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (openFileDialog.ShowDialog() == true)
{
System.IO.FileInfo fInfo = new System.IO.FileInfo(openFileDialog.FileName);
return fInfo.DirectoryName;
}
return null;
}
I have Done the Following Things in IIS 8.5 (Windows Server 2012 R2)Server and its Worked in My Case Without Restart:
Selecting The Application Pool That Connected to The Application in IIS
And Right Click --> Advanced Settings --> Process Model --> Select Local System Instead of Recommended ApplicationPoolIdentity
And Make Sure C:\Windows\SysWOW64\config\systemprofile\desktop Have Enough Access For Users.
Refresh the Website Link that Connected With this Pool
My way
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
public class ReadAnnotation {
private static final Logger LOGGER = LoggerFactory.getLogger(ReadAnnotation.class);
public static boolean hasIgnoreAnnotation(String fieldName, Class entity) throws NoSuchFieldException {
return entity.getDeclaredField(fieldName).isAnnotationPresent(IgnoreAnnotation.class);
}
public static boolean isSkip(PropertyDescriptor propertyDescriptor, Class entity) {
boolean isIgnoreField;
try {
isIgnoreField = hasIgnoreAnnotation(propertyDescriptor.getName(), entity);
} catch (NoSuchFieldException e) {
LOGGER.error("Can not check IgnoreAnnotation", e);
isIgnoreField = true;
}
return isIgnoreField;
}
public void testIsSkip() throws Exception {
Class<TestClass> entity = TestClass.class;
BeanInfo beanInfo = Introspector.getBeanInfo(entity);
for (PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors()) {
System.out.printf("Field %s, has annotation %b", propertyDescriptor.getName(), isSkip(propertyDescriptor, entity));
}
}
}
You can use the .some
method referenced here.
The
some()
method tests whether at least one element in the array passes the test implemented by the provided function.
// test cases
var str1 = 'hi, how do you do?';
var str2 = 'regular string';
// do the test strings contain these terms?
var conditions = ["hello", "hi", "howdy"];
// run the tests against every element in the array
var test1 = conditions.some(el => str1.includes(el));
var test2 = conditions.some(el => str2.includes(el));
// display results
console.log(str1, ' ===> ', test1);
console.log(str2, ' ===> ', test2);
_x000D_
#include <sstream>
and use the fully qualified name i.e. std::stringstream ss;
By default, py.test
captures the result of standard out so that it can control how it prints it out. If it didn't do this, it would spew out a lot of text without the context of what test printed that text.
However, if a test fails, it will include a section in the resulting report that shows what was printed to standard out in that particular test.
For example,
def test_good():
for i in range(1000):
print(i)
def test_bad():
print('this should fail!')
assert False
Results in the following output:
>>> py.test tmp.py
============================= test session starts ==============================
platform darwin -- Python 2.7.6 -- py-1.4.20 -- pytest-2.5.2
plugins: cache, cov, pep8, xdist
collected 2 items
tmp.py .F
=================================== FAILURES ===================================
___________________________________ test_bad ___________________________________
def test_bad():
print('this should fail!')
> assert False
E assert False
tmp.py:7: AssertionError
------------------------------- Captured stdout --------------------------------
this should fail!
====================== 1 failed, 1 passed in 0.04 seconds ======================
Note the Captured stdout
section.
If you would like to see print
statements as they are executed, you can pass the -s
flag to py.test
. However, note that this can sometimes be difficult to parse.
>>> py.test tmp.py -s
============================= test session starts ==============================
platform darwin -- Python 2.7.6 -- py-1.4.20 -- pytest-2.5.2
plugins: cache, cov, pep8, xdist
collected 2 items
tmp.py 0
1
2
3
... and so on ...
997
998
999
.this should fail!
F
=================================== FAILURES ===================================
___________________________________ test_bad ___________________________________
def test_bad():
print('this should fail!')
> assert False
E assert False
tmp.py:7: AssertionError
====================== 1 failed, 1 passed in 0.02 seconds ======================
set /a countfiles-=%countfiles%
This will set countfiles to 0. I think you want to decrease it by 1, so use this instead:
set /a countfiles-=1
I'm not sure if the for loop will work, better try something like this:
:loop
cscript /nologo c:\deletefile.vbs %BACKUPDIR%
set /a countfiles-=1
if %countfiles% GTR 21 goto loop
Since i am little late here but i wanted to share how actually list comprehension works especially nested list comprehension :
New_list= [[float(y) for x in l]
is actually same as :
New_list=[]
for x in l:
New_list.append(x)
And now nested list comprehension :
[[float(y) for y in x] for x in l]
is same as ;
new_list=[]
for x in l:
sub_list=[]
for y in x:
sub_list.append(float(y))
new_list.append(sub_list)
print(new_list)
output:
[[40.0, 20.0, 10.0, 30.0], [20.0, 20.0, 20.0, 20.0, 20.0, 30.0, 20.0], [30.0, 20.0, 30.0, 50.0, 10.0, 30.0, 20.0, 20.0, 20.0], [100.0, 100.0], [100.0, 100.0, 100.0, 100.0, 100.0], [100.0, 100.0, 100.0, 100.0]]
If you want to use SQL Server Management Studio, you want to install the full Oracle client, not the Instant Client. The full Oracle client is on the same download page as the Oracle database. Assuming that you are installing on a 64-bit version of Windows, I expect you want the "Oracle Database 11g Release 2 Client (11.2.0.1.0) for Microsoft Windows (x64)" download. This is several hundred MB rather than a couple of MB for the Instant Client.
I know this is an old topic but this feature has now been implemented since SQL Server 2017. The parameter you're looking for is FIELDQUOTE= which defaults to '"'. See more on https://docs.microsoft.com/en-us/sql/t-sql/statements/bulk-insert-transact-sql?view=sql-server-2017
Given a radius length r and an angle t in radians and a circle's center (h,k), you can calculate the coordinates of a point on the circumference as follows (this is pseudo-code, you'll have to adapt it to your language):
float x = r*cos(t) + h;
float y = r*sin(t) + k;
I like and learned a lot from Lasse V. Karlsen. I modified it into the following example, which highlights pretty well the difference between shallow dictionary copies and deep copies:
import copy
my_dict = {'a': [1, 2, 3], 'b': [4, 5, 6]}
my_copy = copy.copy(my_dict)
my_deepcopy = copy.deepcopy(my_dict)
Now if you change
my_dict['a'][2] = 7
and do
print("my_copy a[2]: ",my_copy['a'][2],",whereas my_deepcopy a[2]: ", my_deepcopy['a'][2])
you get
>> my_copy a[2]: 7 ,whereas my_deepcopy a[2]: 3
The solution of Rohan will fix the problem as the error message will not be shown but the emulator will not use the hardware acceleration and thus be again very slow.
I recommend instead to install the Intel Hardware Accelerated Execution Manager as described here:
For Q2 this is a solution that is a bit more inefficient than the others, but still has O(N) runtime and takes O(k) space.
The idea is to run the original algorithm two times. In the first one you get a total number which is missing, which gives you an upper bound of the missing numbers. Let's call this number N
. You know that the missing two numbers are going to sum up to N
, so the first number can only be in the interval [1, floor((N-1)/2)]
while the second is going to be in [floor(N/2)+1,N-1]
.
Thus you loop on all numbers once again, discarding all numbers that are not included in the first interval. The ones that are, you keep track of their sum. Finally, you'll know one of the missing two numbers, and by extension the second.
I have a feeling that this method could be generalized and maybe multiple searches run in "parallel" during a single pass over the input, but I haven't yet figured out how.
Do you want to insert one dictionary into the other, as one of its elements, or do you want to reference the values of one dictionary from the keys of another?
Previous answers have already covered the first case, where you are creating a dictionary within another dictionary.
To re-reference the values of one dictionary into another, you can use dict.update
:
>>> d1 = {1: [1]}
>>> d2 = {2: [2]}
>>> d1.update(d2)
>>> d1
{1: [1], 2: [2]}
A change to a value that's present in both dictionaries will be visible in both:
>>> d1[2].append('appended')
>>> d1
{1: [1], 2: [2, 'appended']}
>>> d2
{2: [2, 'appended']}
This is the same as copying the value over or making a new dictionary with it, i.e.
>>> d3 = {1: d1[1]}
>>> d3[1].append('appended from d3')
>>> d1[1]
[1, 'appended from d3']
Making Node.js code sync is essential in few aspects such as database. But actual advantage of Node.js lies in async code. As it is single thread non-blocking.
we can sync it using important functionality Fiber() Use await() and defer () we call all methods using await(). then replace the callback functions with defer().
Normal Async code.This uses CallBack functions.
function add (var a, var b, function(err,res){
console.log(res);
});
function sub (var res2, var b, function(err,res1){
console.log(res);
});
function div (var res2, var b, function(err,res3){
console.log(res3);
});
Sync the above code using Fiber(), await() and defer()
fiber(function(){
var obj1 = await(function add(var a, var b,defer()));
var obj2 = await(function sub(var obj1, var b, defer()));
var obj3 = await(function sub(var obj2, var b, defer()));
});
I hope this will help. Thank You
I'm a little out of touch with the details of how MySQL deals with nulls, but here's two things to try:
SELECT * FROM match WHERE id NOT IN
( SELECT id FROM email WHERE id IS NOT NULL) ;
SELECT
m.*
FROM
match m
LEFT OUTER JOIN email e ON
m.id = e.id
AND e.id IS NOT NULL
WHERE
e.id IS NULL
The second query looks counter intuitive, but it does the join condition and then the where condition. This is the case where joins and where clauses are not equivalent.
I was using (goggle location picker (with much more customisation in functions and UI) ) so I copy this package(complete) and using in my app in one folder but since dart code analyser analyses one flutter project so I found that those which are referencing from inside of this package is not working then I copy only lib folder(of google location picker) in my original project folder and voila this worked for me. This solution took me a time of 3 days. I know this is not the question but it might help someone to save 3 days.
theharshest's answer is the best solution, but FYI the problem you were encountering has to do with the fact that a Tag object in Beautiful Soup acts like a Python dictionary. If you access tag['name'] on a tag that doesn't have a 'name' attribute, you'll get a KeyError.
For the select tag, angular provides the ng-options directive. It gives you the specific framework to set up options and set a default. Here is the updated fiddle using ng-options that works as expected: http://jsfiddle.net/FxM3B/4/
Updated HTML (code stays the same)
<body ng-app ng-controller="AppCtrl">
<div>Operator is: {{filterCondition.operator}}</div>
<select ng-model="filterCondition.operator" ng-options="operator.value as operator.displayName for operator in operators">
</select>
</body>
FYI: If the Icon doesn't appear, ensure your local or remote notification configuration contains the correct icon name i.e
'largeIcon' => 'ic_launcher',
'smallIcon' => 'ic_launcher' // defaults to ic_launcher,
gravity--Applies to its own view.
layout-gravity---Applies to view related to its parent.
I like Calibri.
var firstColumn = new List<string>();
var lastColumn = new List<string>();
// your code for reading CSV file
foreach(var line in file)
{
var array = line.Split(';');
firstColumn.Add(array[0]);
lastColumn.Add(array[1]);
}
var firstArray = firstColumn.ToArray();
var lastArray = lastColumn.ToArray();
Maybe you can try this
var str = "'SELECT___100E___7',24";
var res = str.split(',').pop();
If NEW_TABLE already exists then ...
insert into new_table
select * from old_table
/
If you want to create NEW_TABLE based on the records in OLD_TABLE ...
create table new_table as
select * from old_table
/
If the purpose is to create a new but empty table then use a WHERE clause with a condition which can never be true:
create table new_table as
select * from old_table
where 1 = 2
/
Remember that CREATE TABLE ... AS SELECT creates only a table with the same projection as the source table. The new table does not have any constraints, triggers or indexes which the original table might have. Those still have to be added manually (if they are required).
export default
is used to create local registration for Vue component.
Here is a great article that explain more about components https://frontendsociety.com/why-you-shouldnt-use-vue-component-ff019fbcac2e
This will get you a string array of all the resources:
System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames();
Instead of forcing an F5 keypress when you're just trying to get the page to postback, you can call a postback based on a JS event (even mousemove or timer_tick if you want it to fire all the time). Use the code at http://weblogs.asp.net/mnolton/archive/2003/06/04/8260.aspx as a reference.
For npm: you can run:
npm update -g typescript
By default, it will install latest version.
For yarn, you can run:
yarn upgrade typescript
Or you can remove the orginal version, run yarn global remove typescript
, and then execute yarn global add typescript
, by default it will also install the latest version of typescript.
more details, you can read yarn docs.
Use brackets to group the OR statements.
mysql_query("SELECT * FROM Drinks WHERE email='$Email' AND (date='$Date_Today' OR date='$Date_Yesterday' OR date='$Date_TwoDaysAgo' OR date='$Date_ThreeDaysAgo' OR date='$Date_FourDaysAgo' OR date='$Date_FiveDaysAgo' OR date='$Date_SixDaysAgo' OR date='$Date_SevenDaysAgo')");
You can also use IN
mysql_query("SELECT * FROM Drinks WHERE email='$Email' AND date IN ('$Date_Today','$Date_Yesterday','$Date_TwoDaysAgo','$Date_ThreeDaysAgo','$Date_FourDaysAgo','$Date_FiveDaysAgo','$Date_SixDaysAgo','$Date_SevenDaysAgo')");
those are miliseconds, just divide them by 1000, since gmtime expects seconds ...
time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1236472051807/1000.0))
It's my solution:
First, define boolean that indicate if navigation bar is visible or not.
boolean navigationBarVisibility = true //because it's visible when activity is created
Second create method that hide navigation bar.
private void setNavigationBarVisibility(boolean visibility){
if(visibility){
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
navigationBarVisibility = false;
}
else
navigationBarVisibility = true;
}
By default, if you click to activity after hide navigation bar, navigation bar will be visible. So we got it's state if it visible we will hide it.
Now set OnClickListener to your view. I use a surfaceview so for me:
playerSurface.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setNavigationBarVisibility(navigationBarVisibility);
}
});
Also, we must call this method when activity is launched. Because we want hide it at the beginning.
setNavigationBarVisibility(navigationBarVisibility);
This is not a perfect solution but it sort of does work.
In the select tag, include the following attributes where 'n' is the number of dropdown rows that would be visible.
<select size="1" position="absolute" onclick="size=(size!=1)?n:1;" ...>
There are three problems with this solution. 1) There is a quick flash of all the elements shown during the first mouse click. 2) The position is set to 'absolute' 3) Even if there are less than 'n' items the dropdown box will still be for the size of 'n' items.
You can add the src
folder to build path by:
src
folder.And you are done. Hope this help.
EDIT: Refer to the Eclipse documentation
Surely have a mutex-wrapped variable initialised to false
, that the thread sets to true
as the last thing it does before exiting. Is that atomic enough for your needs?
Tested successfully in FF 18 and Chrome 24:
Insert in head:
<script>
function closeWindow() {
window.open('','_parent','');
window.close();
}
</script>
HTML:
<a href="javascript:closeWindow();">Close Window</a>
Credits go to Marcos J. Drake.
using (SqlConnection connection = new SqlConnection("Data Source=localhost;Initial Catalog=LoginScreen;Integrated Security=True"))
{
SqlCommand command =
new SqlCommand("select * from Pending_Tasks WHERE CustomerId=...", connection);
connection.Open();
SqlDataReader read= command.ExecuteReader();
while (read.Read())
{
CustID.Text = (read["Customer_ID"].ToString());
CustName.Text = (read["Customer_Name"].ToString());
Add1.Text = (read["Address_1"].ToString());
Add2.Text = (read["Address_2"].ToString());
PostBox.Text = (read["Postcode"].ToString());
PassBox.Text = (read["Password"].ToString());
DatBox.Text = (read["Data_Important"].ToString());
LanNumb.Text = (read["Landline"].ToString());
MobNumber.Text = (read["Mobile"].ToString());
FaultRep.Text = (read["Fault_Report"].ToString());
}
read.Close();
}
Make sure you have data in the query : select * from Pending_Tasks and you are using "using System.Data.SqlClient;"
method 1 <input type="text" onclick="this.disabled=false;" disabled>
<hr>
method 2 <input type="text" onclick="this.removeAttribute('disabled');" disabled>
<hr>
method 3 <input type="text" onclick="this.removeAttribute('readonly');" readonly>
code of the previous answers don't seem to work in inline mode, but there is a workaround: method 3.
The code below was tested on iPhone, iPad (iOS13), Safari (Catalina). It was able to autoplay the YouTube video on all devices. Make sure the video is muted and the playsinline parameter is on. Those are the magic parameters that make it work.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, minimum-scale=1.0, user-scalable=yes">
</head>
<body>
<!-- 1. The <iframe> (video player) will replace this <div> tag. -->
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
width: '100%',
videoId: 'osz5tVY97dQ',
playerVars: { 'autoplay': 1, 'playsinline': 1 },
events: {
'onReady': onPlayerReady
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.mute();
event.target.playVideo();
}
</script>
</body>
</html>
You should call this function from the controller.
angular.module('App', [])
.controller('CinemaCtrl', ['$scope', function($scope) {
myFunction();
}]);
Even with normal javascript/html your function won't run on page load as all your are doing is defining the function, you never call it. This is really nothing to do with angular, but since you're using angular the above would be the "angular way" to invoke the function.
Obviously better still declare the function in the controller too.
Edit: Actually I see your "onload" - that won't get called as angular injects the HTML into the DOM. The html is never "loaded" (or the page is only loaded once).
let str = "Hello World"
console.log(str.substring(1, 3)) // el -> Excludes the last index
console.log(str.substr(1, 3)) // ell -> Includes the last index
Even if your data falls within your specified limits (e.g. c(0, 335)
), adding a geom_jitter()
statement could push some points outside those limits, producing the same error message.
library(ggplot2)
range(mtcars$hp)
#> [1] 52 335
# No jitter -- no error message
ggplot(mtcars, aes(mpg, hp)) +
geom_point() +
scale_y_continuous(limits=c(0,335))
# Jitter is too large -- this generates the error message
ggplot(mtcars, aes(mpg, hp)) +
geom_point() +
geom_jitter(position = position_jitter(w = 0.2, h = 0.2)) +
scale_y_continuous(limits=c(0,335))
#> Warning: Removed 1 rows containing missing values (geom_point).
Created on 2020-08-24 by the reprex package (v0.3.0)
This workflow works best for me:
git checkout -b develop
...make some changes...
...notice master has been updated...
...commit changes to develop...
git checkout master
git pull
...bring those changes back into develop...
git checkout develop
git rebase master
...make some more changes...
...commit them to develop...
...merge them into master...
git checkout master
git pull
git merge develop
Here is an alternate solution for version 4.x of Select2. You can use listeners to catch the focus event and then open the select.
$('#test').select2({
// Initialisation here
}).data('select2').listeners['*'].push(function(name, target) {
if(name == 'focus') {
$(this.$element).select2("open");
}
});
Find the working example here based the exampel created by @tonywchen
There actually is now a GAC Utility for .NET 4.0. It is found in the Microsoft Windows 7 and .NET 4.0 SDK (the SDK supports multiple OSs -- not just Windows 7 -- so if you are using a later OS from Microsoft the odds are good that it's supported).
This is the SDK. You can download the ISO or do a Web install. Kind-of overkill to download the entire thing if all you want is the GAC Util; however, it does work.
If you're using PostgreSQL you can use DISTINCT ON
to find the first row in a group.
SELECT customer.*, purchase.*
FROM customer
JOIN (
SELECT DISTINCT ON (customer_id) *
FROM purchase
ORDER BY customer_id, date DESC
) purchase ON purchase.customer_id = customer.id
Note that the DISTINCT ON
field(s) -- here customer_id
-- must match the left most field(s) in the ORDER BY
clause.
Caveat: This is a nonstandard clause.
It's been more than 6 years since the question was asked, but I didn't find any tool to clean up my repository. So I wrote one myself in python to get rid of old jars. Maybe it will be useful for someone:
from os.path import isdir
from os import listdir
import re
import shutil
dry_run = False # change to True to get a log of what will be removed
m2_path = '/home/jb/.m2/repository/' # here comes your repo path
version_regex = '^\d[.\d]*$'
def check_and_clean(path):
files = listdir(path)
for file in files:
if not isdir('/'.join([path, file])):
return
last = check_if_versions(files)
if last is None:
for file in files:
check_and_clean('/'.join([path, file]))
elif len(files) == 1:
return
else:
print('update ' + path.split(m2_path)[1])
for file in files:
if file == last:
continue
print(file + ' (newer version: ' + last + ')')
if not dry_run:
shutil.rmtree('/'.join([path, file]))
def check_if_versions(files):
if len(files) == 0:
return None
last = ''
for file in files:
if re.match(version_regex, file):
if last == '':
last = file
if len(last.split('.')) == len(file.split('.')):
for (current, new) in zip(last.split('.'), file.split('.')):
if int(new) > int(current):
last = file
break
elif int(new) < int(current):
break
else:
return None
else:
return None
return last
check_and_clean(m2_path)
It recursively searches within the .m2
repository and if it finds a catalog where different versions reside it removes all of them but the newest.
Say you have the following tree somewhere in your .m2 repo:
.
+-- antlr
+-- 2.7.2
¦ +-- antlr-2.7.2.jar
¦ +-- antlr-2.7.2.jar.sha1
¦ +-- antlr-2.7.2.pom
¦ +-- antlr-2.7.2.pom.sha1
¦ +-- _remote.repositories
+-- 2.7.7
+-- antlr-2.7.7.jar
+-- antlr-2.7.7.jar.sha1
+-- antlr-2.7.7.pom
+-- antlr-2.7.7.pom.sha1
+-- _remote.repositories
Then the script removes version 2.7.2 of antlr and what is left is:
.
+-- antlr
+-- 2.7.7
+-- antlr-2.7.7.jar
+-- antlr-2.7.7.jar.sha1
+-- antlr-2.7.7.pom
+-- antlr-2.7.7.pom.sha1
+-- _remote.repositories
If any old version, that you actively use, will be removed. It can easily be restored with maven (or other tools that manage dependencies).
You can get a log of what is going to be removed without actually removing it by setting dry_run = False
. The output will go like this:
update /org/projectlombok/lombok
1.18.2 (newer version: 1.18.6)
1.16.20 (newer version: 1.18.6)
This means, that versions 1.16.20 and 1.18.2 of lombok will be removed and 1.18.6 will be left untouched.
The file can be found on my github (the latest version).
less will look in its environment to see if there is a variable named LESS
You can set LESS in one of your ~/.profile (.bash_rc, etc, etc) and then anytime you run less
from the comand line, it will find the LESS.
Try adding this
export LESS="-CQaix4"
This is the setup I use, there are some behaviors embedded in that may confuse you, so you can find out about what all of these mean from the help function in less
, just tap the 'h' key and nose around, or run less --help
.
Edit:
I looked at the help, and noticed there is also an -r
option
-r -R .... --raw-control-chars --RAW-CONTROL-CHARS
Output "raw" control characters.
I agree that cat
may be the most exact match to your stated needs.
cat -vet file | less
Will add '$' at end of each line and convert tab char to visual '^I'.
cat --help
(edited)
-e equivalent to -vE
-E, --show-ends display $ at end of each line
-t equivalent to -vT
-T, --show-tabs display TAB characters as ^I
-v, --show-nonprinting use ^ and M- notation, except for LFD and TAB
I hope this helps.