In my case I forgot it was packaging conflict jar vs pom. I forgot to write
<packaging>pom</packaging>
In every child pom.xml file
If you need to do anything more with office documents in Java, go for POI as mentioned.
For simple reading/writing an excel document like you requested, you can use the CSV format (also as mentioned):
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class CsvWriter {
public static void main(String args[]) throws IOException {
String fileName = "test.xls";
PrintWriter out = new PrintWriter(new FileWriter(fileName));
out.println("a,b,c,d");
out.println("e,f,g,h");
out.println("i,j,k,l");
out.close();
BufferedReader in = new BufferedReader(new FileReader(fileName));
String line = null;
while ((line = in.readLine()) != null) {
Scanner scanner = new Scanner(line);
String sep = "";
while (scanner.hasNext()) {
System.out.println(sep + scanner.next());
sep = ",";
}
}
in.close();
}
}
If you are using Android Studio 3.0 or above make sure your project build.gradle should have content similar to-
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
}
}
allprojects {
repositories {
google()
jcenter()
}
}
Note- position really matters add google() before jcenter()
And for below Android Studio 3.0 and starting from support libraries 26.+ your project build.gradle must look like this-
allprojects {
repositories {
jcenter()
maven {
url "https://maven.google.com"
}
}
}
check these links below for more details-
You can add leading zeroes to a variable (value up to 99) like this in batch:
IF 1%Var% LSS 100 SET Var=0%Var%
So you'd need to parse your date and time components out into separate variables, treat them all like this, then concatenate them back together to create the file name.
However, your underlying method for parsing date and time is dependent on system locale settings. If you're happy for your code not to be portable to other machines, that's probably fine, but if you expect it to work in different international contexts then you'll need a different approach, for example by reading out the registry settings:
HKEY_CURRENT_USER\Control Panel\International\iDate
HKEY_CURRENT_USER\Control Panel\International\iTime
HKEY_CURRENT_USER\Control Panel\International\iTLZero
(That last one controls whether there is a leading zero on times, but not dates as far as I know).
Just use
$location.url();
Instead of
$location.path();
This should do the trick
df = data.frame(date=c("2012-02-01", "2012-02-01", "2012-02-02"))
dow <- function(x) format(as.Date(x), "%A")
df$day <- dow(df$date)
df
#Returns:
date day
1 2012-02-01 Wednesday
2 2012-02-01 Wednesday
3 2012-02-02 Thursday
I used:
pip install Pillow
and pip installed PIL in Lib\site-packages. When I moved PIL to Lib everything worked fine. I'm on Windows 10.
Simple answer. Use the Angular CLI and issue the
ng build
command in the root directory of your project. The site will be created in the dist directory and you can deploy that to any web server.
This will build for test, if you have production settings in your app you should use
ng build --prod
This will build the project in the dist
directory and this can be pushed to the server.
Much has happened since I first posted this answer. The CLI is finally at a 1.0.0 so following this guide go upgrade your project should happen before you try to build. https://github.com/angular/angular-cli/wiki/stories-rc-update
distanceTo will give you the distance in meters between the two given location ej target.distanceTo(destination).
distanceBetween give you the distance also but it will store the distance in a array of float( results[0]). the doc says If results has length 2 or greater, the initial bearing is stored in results[1]. If results has length 3 or greater, the final bearing is stored in results[2]
hope that this helps
i've used distanceTo to get the distance from point A to B i think that is the way to go.
If you don't mind using 3rd party libraries, AOL's cyclops-react lib (disclosure I am a contributor) has extensions for all JDK Collection types, including List. The ListX interface extends java.util.List and adds a large number of useful operators, including filter.
You can simply write-
ListX<Long> sourceLongList = ListX.of(1L, 10L, 50L, 80L, 100L, 120L, 133L, 333L);
ListX<Long> targetLongList = sourceLongList.filter(l -> l > 100);
ListX also can be created from an existing List (via ListX.fromIterable)
You can use the -notmatch operator to get the lines that don't have the characters you are interested in.
Get-Content $FileName | foreach-object {
if ($_ -notmatch $arrayofStringsNotInterestedIn) { $) }
You have to access to your class atributes.
To access to it atributes, you have to do:
person.id
person.name
where
person
is an instance of your class Person.
This can be done if the attibutes can be accessed, if not, you must use setters and getters...
android:ellipsize="marquee"
This only works when your TextView
has the focus.
As an alternative solution to the CASE
statement, a table-driven approach can be used:
DECLARE @Product TABLE (ID INT, Obsolete VARCHAR(10), InStock VARCHAR(10))
INSERT INTO @Product VALUES
(1,'N','Y'),
(2,'A','B'),
(3,'N','B'),
(4,'A','Y')
SELECT P.* , ISNULL(Stmt.Saleable,0) Saleable
FROM
@Product P
LEFT JOIN
( VALUES
( 'N', 'Y', 1 )
) Stmt (Obsolete, InStock, Saleable)
ON P.InStock = Stmt.InStock OR P.Obsolete = Stmt.Obsolete
Result:
ID Obsolete InStock Saleable
----------- ---------- ---------- -----------
1 N Y 1
2 A B 0
3 N B 1
4 A Y 1
In this line ...
if (*message == "\0") {
... as you can see in the warning ...
warning: comparison between pointer and integer ('int' and 'char *')
... you are actually comparing an int
with a char *
, or more specifically, an int
with an address to a char
.
To fix this, use one of the following:
if(*message == '\0') ...
if(message[0] == '\0') ...
if(!*message) ...
On a side note, if you'd like to compare strings you should use strcmp
or strncmp
, found in string.h
.
For a single dimension array, you use the Length
property:
int size = theArray.Length;
For multiple dimension arrays the Length
property returns the total number of items in the array. You can use the GetLength
method to get the size of one of the dimensions:
int size0 = theArray.GetLength(0);
If you are using moment.js you can do it easily.
var start = moment("2018-03-10", "YYYY-MM-DD");
var end = moment("2018-03-15", "YYYY-MM-DD");
//Difference in number of days
moment.duration(start.diff(end)).asDays();
//Difference in number of weeks
moment.duration(start.diff(end)).asWeeks();
If you want to find difference between a given date and current date in number of days (ignoring time), make sure to remove time from moment object of current date as below
moment().startOf('day')
To find difference between a given date and current date in number of days
var given = moment("2018-03-10", "YYYY-MM-DD");
var current = moment().startOf('day');
//Difference in number of days
moment.duration(given.diff(current)).asDays();
Disabled
controls cannot be successful, and a successful control is "valid" for submission.
This is the reason why disabled controls don't submit with the form.
This has now been fixed in Firefox Nightly and will be in the next firefox build.
Please see this bug for more information https://bugzilla.mozilla.org/show_bug.cgi?id=610733
I got it solved by setting JDK. I got a pop up saying that Setup JDK when I placed mouse over the error.
For the ones not wanting to create an entrypoint script like me, you actually can start mysqld at build-time and then execute the mysql commands in your Dockerfile like so:
RUN mysqld_safe & until mysqladmin ping; do sleep 1; done && \
mysql -uroot -e "CREATE DATABASE somedb;" && \
mysql -uroot -e "CREATE USER 'someuser'@'localhost' IDENTIFIED BY 'somepassword';" && \
mysql -uroot -e "GRANT ALL PRIVILEGES ON somedb.* TO 'someuser'@'localhost';"
The key here is to send mysqld_safe to background with the single &
sign.
One of the best ways to retrieve the username and password is to view and update them. The User Model provides a perfect way to do so.
Navigate to your root directory i,e. where you "manage.py" file is located using your console or other application such as Git.
Retrieve the Python shell using the command "python manage.py shell".
Import the User Model by typing the following command "from django.contrib.auth.models import User"
Get all the users by typing the following command "users = User.objects.all()"
Print a list of the users For Python 2 users use the command "print users" For Python 3 users use the command "print(users)" The first user is usually the admin.
Select the user you wish to change their password e.g.
"user = users[0]"
Set the password
user.set_password('name_of_the_new_password_for_user_selected')
Save the new password
"user.save()"
Start the server and log in using the username and the updated password.
If you simply want to go to another page, then what you might need is a link that looks like a button with a href like so:
<a href="/#/somepage.html" class="button">Back to Listings</a>
Hope this helps.
I found this here that describes how to set the VBA Project Password. You should be able to modify it to unset the VBA Project Password.
This one does not use SendKeys.
Let me know if this helps! JFV
I believe that the body height being returned is the visible height. If you need the total page height, you could wrap your div tags in a containing div and get the height of that.
This would be eliminate the select query from running twice and be better for performance:
Declare @rate int
select
@rate = rate
from
d_payment_index
where
fy = 2007
and payment_year = 2008
and program_id = 18
IF @@rowcount = 0
Set @rate = 0
Select @rate 'rate'
@Simple-Solution
I use a simple Python HTTP server. When in the directory of the Angular app in question (using a MBP with Mavericks 10.9 and Python 2.x) I simply run
python -m SimpleHTTPServer 8080
And that sets up the simple server on port 8080 letting you visit localhost:8080
on your browser to view the app in development.
Hope that helped!
Try this:
dataTable.Columns["Marks"].ColumnName = "SubjectMarks";
A little addition to other answers here, for anyone having the same error while using the right lib version and the right class.
When I upgraded to
appcompat-v7:22.1.0
In which ActionBarActivity
is deprecated and empty and AppCompatActivty
is the way to go, due to some glitch in Android Studio, It didn't quite pick up on version change.
i.e. Even though Gradle ran without errors, the IDE itself kept saying
Cannot resolve symbol 'AppCompatActivity'
(and it also wasn't available through the Ctrl+N
search)
I looked into the .idea/libraries
folder and noticed there's no appropriate metafile for the new version of the lib.
So, using the old-reliable File->Invalidate Caches/Restart did the trick. Always try this when you feel something is magically wrong with Android Studio. And then Disable offline mode and sync.
You can use the parse
static method from Uri
//...
import android.net.Uri;
//...
Uri myUri = Uri.parse("http://stackoverflow.com")
No submodule mapping found in .gitmodules for path 'OtherLibrary/MKStore' when
$ git submodule update --init
I didn't know why the error occur. After spending a minute and found the answer in stackoverflow.
$ git rm --cached OtherLibrary/MKStore
and then update the submodule again. It's working fine.
http://en.saturngod.net/no-submodule-mapping-found-in-gitmodules
If when running react-native run-android
command the second line of the trace is
JS server not recognized, continuing with build...
it means packager for the app cannot be started and the app will fail to load without some extra steps. Note that the end of the trace still reports success:
BUILD SUCCESSFUL
The problem is probably some port conflict (in my case it was the default IIS site that I completely forgot about). Another manifestation of the problem would be a failure to open http://localhost:8081/debugger-ui
URL in Chrome.
Once the port conflict is resolved the trace will report
Starting JS server...
then an additional Node window will open (node ...cli.js start
) and the app will load/reload successfully.
After that you should be able to open debug console in Chrome with http://localhost:8081/debugger-ui
.
Aligning to 6 bytes is not weird, because it is aligning to addresses multiple to 4.
So basically you have 34 bytes in your structure and the next structure should be placed on the address, that is multiple to 4. The closest value after 34 is 36. And this padding area counts into the size of the structure.
There are multiple ways to obfuscate code. Here's just one example:
(lambda _, __, ___, ____, _____, ______, _______, ________:
getattr(
__import__(True.__class__.__name__[_] + [].__class__.__name__[__]),
().__class__.__eq__.__class__.__name__[:__] +
().__iter__().__class__.__name__[_____:________]
)(
_, (lambda _, __, ___: _(_, __, ___))(
lambda _, __, ___:
chr(___ % __) + _(_, __, ___ // __) if ___ else
(lambda: _).func_code.co_lnotab,
_ << ________,
(((_____ << ____) + _) << ((___ << _____) - ___)) + (((((___ << __)
- _) << ___) + _) << ((_____ << ____) + (_ << _))) + (((_______ <<
__) - _) << (((((_ << ___) + _)) << ___) + (_ << _))) + (((_______
<< ___) + _) << ((_ << ______) + _)) + (((_______ << ____) - _) <<
((_______ << ___))) + (((_ << ____) - _) << ((((___ << __) + _) <<
__) - _)) - (_______ << ((((___ << __) - _) << __) + _)) + (_______
<< (((((_ << ___) + _)) << __))) - ((((((_ << ___) + _)) << __) +
_) << ((((___ << __) + _) << _))) + (((_______ << __) - _) <<
(((((_ << ___) + _)) << _))) + (((___ << ___) + _) << ((_____ <<
_))) + (_____ << ______) + (_ << ___)
)
)
)(
*(lambda _, __, ___: _(_, __, ___))(
(lambda _, __, ___:
[__(___[(lambda: _).func_code.co_nlocals])] +
_(_, __, ___[(lambda _: _).func_code.co_nlocals:]) if ___ else []
),
lambda _: _.func_code.co_argcount,
(
lambda _: _,
lambda _, __: _,
lambda _, __, ___: _,
lambda _, __, ___, ____: _,
lambda _, __, ___, ____, _____: _,
lambda _, __, ___, ____, _____, ______: _,
lambda _, __, ___, ____, _____, ______, _______: _,
lambda _, __, ___, ____, _____, ______, _______, ________: _
)
)
)
You should do it this way, if you want to get yesterday and tomorrow at 00:00:00 time:
DateTime yesterday = DateTime.Today.AddDays(-1);
DateTime tomorrow = DateTime.Today.AddDays(1); // Output example: 6. 02. 2016 00:00:00
Just bare in mind that if you do it this way:
DateTime yesterday = DateTime.Now.AddDays(-1);
DateTime tomorrow = DateTime.Now.AddDays(1); // Output example: 6. 02. 2016 18:09:23
then you will get the current time minus one day, and not yesterday at 00:00:00 time.
If you came here from Google, trying to find where your previously created virtualenv installation ended up, and why there is no command to find it, here's the low-down.
The design of virtualenv
has a fundamental flaw of not being able to keep track of it's own created environments. Someone was not quite in their right mind when they created virtualenv
without having a rudimentary way to keep track of already created environments, and certainly not fit for a time and age when most pip requirements require multi-giga-byte installations, which should certainly not go into some obscure .virtualenvs
sub-directory of your ~/home.
IMO, the created virtualenv directory should be created in $CWD
and a file called ~/.virtualenv
(in home) should keep track of the name and path of that creation. Which is a darn good reason to use Conda/Miniconda3 instead, which does seem to keep good track of this.
As answered here, the only way to keep track of this, is to install yet another package called virtualenvwrapper
. If you don't do that, you will have to search for the created directory by yourself. Clearly, if you don't remember the name or the location it was created with/at, you will most likely never find your virtual environment again...
One try to remedy the situation in windows, is by putting the following functions into your powershell profile:
# wrap virtualenv.exe and write last argument (presumably
# your virtualenv name) to the file: $HOME/.virtualenv.
function ven { if( $args.count -eq 0) {Get-Content ~/.virtualenv } else {virtualenv.exe "$args"; Write-Output ("{0} `t{1}" -f $args[-1],$PWD) | Out-File -Append $HOME/.virtualenv }}
# List what's in the file or the directories under ~/.virtualenvs
function lsven { try {Get-Content ~/.virtualenv } catch {Get-ChildItem ~\.virtualenvs -Directory | Select-Object -Property Name } }
WARNING: This will write to ~\.virtualenv
...
Use:
1..10 | % { write "loop $_" }
Output:
PS D:\temp> 1..10 | % { write "loop $_" }
loop 1
loop 2
loop 3
loop 4
loop 5
loop 6
loop 7
loop 8
loop 9
loop 10
Thanks Ravi and other users .... Nevertheless I have got the solution
SELECT @phoneNumber=
CASE
WHEN ISNULL(rdg2.nPhoneNumber ,'0') in ('0','-',NULL)
THEN ISNULL(rdg2.nMobileNumber, '0')
WHEN ISNULL(rdg2.nMobileNumber, '0') in ('0','-',NULL)
THEN '0'
ELSE ISNULL(rdg2.nPhoneNumber ,'0')
END
FROM tblReservation_Details_Guest rdg2
WHERE nReservationID=@nReservationID
Just need to put '0' instead of 0
SELECT ID from bugs WHERE user=Me ORDER BY CREATED_STAMP DESC; BY CREATED_STAMP DESC fetches those data at index first which last created.
I hope it will resolve your problem
private void showImage(ImageView img, String absolutePath) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap bitmapPicture = BitmapFactory.decodeFile(absolutePath);
img.setImageBitmap(bitmapPicture);
}
If you have a numpy array, you can do the following:
>>> import numpy as np
>>> a = np.array([133, 53, 234, 241])
>>> a.astype(np.uint8).data.hex()
'8535eaf1'
Just download and install "Samsung Kies" from this link. and everything would work as required.
Before installing, uninstall the drivers you have installed for your device.
Update:
Two possible solutions:
This may work for you, Please try this.
<form>
<div class="form-inline">
<div class="controls-row">
<label class="control-label">Some label</label>
<label class="radio inline">
<input type="radio" value="1" />First
</label>
<label class="radio inline">
<input type="radio" value="2" />Second
</label>
</div>
</div>
</form>
One way which works for sure
SELECT a.distributor_id,
(SELECT COUNT(*) FROM myTable WHERE level='personal' and distributor_id = a.distributor_id) as PersonalCount,
(SELECT COUNT(*) FROM myTable WHERE level='exec' and distributor_id = a.distributor_id) as ExecCount,
(SELECT COUNT(*) FROM myTable WHERE distributor_id = a.distributor_id) as TotalCount
FROM (SELECT DISTINCT distributor_id FROM myTable) a ;
EDIT:
See @KevinBalmforth's break down of performance for why you likely don't want to use this method and instead should opt for @Taryn?'s answer. I'm leaving this so people can understand their options.
I know it's a "very long time" since this question was first asked. Just in case, if it helps someone,
Adding relationships is well supported by MS via SQL Server Compact Tool Box (https://sqlcetoolbox.codeplex.com/). Just install it, then you would get the option to connect to the Compact Database using the Server Explorer Window. Right click on the primary table , select "Table Properties". You should have the following window, which contains "Add Relations" tab allowing you to add relations.
This can be done just using Copy-Item. No need to use Get-Childitem. I think you are just overthinking it.
Copy-Item -Path C:\MyFolder -Destination \\Server\MyFolder -recurse -Force
I just tested it and it worked for me.
edit: included suggestion from the comments
# Add wildcard to source folder to ensure consistent behavior
Copy-Item -Path $sourceFolder\* -Destination $targetFolder -Recurse
You can also make this a little simpler by using the following inside the event code:
private void MyDataGridView_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
rowToDelete = e.RowIndex;
MyDataGridView.Rows.RemoveAt(rowToDelete);
MyDataGridView.ClearSelection();
}
}
The folder containing your Anaconda installation contains a subfolder called conda-meta
with json files for all installed packages, including one for Anaconda itself. Look for anaconda-<version>-<build>.json
.
My file is called anaconda-5.0.1-py27hdb50712_1.json
, and at the bottom is more info about the version:
"installed_by": "Anaconda2-5.0.1-Windows-x86_64.exe",
"link": { "source": "C:\\ProgramData\\Anaconda2\\pkgs\\anaconda-5.0.1-py27hdb50712_1" },
"name": "anaconda",
"platform": "win",
"subdir": "win-64",
"url": "https://repo.continuum.io/pkgs/main/win-64/anaconda-5.0.1-py27hdb50712_1.tar.bz2",
"version": "5.0.1"
(Slightly edited for brevity.)
The output from conda -V
is the conda version.
Brew users can use reference below,
command to install requests
:
python3 -m pip install requests
pip is the package installer for Python and you need the package requests
.
See also this previous answer which recommends the not
keyword
How to check if a list is empty in Python?
It generalizes to more than just lists:
>>> a = ""
>>> not a
True
>>> a = []
>>> not a
True
>>> a = 0
>>> not a
True
>>> a = 0.0
>>> not a
True
>>> a = numpy.array([])
>>> not a
True
Notably, it will not work for "0" as a string because the string does in fact contain something - a character containing "0". For that you have to convert it to an int:
>>> a = "0"
>>> not a
False
>>> a = '0'
>>> not int(a)
True
You cannot have the WHERE
clause in an INSERT
statement.
insert into table1(data) VALUES(:data) where sno ='45830'
Should be
insert into table1(data) VALUES(:data)
Update: You have removed that from your code (I assume you copied the code in wrong). You want to increase your allowed packet size:
SET GLOBAL max_allowed_packet=32M
Change the 32M
(32 megabytes) up/down as required. Here is a link to the MySQL documentation on the subject.
const [people, setPeople] = useState(data);
const handleRemove = (id) => {
const newPeople = people.filter((person) => { person.id !== id;
setPeople( newPeople );
});
};
<button onClick={() => handleRemove(id)}>Remove</button>
You can Just save the response(pdf,doc etc..) by option on the right side of the response in postman check this image
For more Details check this
https://learning.getpostman.com/docs/postman/sending_api_requests/responses/
I used fake UserAgent.
How to use:
from fake_useragent import UserAgent
import requests
ua = UserAgent()
print(ua.chrome)
header = {'User-Agent':str(ua.chrome)}
print(header)
url = "https://www.hybrid-analysis.com/recent-submissions?filter=file&sort=^timestamp"
htmlContent = requests.get(url, headers=header)
print(htmlContent)
Output:
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1309.0 Safari/537.17
{'User-Agent': 'Mozilla/5.0 (X11; OpenBSD i386) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36'}
<Response [200]>
file_get_contents(php://input) - gets the raw POST data and you need to use this when you write APIs and need XML/JSON/... input that cannot be decoded to $_POST by PHP some example :
send by post JSON string
<input type="button" value= "click" onclick="fn()">
<script>
function fn(){
var js_obj = {plugin: 'jquery-json', version: 2.3};
var encoded = JSON.stringify( js_obj );
var data= encoded
$.ajax({
type: "POST",
url: '1.php',
data: data,
success: function(data){
console.log(data);
}
});
}
</script>
1.php
//print_r($_POST); //empty!!! don't work ...
var_dump( file_get_contents('php://input'));
A common cause is cloning using the default (HTTPS) instead of SSH. You can correct this by going to your repository, clicking "Clone or download", then clicking the "Use SSH" button above the URL field and updating the URL of your origin remote like this:
git remote set-url origin [email protected]:username/repo.git
This is documented at GitHub: Switching remote URLs from HTTPS to SSH.
Inspired by jfriend00, this worked for me
const seconds = new Date();
// wait 5 seconds for flag to become true
const waitTime = 5
const extraSeconds = seconds.setSeconds(seconds.getSeconds() + waitTime);
while (Date.now() < extraSeconds) {
// break when flag is false
if (flag === false) break;
}
_x000D_
The below code works for me, for both accessing and changing a pixel value.
For accessing pixel's channel value :
for (int i = 0; i < image.cols; i++) {
for (int j = 0; j < image.rows; j++) {
Vec3b intensity = image.at<Vec3b>(j, i);
for(int k = 0; k < image.channels(); k++) {
uchar col = intensity.val[k];
}
}
}
For changing a pixel value of a channel :
uchar pixValue;
for (int i = 0; i < image.cols; i++) {
for (int j = 0; j < image.rows; j++) {
Vec3b &intensity = image.at<Vec3b>(j, i);
for(int k = 0; k < image.channels(); k++) {
// calculate pixValue
intensity.val[k] = pixValue;
}
}
}
`
Source : Accessing pixel value
Simpler version of yfeldblum's answer, that is simpler and works well also with large files:
require 'csv'
CSV.foreach(filename, headers: true) do |row|
Moulding.create!(row.to_hash)
end
No need for with_indifferent_access
or symbolize_keys
, and no need to read in the file to a string first.
It doesnt't keep the whole file in memory at once, but reads in line by line and creates a Moulding per line.
Try this...
In kotlin
fun determineScreenDensityCode(): String {
return when (resources.displayMetrics.densityDpi) {
DisplayMetrics.DENSITY_LOW -> "ldpi"
DisplayMetrics.DENSITY_MEDIUM -> "mdpi"
DisplayMetrics.DENSITY_HIGH -> "hdpi"
DisplayMetrics.DENSITY_XHIGH, DisplayMetrics.DENSITY_280 -> "xhdpi"
DisplayMetrics.DENSITY_XXHIGH, DisplayMetrics.DENSITY_360, DisplayMetrics.DENSITY_400, DisplayMetrics.DENSITY_420 -> "xxhdpi"
DisplayMetrics.DENSITY_XXXHIGH, DisplayMetrics.DENSITY_560 -> "xxxhdpi"
else -> "Unknown code ${resources.displayMetrics.densityDpi}"
}
}
You can call by println("density: ${determineScreenDensityCode()}")
and the output will be System.out: density: xxxhdpi
If all you need is a subject line (as in an alert message) simply do:
mailx -s "This is all she wrote" < /dev/null "myself@myaddress"
<br>
<%String id = request.getParameter("track_id");%>
<%if (id.length() == 0) {%>
<b><h1>Please Enter Tracking ID</h1></b>
<% } else {%>
<div class="container">
<table border="1" class="table" >
<thead>
<tr class="warning" >
<td ><h4>Track ID</h4></td>
<td><h4>Source</h4></td>
<td><h4>Destination</h4></td>
<td><h4>Current Status</h4></td>
</tr>
</thead>
<%
try {
connection = DriverManager.getConnection(connectionUrl + database, userid, password);
statement = connection.createStatement();
String sql = "select * from track where track_id="+ id;
resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
%>
<tr class="info">
<td><%=resultSet.getString("track_id")%></td>
<td><%=resultSet.getString("source")%></td>
<td><%=resultSet.getString("destination")%></td>
<td><%=resultSet.getString("status")%></td>
</tr>
<%
}
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
</table>
<%}%>
</body>
The best way is to use simple math
>>> a = 8
>>> a**(1./3.)
2.0
EDIT
For Negative numbers
>>> a = -8
>>> -(-a)**(1./3.)
-2.0
Complete Program for all the requirements as specified
x = int(input("Enter an integer: "))
if x>0:
ans = x**(1./3.)
if ans ** 3 != abs(x):
print x, 'is not a perfect cube!'
else:
ans = -((-x)**(1./3.))
if ans ** 3 != -abs(x):
print x, 'is not a perfect cube!'
print 'Cube root of ' + str(x) + ' is ' + str(ans)
<form action="portfolio.html">
<button type="link" class="btn btn-primary btn-lg">View Work</button>
</form>
I just figured this out, and it links perfectly to another page without having my default link settings over ride my button classes! :)
This is the approach I've used. It's quite straightforward, and works just fine.
In the CK editor root directory there is a file named config.js
I added this (you don't need the querystring stuff, this is just for our file manager). I also included some skinning and changing of the default buttons shown:
CKEDITOR.editorConfig = function(config) {
config.skin = 'v2';
config.startupFocus = false;
config.filebrowserBrowseUrl = '/admin/content/filemanager.aspx?path=Userfiles/File&editor=FCK';
config.filebrowserImageBrowseUrl = '/admin/content/filemanager.aspx?type=Image&path=Userfiles/Image&editor=FCK';
config.toolbar_Full =
[
['Source', '-', 'Preview', '-'],
['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Print', 'SpellChecker'], //, 'Scayt'
['Undo', 'Redo', '-', 'Find', 'Replace', '-', 'SelectAll', 'RemoveFormat'],
'/',
['Bold', 'Italic', 'Underline', 'Strike', '-', 'Subscript', 'Superscript'],
['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', 'Blockquote'],
['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
['Link', 'Unlink', 'Anchor'],
['Image', 'Flash', 'Table', 'HorizontalRule', 'SpecialChar'],
'/',
['Styles', 'Format', 'Templates'],
['Maximize', 'ShowBlocks']
];
};
Then, our file manager calls this:
opener.SetUrl('somefilename');
If you want PHP file caching only, you can use eAccelerator directly. Very easy to install and configure, and give great results.
But too bad, they removed the eaccelerator_put and eaccelerator_put from the latest version 0.9.6.
Insert command tree in bash.
Also, there is a DOS comnand "tree". You can displays directory paths and files in each subdirectory with command:
tree /F
If your current min. API level is 23, you can simply use getColor()
like we are using for getString()
:
//example
textView.setTextColor(getColor(R.color.green));
// if context is not available(ex: not in activity) use with context.getColor()
If you want below API level 23
, just use this:
textView.setTextColor(getResources().getColor(R.color.green));
But note that getResources().getColor()
is deprecated in API Level 23
. In that case replace above with:
textView.setTextColor(ContextCompat.getColor(this /*context*/, R.color.green)) //Im in an activity, so I can use `this`
ContextCompat: Helper for accessing features in Context
If You want, you can constraint with SDK_INT
like below:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
textView.setTextColor(getColor(R.color.green));
} else {
textView.setTextColor(getResources().getColor(R.color.green));
}
I'm not sure that I understood your problem, but I think you can divide loop. On the part of the function and the part without it and save the two loops.
replace it with index of the array.
array[index] = new_value;
I was also facing this problem trying to run an ASP .NET MVC project after a minor update to our codebase, even though it compiled without errors:
Compiler Error Message: CS0012: The type 'System.Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
Our project had never run into this problem, so I was skeptical about changing configuration files before finding out the root cause. From the error logs I was able to locate this detailed compiler output which pointed out to what was really happening:
warning CS1685: The predefined type 'System.Runtime.CompilerServices.ExtensionAttribute' is defined in multiple assemblies in the global alias; using definition from 'c:\Windows\Microsoft.NET\Framework64\v4.0.30319\mscorlib.dll'
c:\Users\Admin\Software Development\source-control\Binaries\Publish\WebApp\Views\Account\Index.cshtml(35,20): error CS0012: The type 'System.Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
c:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\meseems.webapp\68e2ea0f\8c5ee951\assembly\dl3\52ad4dac\84698469_3bb3d401\System.Collections.Immutable.DLL: (Location of symbol related to previous error)
Apparently a new package added to our project was referencing an older version of the .NET Framework, causing the "definition in multiple assemblies" issue (CS1685), which led to the razor view compiler error at runtime.
I removed the incompatible package (System.Collections.Immutable.dll) and the problem stopped occurring. However, if the package cannot be removed in your project you will need to try Baahubali's answer.
A[A==NDV]=numpy.nan
A==NDV will produce a boolean array that can be used as an index for A
An alternative approach would be:
df1 = sqlContext.createDataFrame(
[(1, "a", 2.0), (2, "b", 3.0), (3, "c", 3.0)],
("x1", "x2", "x3"))
df2 = sqlContext.createDataFrame(
[(1, "f", -1.0), (2, "b", 0.0)], ("x1", "x2", "x4"))
df = df1.join(df2, ['x1','x2'])
df.show()
which outputs:
+---+---+---+---+
| x1| x2| x3| x4|
+---+---+---+---+
| 2| b|3.0|0.0|
+---+---+---+---+
With the main advantage being that the columns on which the tables are joined are not duplicated in the output, reducing the risk of encountering errors such as org.apache.spark.sql.AnalysisException: Reference 'x1' is ambiguous, could be: x1#50L, x1#57L.
Whenever the columns in the two tables have different names, (let's say in the example above, df2
has the columns y1
, y2
and y4
), you could use the following syntax:
df = df1.join(df2.withColumnRenamed('y1','x1').withColumnRenamed('y2','x2'), ['x1','x2'])
This might help:
<input type="number" step="1" pattern="\d+" />
step
is for convenience (and could be set to another integer), but pattern
does some actual enforcing.
Note that since pattern
matches the whole expression, it wasn't necessary to express it as ^\d+$
.
Even with this outwardly tight regular expression, Chrome and Firefox's implementations, interestingly allow for e
here (presumably for scientific notation) as well as -
for negative numbers, and Chrome also allows for .
whereas Firefox is tighter in rejecting unless the .
is followed by 0's only. (Firefox marks the field as red upon the input losing focus whereas Chrome doesn't let you input disallowed values in the first place.)
Since, as observed by others, one should always validate on the server (or on the client too, if using the value locally on the client or wishing to prevent the user from a roundtrip to the server).
You can use the -Dmaven.wagon.http.ssl.insecure=true
option
Just tell request that you are using json:true and forget about header and parse
var options = {
hostname: '127.0.0.1',
port: app.get('port'),
path: '/users',
method: 'GET',
json:true
}
request(options, function(error, response, body){
if(error) console.log(error);
else console.log(body);
});
and the same for post
var options = {
hostname: '127.0.0.1',
port: app.get('port'),
path: '/users',
method: 'POST',
json: {"name":"John", "lastname":"Doe"}
}
request(options, function(error, response, body){
if(error) console.log(error);
else console.log(body);
});
You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.
Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String
'Assign data to first item in array
compArray(1) = "asdf"
'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"
'Prints "ErrorState"
Debug.Print Computers("Computer Name")
Collections cannot be sorted so if you need to sort data you will probably want to use an array.
Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx
Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx
Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!
Edit:
Sub ArrayExample()
Dim subject As String
Dim TestArray() As String
Dim counter As Long
subject = "Example"
counter = Len(subject)
ReDim TestArray(1 To counter) As String
For counter = 1 To Len(subject)
TestArray(counter) = Right(Left(subject, counter), 1)
Next
End Sub
You can use SSH and SFTP as suggested here.
sftp -P 2222 [email protected]
; if you prefer a graphical interface, you can use FileZillaReplace user
and 10.0.2.15
with the appropriate values relevant to your configuration.
This is one of the few places that I disagree with the convention enough to go against it. TBH, I HATE that the definition of an enum and the instance of it can have the same name. I postfix all of my Enums with "Enum" specifically because it makes it clear what the context of it is in any given usage. IMO it makes the code much more readable.
public enum PersonTypesEnum {
smart,
sad,
funny,
angry
}
public class Person {
public PersonTypesEnum PersonType {get; set;}
}
Nobody will ever confuse what is the enum and what is the instance of it.
To build on top of @gboffi's and Ben Usman's answer:
In a situation where one has different lines in different subplots with the same color and label, one can do something along the lines of
labels_handles = {
label: handle for ax in fig.axes for handle, label in zip(*ax.get_legend_handles_labels())
}
fig.legend(
labels_handles.values(),
labels_handles.keys(),
loc="upper center",
bbox_to_anchor=(0.5, 0),
bbox_transform=plt.gcf().transFigure,
)
i had a situation where i can't change old code, so added this javascript function to calculate center point and zoom level:
//input_x000D_
var tempdata = ["18.9400|72.8200-19.1717|72.9560-28.6139|77.2090"];_x000D_
_x000D_
function getCenterPosition(tempdata){_x000D_
var tempLat = tempdata[0].split("-");_x000D_
var latitudearray = [];_x000D_
var longitudearray = [];_x000D_
var i;_x000D_
for(i=0; i<tempLat.length;i++){_x000D_
var coordinates = tempLat[i].split("|");_x000D_
latitudearray.push(coordinates[0]);_x000D_
longitudearray.push(coordinates[1]);_x000D_
}_x000D_
latitudearray.sort(function (a, b) { return a-b; });_x000D_
longitudearray.sort(function (a, b) { return a-b; });_x000D_
var latdifferenece = latitudearray[latitudearray.length-1] - latitudearray[0];_x000D_
var temp = (latdifferenece / 2).toFixed(4) ;_x000D_
var latitudeMid = parseFloat(latitudearray[0]) + parseFloat(temp);_x000D_
var longidifferenece = longitudearray[longitudearray.length-1] - longitudearray[0];_x000D_
temp = (longidifferenece / 2).toFixed(4) ;_x000D_
var longitudeMid = parseFloat(longitudearray[0]) + parseFloat(temp);_x000D_
var maxdifference = (latdifferenece > longidifferenece)? latdifferenece : longidifferenece;_x000D_
var zoomvalue; _x000D_
if(maxdifference >= 0 && maxdifference <= 0.0037) //zoom 17_x000D_
zoomvalue='17';_x000D_
else if(maxdifference > 0.0037 && maxdifference <= 0.0070) //zoom 16_x000D_
zoomvalue='16';_x000D_
else if(maxdifference > 0.0070 && maxdifference <= 0.0130) //zoom 15_x000D_
zoomvalue='15';_x000D_
else if(maxdifference > 0.0130 && maxdifference <= 0.0290) //zoom 14_x000D_
zoomvalue='14';_x000D_
else if(maxdifference > 0.0290 && maxdifference <= 0.0550) //zoom 13_x000D_
zoomvalue='13';_x000D_
else if(maxdifference > 0.0550 && maxdifference <= 0.1200) //zoom 12_x000D_
zoomvalue='12';_x000D_
else if(maxdifference > 0.1200 && maxdifference <= 0.4640) //zoom 10_x000D_
zoomvalue='10';_x000D_
else if(maxdifference > 0.4640 && maxdifference <= 1.8580) //zoom 8_x000D_
zoomvalue='8';_x000D_
else if(maxdifference > 1.8580 && maxdifference <= 3.5310) //zoom 7_x000D_
zoomvalue='7';_x000D_
else if(maxdifference > 3.5310 && maxdifference <= 7.3367) //zoom 6_x000D_
zoomvalue='6';_x000D_
else if(maxdifference > 7.3367 && maxdifference <= 14.222) //zoom 5_x000D_
zoomvalue='5';_x000D_
else if(maxdifference > 14.222 && maxdifference <= 28.000) //zoom 4_x000D_
zoomvalue='4';_x000D_
else if(maxdifference > 28.000 && maxdifference <= 58.000) //zoom 3_x000D_
zoomvalue='3';_x000D_
else_x000D_
zoomvalue='1';_x000D_
return latitudeMid+'|'+longitudeMid+'|'+zoomvalue;_x000D_
}
_x000D_
In this example of a rc.local script I use io redirection at the very first line of execution to my own log file:
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
exec 2> /tmp/rc.local.log # send stderr from rc.local to a log file
exec 1>&2 # send stdout to the same log file
set -x # tell sh to display commands before execution
/opt/stuff/somefancy.error.script.sh
exit 0
I think most of the answers have completely ignored UINavigationViewController
, so I handled this use case with following implementation.
+ (UIViewController *)topMostController {
UIViewController * topController = [UIApplication sharedApplication].keyWindow.rootViewController;
while (topController.presentedViewController || [topController isMemberOfClass:[UINavigationController class]]) {
if([topController isMemberOfClass:[UINavigationController class]]) {
topController = [topController childViewControllers].lastObject;
} else {
topController = topController.presentedViewController;
}
}
return topController;
}
If you'd like to read a file from the command line or from stdin, you can also use the fileinput
module:
# reader.py
import fileinput
content = []
for line in fileinput.input():
content.append(line.strip())
fileinput.close()
Pass files to it like so:
$ python reader.py textfile.txt
Read more here: http://docs.python.org/2/library/fileinput.html
You could also use the RANK function
=RANK(C2,$C$2:$C$7,0)
It would return data like your example:
| A | B | C
1 | name | position | points
2 | person1 | 1 | 10
3 | person2 | 2 | 9
4 | person3 | 2 | 9
5 | person4 | 2 | 9
6 | person5 | 5 | 8
7 | person6 | 6 | 7
The 'Points' column needs to be sorted into descending order.
If you are using it with Hibernate, you'll have to explicitly define the annotation CascadeType.DELETE_ORPHAN
, which can be used in conjunction with JPA CascadeType.ALL
.
If you don't plan to use Hibernate, you'll have to explicitly first delete the child elements and then delete the main record to avoid any orphan records.
execution sequence
With JPA 2.0, you can now use the option orphanRemoval = true
@OneToMany(mappedBy="foo", orphanRemoval=true)
I don't know of any way doing this in SQL Developer. You can see all the other schemas and their objects (if you have the correct privileges) when looking in "Other Users" -> "< Schemaname >".
In your case, either use the method described above or create a new connection for the schema in which you want to work or create synonyms for all the tables you wish to access.
If you would work in SQL*Plus, issuing ALTER SESSION SET CURRENT_SCHEMA=MY_NAME
would set your current schema (This is probably what your DBA means).
This caution message also occurs if the response is invalid and therefore dropped by the browser.
In my case the request was correctly sent to the server, the server-side code then produced an error and my custom error handling returned the error message in the HTTP status message field. But this error was not received on the client side, due to invalid characters in the error message (described here http://aspnetwebstack.codeplex.com/workitem/1386) which resulted in corrupt response headers.
Other answers work, but
To get the full/default price:
$product->get_price_html();
Setting innerHtml of input value wont do anything good here, try with other element like span, or just display previously made and hidden error message. You can set value of name field tho.
<head>
<script type="text/javascript">
function validate() {
if (myform.fname.value.length == 0) {
document.getElementById("fname").value = "this is invalid name ";
document.getElementById("errorMessage").style.display = "block";
}
}
</script>
</head>
<body>
<form name="myform">First_Name
<input type="text" id="fname" name="fname" onblur="validate()"></input> <span id="errorMessage" style="display:none;">name field must not be empty</span>
<br>
<br>Last_Name
<input type="text" id="lname" name="lname" onblur="validate()"></input>
<br>
<input type="button" value="check" />
</form>
</body>
Using an escaped string (a.k.a. escaped value):
width: ~"calc(100% - 200px)";
Also, in case you need to mix Less math with escaped strings:
width: calc(~"100% - 15rem +" (10px+5px) ~"+ 2em");
Compiles to:
width: calc(100% - 15rem + 15px + 2em);
This works as Less concatenates values (the escaped strings and math result) with a space by default.
You have set the upstream of that branch
(see:
--set-upstream-to
all the time?"git branch -f --track my_local_branch origin/my_remote_branch # OR (if my_local_branch is currently checked out): $ git branch --set-upstream-to my_local_branch origin/my_remote_branch
(git branch -f --track
won't work if the branch is checked out: use the second command git branch --set-upstream-to
instead, or you would get "fatal: Cannot force update the current branch.
")
That means your branch is already configured with:
branch.my_local_branch.remote origin
branch.my_local_branch.merge my_remote_branch
Git already has all the necessary information.
In that case:
# if you weren't already on my_local_branch branch:
git checkout my_local_branch
# then:
git pull
is enough.
If you hadn't establish that upstream branch relationship when it came to push your 'my_local_branch
', then a simple git push -u origin my_local_branch:my_remote_branch
would have been enough to push and set the upstream branch.
After that, for the subsequent pulls/pushes, git pull
or git push
would, again, have been enough.
There are lots of solutions:
b = Arrays.copyOf(a, a.length);
Which allocates a new array, copies over the elements of a
, and returns the new array.
Or
b = new int[a.length];
System.arraycopy(a, 0, b, 0, b.length);
Which copies the source array content into a destination array that you allocate yourself.
Or
b = a.clone();
which works very much like Arrays.copyOf()
. See this thread.
Or the one you posted, if you reverse the direction of the assignment in the loop:
b[i] = a[i]; // NOT a[i] = b[i];
Here's some sample code that does it.
#include <string.h>
#include <stdlib.h>
char * replace(
char const * const original,
char const * const pattern,
char const * const replacement
) {
size_t const replen = strlen(replacement);
size_t const patlen = strlen(pattern);
size_t const orilen = strlen(original);
size_t patcnt = 0;
const char * oriptr;
const char * patloc;
// find how many times the pattern occurs in the original string
for (oriptr = original; patloc = strstr(oriptr, pattern); oriptr = patloc + patlen)
{
patcnt++;
}
{
// allocate memory for the new string
size_t const retlen = orilen + patcnt * (replen - patlen);
char * const returned = (char *) malloc( sizeof(char) * (retlen + 1) );
if (returned != NULL)
{
// copy the original string,
// replacing all the instances of the pattern
char * retptr = returned;
for (oriptr = original; patloc = strstr(oriptr, pattern); oriptr = patloc + patlen)
{
size_t const skplen = patloc - oriptr;
// copy the section until the occurence of the pattern
strncpy(retptr, oriptr, skplen);
retptr += skplen;
// copy the replacement
strncpy(retptr, replacement, replen);
retptr += replen;
}
// copy the rest of the string.
strcpy(retptr, oriptr);
}
return returned;
}
}
#include <stdio.h>
int main(int argc, char * argv[])
{
if (argc != 4)
{
fprintf(stderr,"usage: %s <original text> <pattern> <replacement>\n", argv[0]);
exit(-1);
}
else
{
char * const newstr = replace(argv[1], argv[2], argv[3]);
if (newstr)
{
printf("%s\n", newstr);
free(newstr);
}
else
{
fprintf(stderr,"allocation error\n");
exit(-2);
}
}
return 0;
}
@Deprecated
public static int toInt(Object obj)
{
if (obj instanceof String)
{
return Integer.parseInt((String) obj);
} else if (obj instanceof Number)
{
return ((Number) obj).intValue();
} else
{
String toString = obj.toString();
if (toString.matches("-?\d+"))
{
return Integer.parseInt(toString);
}
throw new IllegalArgumentException("This Object doesn't represent an int");
}
}
As you can see, this isn't a very efficient way of doing it. You simply have to be sure of what kind of object you have. Then convert it to an int the right way.
I had this problem, and turns out the problem was that I had used
new SimpleJdbcCall(jdbcTemplate)
.withProcedureName("foo")
instead of
new SimpleJdbcCall(jdbcTemplate)
.withFunctionName("foo")
Full sync has few tasks:
git reset HEAD --hard
git clean -f
git pull origin master
Or else, what I prefer is that, I may create a new branch with the latest from the remote using:
git checkout origin/master -b <new branch name>
origin is my remote repository reference, and master is my considered branch name. These may different from yours.
I am adding this answer because none of the answer used Comma operator
.
It's very easy with destructuring assignment
and ,
operator
const object = { a: 5, b: 6, c: 7 };
const picked = ({a,c} = object, {a,c})
console.log(picked);
_x000D_
Members must be resolvable at compile time to be called directly from C#. Otherwise you must use reflection or dynamic objects.
Reflection
namespace ConsoleApplication1
{
using System;
using System.Reflection;
class Program
{
static void Main(string[] args)
{
var DLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");
foreach(Type type in DLL.GetExportedTypes())
{
var c = Activator.CreateInstance(type);
type.InvokeMember("Output", BindingFlags.InvokeMethod, null, c, new object[] {@"Hello"});
}
Console.ReadLine();
}
}
}
Dynamic (.NET 4.0)
namespace ConsoleApplication1
{
using System;
using System.Reflection;
class Program
{
static void Main(string[] args)
{
var DLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");
foreach(Type type in DLL.GetExportedTypes())
{
dynamic c = Activator.CreateInstance(type);
c.Output(@"Hello");
}
Console.ReadLine();
}
}
}
I've not looked into this but shooting from the hip I'd say that they dropped command line support in the portable. The reason people don't do much command line stuff in portable applications is that the OS (windows in your case) requires that executables be added to the %path% inclusion list.
If that requirement is not met using command line utilities is rather tedious.
7z -a .
would be
d:\portable\z7\z7 -a c:\to\archive\folder*.*
Typing that out for everything is why GUI's make sense with things like portable apps it (the app) can remember it's own location and handle that stuff for you and if you can't run it you know it's not attached.
If you really want the portable app to contain that though you can always install the full version and pull the required 7z.exe out and put it into the portable folder making sure it's in with the required dll's.
You'll have to set your path when you hit the shell after making sure it's attached.
http://www.redfernplace.com/software-projects/patheditor/ -- a good path editor (down) usefull if you have lots of path information 20+ get's hard to read.
http://www.softpedia.com/get/System/System-Miscellaneous/Path-Editor.shtml -- alternet source for path editor
It's not advisable to modify your system path for temproary "portable" drives though manualy do that by:
set path=%path%;"d:\portable\z7\";
when you run dos cmd.exe or http://sourceforge.net/p/conemu/home/Home/
The other answers address other problems better I'm not going to try..
http://www.codejacked.com/zip-up-files-from-the-command-line/ -- good reference for command line usage of z7 and z7a.
PS: sorry for the necro but I figured it needed a more direct answer to why (even if it's just speculative).
You can use
t1<- t1[-4:-6,-7:-9]
or
t1 <- t1[-(4:6), -(7:9)]
or
t1 <- t1[-c(4, 5, 6), -c(7, 8, 9)]
You can pass vectors
to select rows/columns
to be deleted. First two methods are useful if you are trying to delete contiguous rows/columns. Third method is useful if You are trying to delete discrete rows/columns
.
> t1 <- array(1:20, dim=c(10,10));
> t1[-c(1, 4, 6, 7, 9), -c(2, 3, 8, 9)]
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 2 12 2 12 2 12
[2,] 3 13 3 13 3 13
[3,] 5 15 5 15 5 15
[4,] 8 18 8 18 8 18
[5,] 10 20 10 20 10 20
I just knocked this up using the Reactive Extensions and remembered this question:
public class BlockingQueue<T>
{
private readonly Subject<T> _queue;
private readonly IEnumerator<T> _enumerator;
private readonly object _sync = new object();
public BlockingQueue()
{
_queue = new Subject<T>();
_enumerator = _queue.GetEnumerator();
}
public void Enqueue(T item)
{
lock (_sync)
{
_queue.OnNext(item);
}
}
public T Dequeue()
{
_enumerator.MoveNext();
return _enumerator.Current;
}
}
Not necessarily entirely safe, but very simple.
You can use the decompose method in bs4:
soup = bs4.BeautifulSoup('<body><a href="http://example.com/">I linked to <i>example.com</i></a></body>')
for a in soup.find('a').children:
if isinstance(a,bs4.element.Tag):
a.decompose()
print soup
Out: <html><body><a href="http://example.com/">I linked to </a></body></html>
select date_format(str_to_date('31/12/2010', '%d/%m/%Y'), '%Y%m');
or
select date_format(str_to_date('12/31/2011', '%m/%d/%Y'), '%Y%m');
hard to tell from your example
The max length of a varchar in MySQL 5.6.12 is 4294967295.
I found the datetime.isoformat in the documentation. It seems to do what you want:
datetime.isoformat([sep])
Return a string representing the date and time in ISO 8601 format, YYYY-MM-DDTHH:MM:SS.mmmmmm or, if microsecond is 0, YYYY-MM-DDTHH:MM:SS
If utcoffset() does not return None, a 6-character string is appended, giving the UTC offset in (signed) hours and minutes: YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if microsecond is 0 YYYY-MM-DDTHH:MM:SS+HH:MM
The optional argument sep (default 'T') is a one-character separator, placed between the date and time portions of the result. For example,
>>>
>>> from datetime import tzinfo, timedelta, datetime
>>> class TZ(tzinfo):
... def utcoffset(self, dt): return timedelta(minutes=-399)
...
>>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
'2002-12-25 00:00:00-06:39'
you have to iterate gridview Rows
for (int count = 0; count < grd.Rows.Count; count++)
{
if (((CheckBox)grd.Rows[count].FindControl("yourCheckboxID")).Checked)
{
((Label)grd.Rows[count].FindControl("labelID")).Text
}
}
First of all, don't create HTML elements by string concatenation. Use DOM manipulation. It's faster, cleaner, and less error-prone. This alone solves one of your problems. Then, just let it accept any array as an argument:
var options = [
set0 = ['Option 1','Option 2'],
set1 = ['First Option','Second Option','Third Option']
];
function makeUL(array) {
// Create the list element:
var list = document.createElement('ul');
for (var i = 0; i < array.length; i++) {
// Create the list item:
var item = document.createElement('li');
// Set its contents:
item.appendChild(document.createTextNode(array[i]));
// Add it to the list:
list.appendChild(item);
}
// Finally, return the constructed list:
return list;
}
// Add the contents of options[0] to #foo:
document.getElementById('foo').appendChild(makeUL(options[0]));
Here's a demo. You might also want to note that set0
and set1
are leaking into the global scope; if you meant to create a sort of associative array, you should use an object:
var options = {
set0: ['Option 1', 'Option 2'],
set1: ['First Option', 'Second Option', 'Third Option']
};
And access them like so:
makeUL(options.set0);
Using http://crsmithdev.com/arrow/
arrowObj = arrow.Arrow.strptime('2017-02-20 10:00:00', '%Y-%m-%d %H:%M:%S' , 'US/Eastern')
arrowObj.to('UTC') or arrowObj.to('local')
This library makes life easy :)
There are two options here.
Edit
@Html.Hidden("clubid", ViewBag.Club.id)
or
@using(Html.BeginForm("action", "controller",
new { clubid = @Viewbag.Club.id }, FormMethod.Post, null)
In my case, I had a textbox that was attached to a datepicker. The only solution that worked for me was to handle it inside the onSelect event of the datepicker.
<input type="text" id="bookdate">
$("#bookdate").datepicker({
onSelect: function (selected) {
//handle change event here
}
});
It depends on what you do: Web developement, business software, etc. I think for this kind of stuff, you don't need math.
If you want to do computer graphics, audio/video processing, AI, cryptography, etc. then you need a math background, otherwise you can simply not do it.
If you aren't a fan of passing in a string, I prefer how @sesperanto has done it, except to make it even more concise, you could drop Float::INFINITY
in the date range and instead simply use created_at: p[:date]..
Note.where(
user_id: current_user.id,
notetype: p[:note_type],
created_at: p[:date]..
).order(:date, :created_at)
Take note that this will change the query to be >=
instead of >
. If that's a concern, you could always add a unit of time to the date by running something like p[:date] + 1.day..
<script language="javascript" type="text/javascript">
function selectFunction() {
var printStr = document.getElementById("select").options[0].value
alert(printStr);
document.getElementById("select").selectedIndex = 0;
}
</script>
Often times we are interested in calculating the full significant digits, but for the visual aesthetics, we may want to see only few decimal point when we display the dataframe.
In jupyter-notebook, pandas can utilize the html formatting taking advantage of the method called style
.
For the case of just seeing two significant digits of some columns, we can use this code snippet:
import numpy as np
import pandas as pd
df = pd.DataFrame({'var1': [1.458315, 1.576704, 1.629253, 1.6693310000000001, 1.705139, 1.740447, 1.77598, 1.812037, 1.85313, 1.9439849999999999],
'var2': [1.500092, 1.6084450000000001, 1.652577, 1.685456, 1.7120959999999998, 1.741961, 1.7708009999999998, 1.7993270000000001, 1.8229819999999999, 1.8684009999999998],
'var3': [-0.0057090000000000005, -0.005122, -0.0047539999999999995, -0.003525, -0.003134, -0.0012230000000000001, -0.0017230000000000001, -0.002013, -0.001396, 0.005732]})
print(df)
var1 var2 var3
0 1.458315 1.500092 -0.005709
1 1.576704 1.608445 -0.005122
2 1.629253 1.652577 -0.004754
3 1.669331 1.685456 -0.003525
4 1.705139 1.712096 -0.003134
5 1.740447 1.741961 -0.001223
6 1.775980 1.770801 -0.001723
7 1.812037 1.799327 -0.002013
8 1.853130 1.822982 -0.001396
9 1.943985 1.868401 0.005732
df.style.format({'var1': "{:.2f}",'var2': "{:.2f}",'var3': "{:.2%}"})
Gives:
var1 var2 var3
id
0 1.46 1.50 -0.57%
1 1.58 1.61 -0.51%
2 1.63 1.65 -0.48%
3 1.67 1.69 -0.35%
4 1.71 1.71 -0.31%
5 1.74 1.74 -0.12%
6 1.78 1.77 -0.17%
7 1.81 1.80 -0.20%
8 1.85 1.82 -0.14%
9 1.94 1.87 0.57%
If display command is not found try following:
from IPython.display import display
df_style = df.style.format({'var1': "{:.2f}",'var2': "{:.2f}",'var3': "{:.2%}"})
display(df_style)
display
command, you need to have installed Ipython in your machine.display
command does not work in online python interpreter which do not have IPyton
installed such as https://repl.it/languages/python3From the Mozilla Developer Center:
The DOMContentLoaded event is fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading (the load event can be used to detect a fully-loaded page).
I used file upload example from,
http://www.mkyong.com/webservices/jax-rs/file-upload-example-in-jersey/
in my resource class i have below method
@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response attachupload(@FormDataParam("file") byte[] is,
@FormDataParam("file") FormDataContentDisposition fileDetail,
@FormDataParam("fileName") String flename){
attachService.saveAttachment(flename,is);
}
in my attachService.java i have below method
public void saveAttachment(String flename, byte[] is) {
// TODO Auto-generated method stub
attachmentDao.saveAttachment(flename,is);
}
in Dao i have
attach.setData(is);
attach.setFileName(flename);
in my HBM mapping is like
<property name="data" type="binary" >
<column name="data" />
</property>
This working for all type of files like .PDF,.TXT, .PNG etc.,
You can use a CSS3 transition
for this. Have a look at this example:
Here is the main code:
#box {
position : relative;
width : 100px;
height : 100px;
background-color : gray;
border : 5px solid black;
-webkit-transition : border 500ms ease-out;
-moz-transition : border 500ms ease-out;
-o-transition : border 500ms ease-out;
transition : border 500ms ease-out;
}
#box:hover {
border : 10px solid red;
}
Like Babel says in the docs, for Babel > 7.4.0 the module @babel/polyfill is deprecated, so it's recommended to use directly core-js and regenerator-runtime libraries that before were included in @babel/polyfill.
So this worked for me:
npm install --save [email protected]
npm install regenerator-runtime
then add to the very top of your initial js file:
import 'core-js/stable';
import 'regenerator-runtime/runtime';
Try this one, if you want to truncate based on Words instead of characters while also allowing an option to see the complete text.
Came here searching for a Read More solution based on words, sharing the custom Pipe
i ended up writing.
Pipe:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'readMore'
})
export class ReadMorePipe implements PipeTransform {
transform(text: any, length: number = 20, showAll: boolean = false, suffix: string = '...'): any {
if (showAll) {
return text;
}
if ( text.split(" ").length > length ) {
return text.split(" ").splice(0, length).join(" ") + suffix;
}
return text;
}
}
In Template:
<p [innerHTML]="description | readMore:30:showAll"></p>
<button (click)="triggerReadMore()" *ngIf="!showAll">Read More<button>
Component:
export class ExamplePage implements OnInit {
public showAll: any = false;
triggerReadMore() {
this.showAll = true;
}
}
In Module:
import { ReadMorePipe } from '../_helpers/read-more.pipe';
@NgModule({
declarations: [ReadMorePipe]
})
export class ExamplePageModule {}
If you are using multiple criteria, and want to count the number of non-blank cells in a particular column, you probably want to look at DCOUNTA.
e.g
A B C D E F G
1 Dog Cat Cow Dog Cat
2 x 1 x 1
3 x 2
4 x 1 nb Result:
5 x 2 nb 1
Formula in E5: =DCOUNTA(A1:C5,"Cow",E1:F2)
The answers here seem a bit inadequate so I'm adding my two cents:
The real solution is that there is generally a mismatch between what is stored in your provisioning profile (check at developer.apple.com -> members -> certificates -> the cert you're using [be sure to check if dev/production) and what is enabled in your app (double click project name), under horizontal menu select'Capabilities' (next to 'General').
If you've recently changed one of these, be sure to refresh your certificates under XCode -> Preferences -> Accounts -> Details -> Refresh Icon and restart XCode.
Instead:
public class PhotosFragment extends Fragment
You can use:
public class PhotosFragment extends ListFragment
It change the methods
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayList<ListviewContactItem> listContact = GetlistContact();
setAdapter(new ListviewContactAdapter(getActivity(), listContact));
}
onActivityCreated is void and you didn't need to return a view like in onCreateView
You can see an example here
Recently, I faced similar problem and I solved it using following approach
def round(value: Either[Double, Float], places: Int) = {
if (places < 0) 0
else {
val factor = Math.pow(10, places)
value match {
case Left(d) => (Math.round(d * factor) / factor)
case Right(f) => (Math.round(f * factor) / factor)
}
}
}
def round(value: Double): Double = round(Left(value), 0)
def round(value: Double, places: Int): Double = round(Left(value), places)
def round(value: Float): Double = round(Right(value), 0)
def round(value: Float, places: Int): Double = round(Right(value), places)
I used this SO issue. I have couple of overloaded functions for both Float\Double and implicit\explicit options. Note that, you need to explicitly mention the return type in case of overloaded functions.
I had this same problem. For me this solution worked for SQL Server 2008 R2 Express.
SQLEXPRWT_x64_ENU.exe
(This is the name of the
file I used)/Action=install /SKIPRULES=PerfMonCounterNotCorruptedCheck
Of course this does not fix the underlying issue but it is a workaround because this fix also works on the principle of skipping the Performance counter check in the setup. The difference is this method worked for me when doing it through the command line failed.
The real question is: Do these records have a one-to-one relationship or a one-to-many relationship?
TLDR Answer:
If one-to-one, use a JOIN
statement.
If one-to-many, use one (or many) SELECT
statements with server-side code optimization.
Why and How To Use SELECT for Optimization
SELECT
'ing (with multiple queries instead of joins) on large group of records based on a one-to-many relationship produces an optimal efficiency, as JOIN
'ing has an exponential memory leak issue. Grab all of the data, then use a server-side scripting language to sort it out:
SELECT * FROM Address WHERE Personid IN(1,2,3);
Results:
Address.id : 1 // First person and their address
Address.Personid : 1
Address.City : "Boston"
Address.id : 2 // First person's second address
Address.Personid : 1
Address.City : "New York"
Address.id : 3 // Second person's address
Address.Personid : 2
Address.City : "Barcelona"
Here, I am getting all of the records, in one select statement. This is better than JOIN
, which would be getting a small group of these records, one at a time, as a sub-component of another query. Then I parse it with server-side code that looks something like...
<?php
foreach($addresses as $address) {
$persons[$address['Personid']]->Address[] = $address;
}
?>
When Not To Use JOIN for Optimization
JOIN
'ing a large group of records based on a one-to-one relationship with one single record produces an optimal efficiency compared to multiple SELECT
statements, one after the other, which simply get the next record type.
But JOIN
is inefficient when getting records with a one-to-many relationship.
Example: The database Blogs has 3 tables of interest, Blogpost, Tag, and Comment.
SELECT * from BlogPost
LEFT JOIN Tag ON Tag.BlogPostid = BlogPost.id
LEFT JOIN Comment ON Comment.BlogPostid = BlogPost.id;
If there is 1 blogpost, 2 tags, and 2 comments, you will get results like:
Row1: tag1, comment1,
Row2: tag1, comment2,
Row3: tag2, comment1,
Row4: tag2, comment2,
Notice how each record is duplicated. Okay, so, 2 comments and 2 tags is 4 rows. What if we have 4 comments and 4 tags? You don't get 8 rows -- you get 16 rows:
Row1: tag1, comment1,
Row2: tag1, comment2,
Row3: tag1, comment3,
Row4: tag1, comment4,
Row5: tag2, comment1,
Row6: tag2, comment2,
Row7: tag2, comment3,
Row8: tag2, comment4,
Row9: tag3, comment1,
Row10: tag3, comment2,
Row11: tag3, comment3,
Row12: tag3, comment4,
Row13: tag4, comment1,
Row14: tag4, comment2,
Row15: tag4, comment3,
Row16: tag4, comment4,
Add more tables, more records, etc., and the problem will quickly inflate to hundreds of rows that are all full of mostly redundant data.
What do these duplicates cost you? Memory (in the SQL server and the code that tries to remove the duplicates) and networking resources (between SQL server and your code server).
Source: https://dev.mysql.com/doc/refman/8.0/en/nested-join-optimization.html ; https://dev.mysql.com/doc/workbench/en/wb-relationship-tools.html
multipart/form-data
Note. Please consult RFC2388 for additional information about file uploads, including backwards compatibility issues, the relationship between "multipart/form-data" and other content types, performance issues, etc.
Please consult the appendix for information about security issues for forms.
The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.
The content type "multipart/form-data" follows the rules of all multipart MIME data streams as outlined in RFC2045. The definition of "multipart/form-data" is available at the [IANA] registry.
A "multipart/form-data" message contains a series of parts, each representing a successful control. The parts are sent to the processing agent in the same order the corresponding controls appear in the document stream. Part boundaries should not occur in any of the data; how this is done lies outside the scope of this specification.
As with all multipart MIME types, each part has an optional "Content-Type" header that defaults to "text/plain". User agents should supply the "Content-Type" header, accompanied by a "charset" parameter.
application/x-www-form-urlencoded
This is the default content type. Forms submitted with this content type must be encoded as follows:
Control names and values are escaped. Space characters are replaced by +', and then reserved characters are escaped as described in [RFC1738], section 2.2: Non-alphanumeric characters are replaced by
%HH', a percent sign and two hexadecimal digits representing the ASCII code of the character. Line breaks are represented as "CR LF" pairs (i.e., %0D%0A').
The control names/values are listed in the order they appear in the document. The name is separated from the value by
=' and name/value pairs are separated from each other by `&'.
application/x-www-form-urlencoded
the body of the HTTP message sent to the server is essentially one giant query string -- name/value pairs are separated by the ampersand (&), and names are separated from values by the equals symbol (=). An example of this would be:
MyVariableOne=ValueOne&MyVariableTwo=ValueTwo
The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.
$('#myDiv').hide();
hide function is used to edit content and show function is used to show again.
For more please click on this link.
You can either have the newly inserted ID being output to the SSMS console like this:
INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')
You can use this also from e.g. C#, when you need to get the ID back to your calling app - just execute the SQL query with .ExecuteScalar()
(instead of .ExecuteNonQuery()
) to read the resulting ID
back.
Or if you need to capture the newly inserted ID
inside T-SQL (e.g. for later further processing), you need to create a table variable:
DECLARE @OutputTbl TABLE (ID INT)
INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID INTO @OutputTbl(ID)
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')
This way, you can put multiple values into @OutputTbl
and do further processing on those. You could also use a "regular" temporary table (#temp
) or even a "real" persistent table as your "output target" here.
Yes l1
and l2
will point to the same reference, same object.
If you want to create a new ArrayList based on the other ArrayList you do this:
List<String> l1 = new ArrayList<String>();
l1.add("Hello");
l1.add("World");
List<String> l2 = new ArrayList<String>(l1); //A new arrayList.
l2.add("Everybody");
The result will be l1
will still have 2 elements and l2
will have 3 elements.
If you want to plot lines instead of points, see this example, modified here to plot good/bad points representing a function as a black/red as appropriate:
def plot(xx, yy, good):
"""Plot data
Good parts are plotted as black, bad parts as red.
Parameters
----------
xx, yy : 1D arrays
Data to plot.
good : `numpy.ndarray`, boolean
Boolean array indicating if point is good.
"""
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
from matplotlib.colors import from_levels_and_colors
from matplotlib.collections import LineCollection
cmap, norm = from_levels_and_colors([0.0, 0.5, 1.5], ['red', 'black'])
points = np.array([xx, yy]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
lines = LineCollection(segments, cmap=cmap, norm=norm)
lines.set_array(good.astype(int))
ax.add_collection(lines)
plt.show()
I just the had same problem. I figured out that Intellisense stopped working after I took some databases offline and doing an Intellisense refresh (Ctrl-Shift-R). I brought the offline databases back online, did a refresh (Ctl-Shft-R) again and VOILA! Intellisense is working again.
What a crappy design. Maybe the population of Intellisense's lists chokes when a database exists but is offline. Thanks Microsoft.
Frank's answer is good but Firestore introduced array-contains
recently that makes it easier to do AND queries.
You can create a filters
field to add you filters. You can add as many values as you need. For example to filter by comedy and Jack Nicholson you can add the value comedy_Jack Nicholson
but if you also you want to by comedy and 2014 you can add the value comedy_2014
without creating more fields.
{
"movies": {
"movie1": {
"genre": "comedy",
"name": "As good as it gets",
"lead": "Jack Nicholson",
"year": 2014,
"filters": [
"comedy_Jack Nicholson",
"comedy_2014"
]
}
}
}
Each MAX function is evaluated individually. So MAX(CompletedDate) will return the value of the latest CompletedDate column and MAX(Notes) will return the maximum (i.e. alphabeticaly highest) value.
You need to structure your query differently to get what you want. This question had actually already been asked and answered several times, so I won't repeat it:
How to find the record in a table that contains the maximum value?
Try something like this:
with toupdate as (
select p.*,
(coalesce(max(interfaceid) over (), 0) +
row_number() over (order by (select NULL))
) as newInterfaceId
from prices
)
update p
set interfaceId = newInterfaceId
where interfaceId is NULL
This doesn't quite make them consecutive, but it does assign new higher ids. To make them consecutive, try this:
with toupdate as (
select p.*,
(coalesce(max(interfaceid) over (), 0) +
row_number() over (partition by interfaceId order by (select NULL))
) as newInterfaceId
from prices
)
update p
set interfaceId = newInterfaceId
where interfaceId is NULL
GetWindowThreadProcessId((IntPtr)app.Hwnd, out iProcessId);
wb.Close(true,Missing.Value,Missing.Value);
app.Quit();
System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName("Excel");
foreach (System.Diagnostics.Process p in process)
{
if (p.Id == iProcessId)
{
try
{
p.Kill();
}
catch { }
}
}
}
[DllImport("user32.dll")]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
uint iProcessId = 0;
this GetWindowThreadProcessId finds the correct Process Id o excell .... After kills it.... Enjoy It!!!
Let's take this:
class Person(val name:String,var age:Int )
def person =new Person("Kumar",12)
person.age=20
println(person.age)
and rewrite it with equivalent code
class Person(val name:String,var age:Int )
def person =new Person("Kumar",12)
(new Person("Kumar", 12)).age_=(20)
println((new Person("Kumar", 12)).age)
See, def
is a method. It will execute each time it is called, and each time it will return (a) new Person("Kumar", 12)
. And these is no error in the "assignment" because it isn't really an assignment, but just a call to the age_=
method (provided by var
).
If you don't need animation, this works:
[self.scrollView setContentOffset:CGPointMake(0, CGFLOAT_MAX) animated:NO];
For variable argument functions like printf
and scanf
, the arguments are promoted, for example, any smaller integer types are promoted to int
, float
is promoted to double
.
scanf
takes parameters of pointers, so the promotion rule takes no effect. It must use %f
for float*
and %lf
for double*
.
printf
will never see a float
argument, float
is always promoted to double
. The format specifier is %f
. But C99 also says %lf
is the same as %f
in printf
:
C99 ยง7.19.6.1 The
fprintf
function
l
(ell) Specifies that a followingd
,i
,o
,u
,x
, orX
conversion specifier applies to along int
orunsigned long int
argument; that a followingn
conversion specifier applies to a pointer to along int
argument; that a followingc
conversion specifier applies to awint_t
argument; that a followings
conversion specifier applies to a pointer to awchar_t
argument; or has no effect on a followinga
,A
,e
,E
,f
,F
,g
, orG
conversion specifier.
I think I see your problem, you need to use the @
syntax to define parameters you will pass in this way, also I'm not sure what loginID or password are doing you don't seem to define them anywhere and they are not being used as URL parameters so are they being sent as query parameters?
This is what I can suggest based on what I see so far:
.factory('MagComments', function ($resource) {
return $resource('http://localhost/dooleystand/ci/api/magCommenct/:id', {
loginID : organEntity,
password : organCommpassword,
id : '@magId'
});
})
The @magId
string will tell the resource to replace :id
with the property magId
on the object you pass it as parameters.
I'd suggest reading over the documentation here (I know it's a bit opaque) very carefully and looking at the examples towards the end, this should help a lot.
Thanks to DroidT, I made this:
I realize that if the Fragment does not execute onCreateView(), its view is not instantiated. So, if the fragment on back stack did not create its views, I save the last stored state, otherwise I build my own bundle with the data I want to save/restore.
1) Extend this class:
import android.os.Bundle;
import android.support.v4.app.Fragment;
public abstract class StatefulFragment extends Fragment {
private Bundle savedState;
private boolean saved;
private static final String _FRAGMENT_STATE = "FRAGMENT_STATE";
@Override
public void onSaveInstanceState(Bundle state) {
if (getView() == null) {
state.putBundle(_FRAGMENT_STATE, savedState);
} else {
Bundle bundle = saved ? savedState : getStateToSave();
state.putBundle(_FRAGMENT_STATE, bundle);
}
saved = false;
super.onSaveInstanceState(state);
}
@Override
public void onCreate(Bundle state) {
super.onCreate(state);
if (state != null) {
savedState = state.getBundle(_FRAGMENT_STATE);
}
}
@Override
public void onDestroyView() {
savedState = getStateToSave();
saved = true;
super.onDestroyView();
}
protected Bundle getSavedState() {
return savedState;
}
protected abstract boolean hasSavedState();
protected abstract Bundle getStateToSave();
}
2) In your Fragment, you must have this:
@Override
protected boolean hasSavedState() {
Bundle state = getSavedState();
if (state == null) {
return false;
}
//restore your data here
return true;
}
3) For example, you can call hasSavedState in onActivityCreated:
@Override
public void onActivityCreated(Bundle state) {
super.onActivityCreated(state);
if (hasSavedState()) {
return;
}
//your code here
}
You can select multiple classes at once with jQuery like this:
$('.tag, .tag2').click(function() {
var $this = $(this);
if ($this.hasClass('tag')) {
// do stuff
} else {
// do other stuff
}
});
Giving a 2nd parameter to the $() function, scopes the selector so $('.tag', '.tag2')
looks for tag
within elements with the class tag2
.
I believe this is much simpler;
dynamic obj = JObject.Parse(jsonString);
string results = obj.results;
foreach(string result in result.Split('))
{
//Todo
}
i've tried all those methods but it didn't work then a workmate told me that Putty Key Generator used to generate keys with 1024 bits but now Putty generate 2048 bits keys by default , so you just need to change the "Number of bits in a generated key" and it should work.
I realize there are already good answers here.
I nevertheless would like to contribute my own, because I feel for an elementary, simple question like this, there should be a short solution that is understandable at a glance.
It should also work in a way that I can add the percentages as a new column, leaving the rest of the dataframe untouched. Last but not least, it should generalize in an obvious way to the case in which there is more than one grouping level (e.g., state and country instead of only state).
The following snippet fulfills these criteria:
df['sales_ratio'] = df.groupby(['state'])['sales'].transform(lambda x: x/x.sum())
Note that if you're still using Python 2, you'll have to replace the x in the denominator of the lambda term by float(x).
The full example explaining the syntax referenced by Robin... brought it home for me:
Something like the following works fine:
function foo<T>(x: T): T { return x; }
However using an arrow generic function will not:
const foo = <T>(x: T) => x; // ERROR : unclosed `T` tag
Workaround: Use extends on the generic parameter to hint the compiler that it's a generic, e.g.:
const foo = <T extends unknown>(x: T) => x;
alternatively you can put onchange attribute on the dropdownlist itself, that onchange will call certain jquery function like this.
<input type="dropdownlist" onchange="jqueryFunc()">
<script type="text/javascript">
$(function(){
jqueryFunc(){
//something goes here
}
});
</script>
hope this one helps you, and please note that this code is just a rough draft, not tested on any ide. thanks
I am a beginner so here is a beginners answer. The if in the for loop gives i which can then be used however needed such as Numbers[i] in another vector. Most is fluff for examples sake, the for/if really says it all.
int main(){
vector<string>names{"Sara", "Harold", "Frank", "Taylor", "Sasha", "Seymore"};
string req_name;
cout<<"Enter search name: "<<'\n';
cin>>req_name;
for(int i=0; i<=names.size()-1; ++i) {
if(names[i]==req_name){
cout<<"The index number for "<<req_name<<" is "<<i<<'\n';
return 0;
}
else if(names[i]!=req_name && i==names.size()-1) {
cout<<"That name is not an element in this vector"<<'\n';
} else {
continue;
}
}
You also can do it with functional programming:
from functools import reduce
reduce(lambda df1, df2: df1.merge(df2, "outer"), mydfs)
Building on @Panagiotis Kanavos' answer, here's a working method as example which will also return the response as an object instead of a string:
using System.Text;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json; // Nuget Package
public static async Task<object> PostCallAPI(string url, object jsonObject)
{
try
{
using (HttpClient client = new HttpClient())
{
var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
var response = await client.PostAsync(url, content);
if (response != null)
{
var jsonString = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<object>(jsonString);
}
}
}
catch (Exception ex)
{
myCustomLogger.LogException(ex);
}
return null;
}
Keep in mind that this is only an example and that you'd probably would like to use HttpClient
as a shared instance instead of using it in a using-clause.
Below Code only works if It contain Unique Value Data
public string getKey(string Value)
{
if (dictionary.ContainsValue(Value))
{
var ListValueData=new List<string>();
var ListKeyData = new List<string>();
var Values = dictionary.Values;
var Keys = dictionary.Keys;
foreach (var item in Values)
{
ListValueData.Add(item);
}
var ValueIndex = ListValueData.IndexOf(Value);
foreach (var item in Keys)
{
ListKeyData.Add(item);
}
return ListKeyData[ValueIndex];
}
return string.Empty;
}
What did you expect the following to do?
v1 = [0,0],[M[i,0],M[i,1]]
v1 = [M[i,0]],[M[i,1]]
This is making two different tuples, and you overwrite what you did the first time... Anyway, matplotlib
does not understand what a "vector" is in the sense you are using. You have to be explicit, and plot "arrows":
In [5]: ax = plt.axes()
In [6]: ax.arrow(0, 0, *v1, head_width=0.05, head_length=0.1)
Out[6]: <matplotlib.patches.FancyArrow at 0x114fc8358>
In [7]: ax.arrow(0, 0, *v2, head_width=0.05, head_length=0.1)
Out[7]: <matplotlib.patches.FancyArrow at 0x115bb1470>
In [8]: plt.ylim(-5,5)
Out[8]: (-5, 5)
In [9]: plt.xlim(-5,5)
Out[9]: (-5, 5)
In [10]: plt.show()
Result:
I've made my own head hurt over nothing! The Answer was very simple- I just went back to the basics...
some_Entities e2 = new some_Entities(); //your entity.
add this line below after you update/delete - you're re-loading your entity-no fancy system methods.
e2 = new some_Entities(); //reset.
showInventory(player);
is passing a type as parameter. That's illegal, you need to pass an object.
For example, something like:
player p;
showInventory(p);
I'm guessing you have something like this:
int main()
{
player player;
toDo();
}
which is awful. First, don't name the object the same as your type. Second, in order for the object to be visible inside the function, you'll need to pass it as parameter:
int main()
{
player p;
toDo(p);
}
and
std::string toDo(player& p)
{
//....
showInventory(p);
//....
}
You can do the access control at the Web server level using HTTP Basic authentication and htpasswd. There are a number of problems with this:
Unless you're building a site for internal use with few users, I wouldn't really recommend it.
I'm a bit surprised that no one has mentioned this. In general, rather than trimming data that you don't want, avoid writing it in the first place. If you don't want the newline in the buffer, don't use fgets. Instead, use getc
or fgetc
or scanf
. Perhaps something like:
#include <stdio.h>
#include <stdlib.h>
int
main(void)
{
char Name[256];
char fmt[32];
int rc;
sprintf(fmt, "%%%zd[^\n]", sizeof Name - 1);
if( (rc = scanf(fmt, Name)) == 1 ) {
printf("Name = %s\n", Name);
}
return rc == 1 ? EXIT_SUCCESS : EXIT_FAILURE;
}
Following up on Mat's answer (use Cygwin), here are some detailed instructions for : installing gcc on Windows The packages you want are gcc, gdb and make. Cygwin installer lets you install additional packages if you need them.
Try renaming the default file. In my case, a recent move to IIS7.5 gave the 405 error. I changed index.aspx to default.aspx and it worked immediately for me.
It depends on how your $('site-header') is constructed.
You can try to use $timeout with 0 delay. Something like:
return function(scope, element, attrs) {
$timeout(function(){
$('.main').height( $('.site-header').height() - $('.site-footer').height() );
});
}
Explanations how it works: one, two.
Don't forget to inject $timeout
in your directive:
.directive('sticky', function($timeout)
To use mock_open for a simple file read()
(the original mock_open snippet already given on this page is geared more for write):
my_text = "some text to return when read() is called on the file object"
mocked_open_function = mock.mock_open(read_data=my_text)
with mock.patch("__builtin__.open", mocked_open_function):
with open("any_string") as f:
print f.read()
Note as per docs for mock_open, this is specifically for read()
, so won't work with common patterns like for line in f
, for example.
Uses python 2.6.6 / mock 1.0.1
You can try : go to edit>preferencec>type.. select type > choose text engine options select east asian. Restart photoshop. Create new peroject. Try text tool again.
(if you want to use your project created with other text engine type) copy /paste all layers to new project.
Can I use pip to install iPython?
Sure, both (first approach on page)
pip install ipython
and (third approach, second is conda
)
You can manually download IPython from GitHub or PyPI. To install one of these versions, unpack it and run the following from the top-level source directory using the Terminal:
pip install .
are officially recommended ways to install.
Why should I use conda as another python package manager when I already have pip?
As said here:
If you need a specific package, maybe only for one project, or if you need to share the project with someone else, conda seems more appropriate.
Conda surpasses pip in (YMMV)
What is the difference between pip and conda?
That is extensively answered by everyone else.
I had this issue after moving my home folder to a new drive on linux. It was fixed by removing .nvm folder and reinstalling nvm
Simply add container to sticky navbar ;
I found another way to export table in sql file.
Suppose my table is abs_item_variations
abs_item_variations ->structure -> propose table structure -> export -> Go
My trick is to create a transparent .png with the color and use background:url()
.
$letters = array("a", "b", "c", "d", "e", "f", "g"); // this array can n no. of values
$result = substr(implode(", ", $letters), 0);
echo $result
output-> a,b,c,d,e,f,g
You had thead
in your selector, but there is no thead
in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr
class to the th
, not vice-versa (although your comment seems to contradict what you wrote up above).
$('tr th').each(function(index){ if($('tr td').eq(index).attr('class') != ''){ // get the class of the td var tdClass = $('tr td').eq(index).attr('class'); // add it to this th $(this).addClass(tdClass ); } });
private void CheckUPdate() {
VersionChecker versionChecker = new VersionChecker();
try
{ String appVersionName = BuildConfig.VERSION_NAME;
String mLatestVersionName = versionChecker.execute().get();
if(!appVersionName.equals(mLatestVersionName)){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Activity.this);
alertDialog.setTitle("Please update your app");
alertDialog.setMessage("This app version is no longer supported. Please update your app from the Play Store.");
alertDialog.setPositiveButton("UPDATE NOW", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
final String appPackageName = getPackageName();
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
}
}
});
alertDialog.show();
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
@SuppressLint("StaticFieldLeak")
public class VersionChecker extends AsyncTask<String, String, String> {
private String newVersion;
@Override
protected String doInBackground(String... params) {
try {
newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id="+getPackageName())
.timeout(30000)
.userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
.referrer("http://www.google.com")
.get()
.select(".hAyfc .htlgb")
.get(7)
.ownText();
} catch (IOException e) {
e.printStackTrace();
}
return newVersion;
}
}
<button onclick="history.go(-1);">Back </button>
One way you could do it is have a file with the username and pass directly under it. Then uses the Scanner class and when you create it, make the file the parameter for the Scanner. Then use the methods hasNext(); and nextLine to verify the username and password;
String user;
String pass;
Scanner scan = new Scanner(new File("File.txt"));
while(scan.hasNext){ //While the file still has more lines remaining
if(scan.nextLine() == user){
if(scan.nextLine == pass){
lblDisplay.setText("Credentials Accepted.");
}
else{
lblDisplay.setText("Please try again.");
}
}
}
Here is an example of how you can do it in Spring 4.0+
application.properties
content:some.key=yes,no,cancel
@Autowire
private Environment env;
...
String[] springRocks = env.getProperty("some.key", String[].class);
Andrey's above post is still valid for the latest version of Intellij as of 3rd Quarter of 2017. So use it. 'Cause, build project, and external command line gradle build, does NOT add it to the external dependencies in Intellij...crazy as that sounds it is true. Only difference now is that the UI looks different to the above, but still the same icon for updating is used. I am only putting an answer here, cause I cannot paste a snapshot of the new UI...I dont want any up votes per se. Andrey still gave the correct answer above:
use NumpyEncoder it will process json dump successfully.without throwing - NumPy array is not JSON serializable
import numpy as np
import json
from numpyencoder import NumpyEncoder
arr = array([ 0, 239, 479, 717, 952, 1192, 1432, 1667], dtype=int64)
json.dumps(arr,cls=NumpyEncoder)
Use count()
:
sc=scorm.objects.filter(Header__id=qp.id)
if sc.count() > 0:
...
The advantage over e.g. len()
is, that the QuerySet is not yet evaluated:
count()
performs aSELECT COUNT(*)
behind the scenes, so you should always usecount()
rather than loading all of the record into Python objects and callinglen()
on the result.
Having this in mind, When QuerySets are evaluated can be worth reading.
If you use get()
, e.g. scorm.objects.get(pk=someid)
, and the object does not exists, an ObjectDoesNotExist
exception is raised:
from django.core.exceptions import ObjectDoesNotExist
try:
sc = scorm.objects.get(pk=someid)
except ObjectDoesNotExist:
print ...
Update:
it's also possible to use exists()
:
if scorm.objects.filter(Header__id=qp.id).exists():
....
Returns
True
if the QuerySet contains any results, andFalse
if not. This tries to perform the query in the simplest and fastest way possible, but it does execute nearly the same query as a normal QuerySet query.
\sf
function_name in psql yields editable source code of a single function.
From https://www.postgresql.org/docs/9.6/static/app-psql.html:
\sf[+] function_description This command fetches and shows the definition of the named function, in the form of a CREATE OR REPLACE FUNCTION command.
If + is appended to the command name, then the output lines are numbered, with the first line of the function body being line 1.
You can read multiple variables from file like this:
for /f "delims== tokens=1,2" %%G in (param.txt) do set %%G=%%H
where param.txt:
PARAM1=value1
PARAM2=value2
...
This code works for me check below code:
<?php
define('UPLOAD_DIR', 'images/');
$image_parts = explode(";base64,", $_POST['image']);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$file = UPLOAD_DIR . uniqid() . '.png';
file_put_contents($file, $image_base64);
?>
I have a more compact approach:
release: DESTDIR = build/release
debug: DESTDIR = build/debug
OBJECTS_DIR = $$DESTDIR/.obj
MOC_DIR = $$DESTDIR/.moc
RCC_DIR = $$DESTDIR/.qrc
UI_DIR = $$DESTDIR/.ui
Note that getcwd(3)
is also available in Microsoft's libc: getcwd(3), and works the same way you'd expect.
Must link with -loldnames
(oldnames.lib, which is done automatically in most cases), or use _getcwd()
. The unprefixed version is unavailable under Windows RT.
This should do it. You were missing a )
and you only need """
not 4 of them. Also you don't need a elif at the end.
ans=True
while ans:
print("""
1.Add a Student
2.Delete a Student
3.Look Up Student Record
4.Exit/Quit
""")
ans=raw_input("What would you like to do? ")
if ans=="1":
print("\nStudent Added")
elif ans=="2":
print("\n Student Deleted")
elif ans=="3":
print("\n Student Record Found")
elif ans=="4":
print("\n Goodbye")
ans = None
else:
print("\n Not Valid Choice Try again")
replace()
returns an new string, and the original string is not modified. You need to do
str = str.replace(/-/g, ' ');
I hope this will help you
Create table :
create table users (id int,first_name varchar(10),last_name varchar(10));
Insert values into the table :
insert into users (id,first_name,last_name) values(1,'Abhishek','Anand');
If you prefer to edit the file php.ini
in your favorite editor than the Editor created by MAMP, you would need to stop the Servers first.
Then head to Library->Application Support->appsolute->MAMP PRO->templates->php{version_number}.ini.temp
and effect any change you would want to have especially the below
max_execution_time = 3000
max_input_time = 60
memory_limit = 128M
post_max_size = 256M
upload_max_filesize 256M
And also make changes in your PHPMyAdmin if it is what you are using in Cpanel.
$cfg['ExecTimeLimit'] = 300;
Make sure you make a copy of the original file. You can navigate under conf
!here
curl's --data
will by default send Content-Type: application/x-www-form-urlencoded
in the request header. However, when using Postman's raw
body mode, Postman sends Content-Type: text/plain
in the request header.
So to achieve the same thing as Postman, specify -H "Content-Type: text/plain"
for curl:
curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/
Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network
tab :
Satisfies all your requirements if you use the trick told below
/^(\+\d{1,3}[- ]?)?\d{10}$/
^
start of line+
followed by \d+
followed by a
or -
which are optional.0
s do not follow.\d+
10 times.DEMO Added m
ultiline flag in demo to check for all cases
P.S. You really need to specify which language you use so as to use an if
condition something like below:
// true if above regex is satisfied and (&&) it does not (`!`) match `0`s `5` or more times
if(number.match(/^(\+\d{1,3}[- ]?)?\d{10}$/) && ! (number.match(/0{5,}/)) )
A backreference to the whole match value is \g<0>
, see re.sub
documentation:
The backreference
\g<0>
substitutes in the entire substring matched by the RE.
See the Python demo:
import re
method = 'images/:id/huge'
print(re.sub(r':[a-z]+', r'<span>\g<0></span>', method))
# => images/<span>:id</span>/huge
I searched for some good themes across internet and found nothing. So I ported selected controls of GTK Hybrid theme. It's MIT licensed and you can find it here:
https://github.com/stil/candyshop
It's not enterprise grade style and probably has some flaws, but I use it in my personal projects.
fill_parent
will make the width or height of the element to be as
large as the parent element, in other words, the container.
wrap_content
will make the width or height be as large as needed to
contain the elements within it.
Using break-inside should work:
@media print {
div {
break-inside: avoid;
}
}
It works on all major browsers:
Using page-break-inside: avoid;
instead should work too, but has been exactly deprecated by break-inside: avoid
.
In short, it is a scripting notation for passing data about. In some ways an alternative to XML, natively supporting basic data types, arrays and associative arrays (name-value pairs, called Objects because that is what they represent).
The syntax is that used in JavaScript and JSON itself stands for "JavaScript Object Notation". However it has become portable and is used in other languages too.
A useful link for detail is here: