Don't know if it's the best way but I'd do this:
=A1 & TEXT(A2,"mm/dd/yyyy")
That should format your date into your desired string.
Edit: That funny number you saw is the number of days between December 31st 1899 and your date. That's how Excel stores dates.
To properly format numbers in columns, it's best to use printf. Depending on how big are the max or min numbers, you might want to adjust the pattern "%4d"
. For instance to allow any integer between Integer.MIN_VALUE
and Integer.MAX_VALUE
, use "%12d"
.
public void printMatrix(int[][] matrix) {
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++) {
System.out.printf("%4d", matrix[row][col]);
}
System.out.println();
}
}
Example output:
36 913 888 908
732 626 61 237
5 8 50 265
192 232 129 307
There are a bunch of color descriptors used to recognise objects, the paper below compares a lot of them. They are specially powerful when combined with SIFT or SURF. SURF or SIFT alone are not very useful in a coca cola can image because they don't recognise a lot of interest points, you need the color information to help. I use BIC (Border/Interior Pixel Classi?cation) with SURF in a project and it worked great to recognise objects.
Color descriptors for Web image retrieval: a comparative study
I had this problem and was able to resolve it with the declaration below.
$.fn.bootstrapBtn = $.fn.button.noConflict();
If you just want to use some of the predefined Android colors, you can use Color.COLOR
(where COLOR
is BLACK
, WHITE
, RED
, etc.):
myView.setBackgroundColor(Color.GREEN);
Otherwise you can do as others have suggested with
myView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.myCustomGreen));
I don't recommend using a hex color directly. You should keep all of your custom colors in colors.xml.
According to the error message, you declared myLoc
as a pointer to an NSInteger (NSInteger *myLoc
) rather than an actual NSInteger (NSInteger myLoc
). It needs to be the latter.
I want to indent a specific section of code in Visual Studio Code:
If you want to format a section (instead of indent it):
return $picName = time().'.'.$request->file->extension();
The time()
function will make the image unique then the .$request->file->extension()
gets the image extension for you.
You can use this it works well with Laravel 6 and above.
<?php
function plusTimetoOldtime($Old_Time,$getFormat,$Plus_Time) {
return date($getFormat,strtotime(date($getFormat,$Old_Time).$Plus_Time));
}
$Old_Time = strtotime("now");
$Plus_Time = '+1 day';
$getFormat = 'Y-m-d H:i:s';
echo plusTimetoOldtime($Old_Time,$getFormat,$Plus_Time);
?>
You can rollback the statements you've executed within a transaction. Instead of commiting the transaction, rollback the transaction.
If you have updated something and want to rollback those updates, and you haven't done this inside a (not-yet-commited) transaction, then I think it's though luck ...
(Manually repair, or, restore backups)
This is because PHP uses the period character .
for string concatenation, not the plus character +
. Therefore to append to a string you want to use the .=
operator:
for ($i=1;$i<=100;$i++)
{
$selectBox .= '<option value="' . $i . '">' . $i . '</option>';
}
$selectBox .= '</select>';
CREATE GLOBAL TEMPORARY TABLE Table_name
(startdate DATE,
enddate DATE,
class CHAR(20))
ON COMMIT DELETE ROWS;
Unlike other languages you may be used to, everything in C++ has to be declared before it can be used. The compiler will read your source file from top to bottom, so when it gets to the call to swapCase
, it doesn't know what it is so you get an error. You can declare your function ahead of main with a line like this:
void swapCase(char *name);
or you can simply move the entirety of that function ahead of main in the file. Don't worry about having the seemingly most important function (main) at the bottom of the file. It is very common in C or C++ to do that.
This may happen when the same classname is specified in multiple .aspx.cs
files, i.e.
when two pages are created with different file name but by mistake have the same classname.
// file a.aspx
public partial class Test1: System.Web.UI.Page
// file b.aspx
public partial class Test1: System.Web.UI.Page
While building the webapplication this gives a warning, but the application runs, however, after publishing the application doesn't work anymore and throws the exception as mentioned in the OP's question.
Making sure that two classnames do no overlap solves the issue.
The Like button coded to show "Recommend" is 84px wide and the "Like" button is 44px, will save some time for you CSS guys like me who need to hide how unpopular my page currently is! I put this code on top of my homepage, so initially I don't want it to advertise how few Likes I have.
Simple math..
def average(n):
result = 0
for i in n:
result += i
ave_num = result / len(n)
return ave_num
input -> [1,2,3,4,5]
output -> 3.0
Well, you can do css tables instead of html tables. This keeps your html semantically correct, but allows you to use tables for layout purposes.
This seems to make more sense than using float hacks.
<html>
<head>
<style>
#content-wrapper{
display:table;
}
#content{
display:table-row;
}
#content>div{
display:table-cell
}
/*adding some extras for demo purposes*/
#content-wrapper{
width:100%;
height:100%;
top:0px;
left:0px;
position:absolute;
}
#nav{
width:100px;
background:yellow;
}
#body{
background:blue;
}
</style>
</head>
<body>
<div id="content-wrapper">
<div id="content">
<div id="nav">
Left hand content
</div>
<div id="body">
Right hand content
</div>
</div>
</div>
</body>
</html>
The module was install but symbolic link was not in /etc/php5/cli/conf.d
You could try to create your own color palette using the RColorBrewer
package
my_palette <- colorRampPalette(c("green", "black", "red"))(n = 1000)
and see how this looks like. But I assume in your case only scaling would help if you really want to keep the black in "the middle". You can simply use my_palette
instead of the redgreen()
I recommend that you check out the RColorBrewer package, they have pretty nice in-built palettes, and see interactive website for colorbrewer.
Export:
mysqldump --user=root databasename > whole.database.sql
mysqldump --user=root databasename onlySingleTableName > single.table.sql
Import:
Whole database:
mysql --user=root wholedatabase < whole.database.sql
Single table:
mysql --user=root databasename < single.table.sql
MERGE INTO target
USING
(
--Source data
SELECT id, some_value, 0 deleteMe FROM source
--And anything that has been deleted from the source
UNION ALL
SELECT id, null some_value, 1 deleteMe
FROM
(
SELECT id FROM target
MINUS
SELECT id FROM source
)
) source
ON (target.ID = source.ID)
WHEN MATCHED THEN
--Requires a lot of ugly CASE statements, to prevent updating deleted data
UPDATE SET target.some_value =
CASE WHEN deleteMe=1 THEN target.some_value ELSE source.some_value end
,isDeleted = deleteMe
WHEN NOT MATCHED THEN
INSERT (id, some_value, isDeleted) VALUES (source.id, source.some_value, 0)
--Test data
create table target as
select 1 ID, 'old value 1' some_value, 0 isDeleted from dual union all
select 2 ID, 'old value 2' some_value, 0 isDeleted from dual;
create table source as
select 1 ID, 'new value 1' some_value, 0 isDeleted from dual union all
select 3 ID, 'new value 3' some_value, 0 isDeleted from dual;
--Results:
select * from target;
ID SOME_VALUE ISDELETED
1 new value 1 0
2 old value 2 1
3 new value 3 0
The runtime jre was set to jre 6 instead of jre 7 in the build configuration window.
I come here with the same doubt but for Xamarin for Android, I have used the Sigrist answer to do this method after save my file:
private void UpdateGallery()
{
Intent mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
Java.IO.File file = new Java.IO.File(_path);
Android.Net.Uri contentUri = Android.Net.Uri.FromFile(file);
mediaScanIntent.SetData(contentUri);
Application.Context.SendBroadcast(mediaScanIntent);
}
and it solved my problem, Thx Sigrist. I put it here becouse i did not found an answare about this for Xamarin and i hope it can help other people.
As of today, epxress.compress()
seems to be doing a brilliant job of this.
In any express app just call this.use(express.compress());
.
I'm running locomotive on top of express personally and this is working beautifully. I can't speak to any other libraries or frameworks built on top of express but as long as they honor full stack transparency you should be fine.
Recently i had the same problem (Compiling OpenCV with CMake and Qt/MinGW on WIN764)
And I think I solve this including on my environment variable PATH (through Control Panel\All Control Panel Items\System\Advanced Sytem Settings
) with the %MINGW_DIR%\bin and %CMAKE_DIR%/bin
Furthermore, I installed cmake2.8 on an easy directory (without blanks on it)
You have an incompatibility between the version of ASM required by Hibernate (asm-1.5.3.jar) and the one required by Spring. But, actually, I wonder why you have asm-2.2.3.jar on your classpath (ASM is bundled in spring.jar and spring-core.jar to avoid such problems AFAIK). See HHH-2222.
Rename-Computer was removed from CTP3 because there are a lot of things done when renaming a computer and MS either didn't want to recreate that process or couldn't include all of the necessary bits. I think Jefferey Snover said to just use netdom.exe instead, as that is the best practice for renaming a computer on the command-line. Not the answer you were looking for, but should point you in the right direction
Why Map.Entry
? I guess something like a key-value pair is fit for the case.
Use java.util.AbstractMap.SimpleImmutableEntry
or java.util.AbstractMap.SimpleEntry
Sorry but I don't understand why too many people even think a string was something that could be evaluated. You must change your mindset, really. Forget all connections between strings on one side and expressions, calls, evaluation on the other side.
The (possibly) only connection is via parse(text = ....)
and all good R programmers should know that this is rarely an efficient or safe means to construct expressions (or calls). Rather learn more about substitute()
, quote()
, and possibly the power of using do.call(substitute, ......)
.
fortunes::fortune("answer is parse")
# If the answer is parse() you should usually rethink the question.
# -- Thomas Lumley
# R-help (February 2005)
Dec.2017: Ok, here is an example (in comments, there's no nice formatting):
q5 <- quote(5+5)
str(q5)
# language 5 + 5
e5 <- expression(5+5)
str(e5)
# expression(5 + 5)
and if you get more experienced you'll learn that q5
is a "call"
whereas e5
is an "expression"
, and even that e5[[1]]
is identical to q5
:
identical(q5, e5[[1]])
# [1] TRUE
We can calculate intersection minus union of lists:
temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two', 'Five']
set(temp1+temp2)-(set(temp1)&set(temp2))
Out: set(['Four', 'Five', 'Three'])
To get a full list of colors to use in plots:
import matplotlib.colors as colors
colors_list = list(colors._colors_full_map.values())
So, you can use in that way quickly:
scatter(X,Y, color=colors_list[0])
scatter(X,Y, color=colors_list[1])
scatter(X,Y, color=colors_list[2])
...
scatter(X,Y, color=colors_list[-1])
There's actually a great Google API for this. It takes in a location and returns the timezone for that location. Should be simple enough to create a bash or python script to get the results for each address in a CSV file or database then save the timezone information.
https://developers.google.com/maps/documentation/timezone/start
Request Endpoint:
https://maps.googleapis.com/maps/api/timezone/json?location=38.908133,-77.047119×tamp=1458000000&key=YOUR_API_KEY
Response:
{
"dstOffset" : 3600,
"rawOffset" : -18000,
"status" : "OK",
"timeZoneId" : "America/New_York",
"timeZoneName" : "Eastern Daylight Time"
}
I have this git log
alias in ~/.gitconfig
to view the graph history:
[alias]
l = log --all --graph --pretty=format:'%C(auto)%h%C(auto)%d %s %C(dim white)(%aN, %ar)'
With this in place, git l
will output something like:
In Git 2.12+ you can even customize the line colors of the graph using the log.graphColors
configuration option.
As for the logs' format, it's similar to --oneline
, with the addition of the author name (respecting .mailmap
) and the relative author date. Note that the %C(auto)
syntax, which tells Git to use the default colors for commit hash, etc. is supported in Git >= 1.8.3.
For Windows, first install the git base from here: https://git-scm.com/downloads
Next, set the environment variable:
C:\Program Files\Git\git-bash.exe
To test it, open the command window: press Windows+R, type cmd and then type ssh.
Array(10).fill('a').join('')
Although the most voted answer is a bit more compact, with this approach you don't have to add an extra array item.
Have you tried:
tr.classname { margin-bottom:5em; }
Alternatively, each td can be adjusted as well:
td.classname { margin-bottom:5em; }
or
td.classname { padding-bottom:5em; }
Type assertion is un-avoidable. Following up on
enum Vehicle {
Car = 'car',
Bike = 'bike',
Truck = 'truck'
}
I found one alternative that wasn't mentioned so thought I'd share my fix for it:
const someString: Vehicle | string = 'car';
const inEnum = (Object.values(Vehicle) as string[]).includes(someString);
I find this more truthful because we usually come in typesafe(with a string) and want to compare it to the enum; it'd be a bit reckless to typecast it to any
(reason: never do this) or Vehicle
(reason: likely untruthful). Instead, typecasting the Object.values()
output to an array of strings is in-fact very much real.
It's also possible that you have included /bin in your JAVA_HOME setting, and Ant is adding /bin to it - thereby not finding any exe's. It's happened to me :}
Use Application.ActiveWorkbook.Path
for just the path itself (without the workbook name) or Application.ActiveWorkbook.FullName
for the path with the workbook name.
The two syntaxes are not equivalent and it can lead to unexpected errors. Here is a simple example showing the differences. If you have a model:
from django.db import models
class Test(models.Model):
added = models.DateTimeField(auto_now_add=True)
And you create a first object:
foo = Test.objects.create(pk=1)
Then you try to create an object with the same primary key:
foo_duplicate = Test.objects.create(pk=1)
# returns the error:
# django.db.utils.IntegrityError: (1062, "Duplicate entry '1' for key 'PRIMARY'")
foo_duplicate = Test(pk=1).save()
# returns the error:
# django.db.utils.IntegrityError: (1048, "Column 'added' cannot be null")
Updated 2017-12-16
I was not sure about the tests in OP. I decided to experiment a little and ended up busting some of the myths.
Synchronous
<script src...>
will block downloading of the resources below it until it is downloaded and executed
This is no longer true. Have a look at the waterfall generated by Chrome 63:
<head>
<script src="//alias-0.redacted.com/payload.php?type=js&delay=333&rand=1"></script>
<script src="//alias-1.redacted.com/payload.php?type=js&delay=333&rand=2"></script>
<script src="//alias-2.redacted.com/payload.php?type=js&delay=333&rand=3"></script>
</head>
<link rel=stylesheet>
will not block download and execution of scripts below it
This is incorrect. The stylesheet will not block download but it will block execution of the script (little explanation here). Have a look at performance chart generated by Chrome 63:
<link href="//alias-0.redacted.com/payload.php?type=css&delay=666" rel="stylesheet">
<script src="//alias-1.redacted.com/payload.php?type=js&delay=333&block=1000"></script>
Keeping the above in mind, the results in OP can be explained as follows:
CSS First:
CSS Download 500ms:<------------------------------------------------>
JS Download 400ms:<-------------------------------------->
JS Execution 1000ms: <-------------------------------------------------------------------------------------------------->
DOM Ready @1500ms: ?
JS First:
JS Download 400ms:<-------------------------------------->
CSS Download 500ms:<------------------------------------------------>
JS Execution 1000ms: <-------------------------------------------------------------------------------------------------->
DOM Ready @1400ms: ?
Would something like this help?
var fileWasWrittenSuccessfully = false;
while (fileWasWrittenSuccessfully == false)
{
try
{
lock (new Object())
{
using (StreamWriter streamWriter = new StreamWriter("filepath.txt"), true))
{
streamWriter.WriteLine("text");
}
}
fileWasWrittenSuccessfully = true;
}
catch (Exception)
{
}
}
SELECT *
FROM customer
WHERE joiningdate >= NOW();
Thanks, this worked for my purposes. BTW there is a missing single-quote in the example, above.
REGEXP_REPLACE (COLUMN,'[^' || CHR (32) || '-' || CHR (127) || ']', ' '))
I used it in a word-wrap function. Occasionally there was an embedded NewLine/ NL / CHR(10) / 0A in the incoming text that was messing things up.
Register keyword tells compiler to store the particular variable in CPU registers so that it could be accessible fast. From a programmer's point of view register keyword is used for the variables which are heavily used in a program, so that compiler can speedup the code. Although it depends on the compiler whether to keep the variable in CPU registers or main memory.
I know that this is a very old post but just wanted to say that using flexbox on a parent element would disable margin collapsing for its child elements.
Copy the hosts
file and add 127.0.0.1
and name which you want to show or run at the browser link. For example:
127.0.0.1 abc
Then run abc/
as a local host in the browser.
try
java -cp "your_jar.jar:lib/referenced_jar.jar" com.your.main.Main
If you are on windows, you should use ;
instead of :
The trick is that you need to create an environment/workspace for Python. This solution should work for Python 2.7 but at the time of writing keras can run on python 3.5, especially if you have the latest anaconda installed (this took me awhile to figure out so I'll outline the steps I took to install KERAS in python 3.5):
Create environment/workspace for Python 3.5
C:\conda create --name neuralnets python=3.5
C:\activate neuralnets
Install everything (notice the neuralnets workspace in parenthesis on each line). Accept any dependencies each of those steps wants to install:
(neuralnets) C:\conda install theano
(neuralnets) C:\conda install mingw libpython
(neuralnets) C:\pip install tensorflow
(neuralnets) C:\pip install keras
Test it out:
(neuralnets) C:\python -c "from keras import backend; print(backend._BACKEND)"
Just remember, if you want to work in the workspace you always have to do:
C:\activate neuralnets
so you can launch Jupyter for example (assuming you also have Jupyter installed in this environment/workspace) as:
C:\activate neuralnets
(neuralnets) jupyter notebook
You can read more about managing and creating conda environments/workspaces at the follwing URL: https://conda.io/docs/using/envs.html
Here is my answer for Swift 2:
func daysBetweenDates(startDate: NSDate, endDate: NSDate) -> Int
{
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day], fromDate: startDate, toDate: endDate, options: [])
return components.day
}
I have this function in my toolbelt since years ago (all the function and variable names are messy and mixing Spanish and English, sorry for that).
It lets the user use ,
and .
to separate the decimals and will try to do the best if both symbols are used.
Public Shared Function TryCDec(ByVal texto As String, Optional ByVal DefaultValue As Decimal = 0) As Decimal
If String.IsNullOrEmpty(texto) Then
Return DefaultValue
End If
Dim CurAsTexto As String = texto.Trim.Replace("$", "").Replace(" ", "")
''// You can probably use a more modern way to find out the
''// System current locale, this function was done long time ago
Dim SepDecimal As String, SepMiles As String
If CDbl("3,24") = 324 Then
SepDecimal = "."
SepMiles = ","
Else
SepDecimal = ","
SepMiles = "."
End If
If InStr(CurAsTexto, SepDecimal) > 0 Then
If InStr(CurAsTexto, SepMiles) > 0 Then
''//both symbols was used find out what was correct
If InStr(CurAsTexto, SepDecimal) > InStr(CurAsTexto, SepMiles) Then
''// The usage was correct, but get rid of thousand separator
CurAsTexto = Replace(CurAsTexto, SepMiles, "")
Else
''// The usage was incorrect, but get rid of decimal separator and then replace it
CurAsTexto = Replace(CurAsTexto, SepDecimal, "")
CurAsTexto = Replace(CurAsTexto, SepMiles, SepDecimal)
End If
End If
Else
CurAsTexto = Replace(CurAsTexto, SepMiles, SepDecimal)
End If
''// At last we try to tryParse, just in case
Dim retval As Decimal = DefaultValue
Decimal.TryParse(CurAsTexto, retval)
Return retval
End Function
Latin-1 (aka ISO 8859-1) is a single octet character encoding scheme, and you can't fit \u201c
(“
) into a byte.
Did you mean to use UTF-8 encoding?
Looking at http.Request you can find the following member variables:
// HTTP defines that header names are case-insensitive.
// The request parser implements this by canonicalizing the
// name, making the first character and any characters
// following a hyphen uppercase and the rest lowercase.
//
// For client requests certain headers are automatically
// added and may override values in Header.
//
// See the documentation for the Request.Write method.
Header Header
// RemoteAddr allows HTTP servers and other software to record
// the network address that sent the request, usually for
// logging. This field is not filled in by ReadRequest and
// has no defined format. The HTTP server in this package
// sets RemoteAddr to an "IP:port" address before invoking a
// handler.
// This field is ignored by the HTTP client.
RemoteAddr string
You can use RemoteAddr
to get the remote client's IP address and port (the format is "IP:port"), which is the address of the original requestor or the last proxy (for example a load balancer which lives in front of your server).
This is all you have for sure.
Then you can investigate the headers, which are case-insensitive (per documentation above), meaning all of your examples will work and yield the same result:
req.Header.Get("X-Forwarded-For") // capitalisation
req.Header.Get("x-forwarded-for") // doesn't
req.Header.Get("X-FORWARDED-FOR") // matter
This is because internally http.Header.Get
will normalise the key for you. (If you want to access header map directly, and not through Get
, you would need to use http.CanonicalHeaderKey first.)
Finally, "X-Forwarded-For"
is probably the field you want to take a look at in order to grab more information about client's IP. This greatly depends on the HTTP software used on the remote side though, as client can put anything in there if it wishes to. Also, note the expected format of this field is the comma+space separated list of IP addresses. You will need to parse it a little bit to get a single IP of your choice (probably the first one in the list), for example:
// Assuming format is as expected
ips := strings.Split("10.0.0.1, 10.0.0.2, 10.0.0.3", ", ")
for _, ip := range ips {
fmt.Println(ip)
}
will produce:
10.0.0.1
10.0.0.2
10.0.0.3
They are format specifiers. They are used when you want to include the value of your Python expressions into strings, with a specific format enforced.
See Dive into Python for a relatively detailed introduction.
Pure js approach:
var elem = document.getElementsByClassName('parent');
alert(elem[0].hasAttribute('id'));
According to the doc, the default implementation of hashCode will return some integer that differ for every object
As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation
technique is not required by the JavaTM programming language.)
However some time you want the hash code to be the same for different object that have the same meaning. For example
Student s1 = new Student("John", 18);
Student s2 = new Student("John", 18);
s1.hashCode() != s2.hashCode(); // With the default implementation of hashCode
This kind of problem will be occur if you use a hash data structure in the collection framework such as HashTable, HashSet. Especially with collection such as HashSet you will end up having duplicate element and violate the Set contract.
You didn't provide us which operating system are you on? If it is a Linux, make sure you have scipy installed as well, after that just do
pip install -U scikit-learn
If you are on windows you might want to check out these pages.
You can always find out the location of the tnsnames.ora file being used by running TNSPING to check connectivity (9i or later):
C:\>tnsping dev
TNS Ping Utility for 32-bit Windows: Version 10.2.0.1.0 - Production on 08-JAN-2009 12:48:38
Copyright (c) 1997, 2005, Oracle. All rights reserved.
Used parameter files:
C:\oracle\product\10.2.0\client_1\NETWORK\ADMIN\sqlnet.ora
Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = XXX)(PORT = 1521)) (CONNECT_DATA = (SERVICE_NAME = DEV)))
OK (30 msec)
C:\>
Sometimes, the problem is with the entry you made in tnsnames.ora, not that the system can't find it. That said, I agree that having a tns_admin environment variable set is a Good Thing, since it avoids the inevitable issues that arise with determining exactly which tnsnames file is being used in systems with multiple oracle homes.
These methods works on the locks and locks are associated with Object and not Threads. Hence, it is in Object class.
The methods wait(), notify() and notifyAll() are not only just methods, these are synchronization utility and used in communication mechanism among threads in Java.
For more detailed explanation, please visit : http://parameshk.blogspot.in/2013/11/why-wait-notify-and-notifyall-methods.html
try boost::asio lib (http://www.boost.org/doc/libs/1_36_0/doc/html/boost_asio.html) it have lot examples.
select to_char(tran_datetime,'HH24') from test;
TO_CHAR(tran_datetime,'HH24')
------------------
16
unsigned_value = Math.abs(signed_value);
For the Sake of Understanding:
Depending on how you're approaching your objective(s), keep in mind that the developer is responsible to Dispose everything that is no longer being used or necessary.
This means: Everything you've created along with your pictureBox (i.e: Graphics, List; etc) shall be disposed whenever it is no longer necessary.
For Instance: Let's say you have a Image File Loaded into your PictureBox, and you wish to somehow Delete that file. If you don't unload the Image File from PictureBox correctly; you won't be able to delete the file, as this will likely throw an Exception saying that the file is being used.
Therefore you'd be required to do something like:
pic_PhotoDisplay.Image.Dispose();
pic_PhotoDisplay.Image = null;
pic_PhotoDisplay.ImageLocation = null;
// Required if you've drawn something in the PictureBox. Just Don't forget to Dispose Graphic.
pic_PhotoDisplay.Update();
// Depending on your approach; Dispose the Graphics with Something Like:
gfx = null;
gfx.Clear();
gfx.Dispose();
Hope this helps you out.
This is how I created filter for the Name field in Edit Text.(First letter is CAPS, and allow only single space after every word.
public void setNameFilter() {
InputFilter filter = new InputFilter() {
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
if (dend == 0) {
if (Character.isSpaceChar(source.charAt(i)) ||
!Character.isAlphabetic(source.charAt(i))) {
return Constants.Delimiter.BLANK;
} else {
return String.valueOf(source.charAt(i)).toUpperCase();
}
} else if (Character.isSpaceChar(source.charAt(i)) &&
String.valueOf(dest).endsWith(Constants.Delimiter.ONE_SPACE)) {
return Constants.Delimiter.BLANK;
} else if ((!Character.isSpaceChar(source.charAt(i)) &&
!Character.isAlphabetic(source.charAt(i)))) {
return Constants.Delimiter.BLANK;
}
}
return null;
}
};
editText.setFilters(new InputFilter[]{filter, new InputFilter.LengthFilter(Constants.Length.NAME_LENGTH)});
}
Use substr()
with a negative number for the 2nd argument.
$newstring = substr($dynamicstring, -7);
From the php docs:
string substr ( string $string , int $start [, int $length ] )
If start is negative, the returned string will start at the start'th character from the end of string.
package com.test;
import java.util.ArrayList;
import java.util.List;
public class TEst {
public static void main(String[] args) {
List<Integer> ls=new ArrayList<>();
ls.add(1);
ls.add(2);
List<Integer> ls1=new ArrayList<>();
ls1.add(3);
ls1.add(4);
List<List<Integer>> ls2=new ArrayList<>();
ls2.add(ls);
ls2.add(ls1);
List<List<List<Integer>>> ls3=new ArrayList<>();
ls3.add(ls2);
m1(ls3);
}
private static void m1(List ls3) {
for(Object ls4:ls3)
{
if(ls4 instanceof List)
{
m1((List)ls4);
}else {
System.out.print(ls4);
}
}
}
}
display: inline-block;
won't work in any of IE browsers. Here is what I used.
// change the width of #boxContainer to
// 1-2 pixels higher than total width of the boxes inside:
#boxContainer {
width: 800px;
height: auto;
text-align: center;
margin-left: auto;
margin-right: auto;
}
#Box{
width: 240px;
height: 90px;
background-color: #FFF;
float: left;
margin-left: 10px;
margin-right: 10px;
}
I was trying to do a similar task to get a dropdown arrow always on the right side of the table header and came up with this which seemed to work in Chrome and Firefox, but safari was telling me it was an invalid property.
background: url(http://goo.gl/P93P5Q) center right 10px no-repeat;
After doing a bit of messing around in the inspector, I came up with this cross-browser solution that works in IE8+, Chrome, Firefox, and Safari, as well as responsive designs.
background: url(http://goo.gl/P93P5Q) no-repeat 95% center;
Here is a codepen of how it looks and works. Codepen is written with SCSS - http://cdpn.io/xqGbk
I solve my problem by passing nil permission while login.
[FBSession openActiveSessionWithReadPermissions:nil
allowLoginUI:YES
completionHandler:
If you use Data.Text, there is splitOn:
http://hackage.haskell.org/packages/archive/text/0.11.2.0/doc/html/Data-Text.html#v:splitOn
This is built in the Haskell Platform.
So for instance:
import qualified Data.Text as T
main = print $ T.splitOn (T.pack " ") (T.pack "this is a test")
or:
{-# LANGUAGE OverloadedStrings #-}
import qualified Data.Text as T
main = print $ T.splitOn " " "this is a test"
This looks a little ugly. Is it possible to cast an entire stream to a different type? Like cast
Stream<Object>
to aStream<Client>
?
No that wouldn't be possible. This is not new in Java 8. This is specific to generics. A List<Object>
is not a super type of List<String>
, so you can't just cast a List<Object>
to a List<String>
.
Similar is the issue here. You can't cast Stream<Object>
to Stream<Client>
. Of course you can cast it indirectly like this:
Stream<Client> intStream = (Stream<Client>) (Stream<?>)stream;
but that is not safe, and might fail at runtime. The underlying reason for this is, generics in Java are implemented using erasure. So, there is no type information available about which type of Stream
it is at runtime. Everything is just Stream
.
BTW, what's wrong with your approach? Looks fine to me.
Just wanted to add that if you want to add several parameters with the same key name for example: www.test.com/home?id=1&id=2
let params = new HttpParams();
params = params.append(key, value);
Use append, if you use set, it will overwrite the previous value with the same key name.
Have you tried:
#!/usr/local/bin/php
I.e. without the -q
part? That's what the error message "Could not open input file: -q" means. The first argument to php
if it doesn't look like an option is the name of the PHP file to execute, and -q
is CGI only.
EDIT: A couple of (non-related) tips:
?>
. In fact, it is often better not to.STDIN
to fopen("php://stdin", "r")
. You can use that instead of opening "php://stdin"
a second time: $fd = STDIN;
If you have fixed values (like a month name list) and want a one-line solution
var result = ['January', 'February', 'March'][Math.floor(Math.random() * 3)]
The second part of the array is an access operation as described in Why does [5,6,8,7][1,2] = 8 in JavaScript?
Javascript can have inheritance, check out the URL below:
http://www.webreference.com/js/column79/
Andrew
I know this is an old thread but thought I should mention that the extern
keyword. I've recently ran into this issue and solved as follows
Helper.h
namespace DX
{
extern inline void ThrowIfFailed(HRESULT hr);
}
Helper.cpp
namespace DX
{
inline void ThrowIfFailed(HRESULT hr)
{
if (FAILED(hr))
{
std::stringstream ss;
ss << "#" << hr;
throw std::exception(ss.str().c_str());
}
}
}
If anyone's still stuck on this, the easiest solution I found was to "Retarget Solution". In my case, the project was built of SDK 8.1, upgrading to VS2017 brought with it SDK 10.0.xxx.
To retarget solution: Project->Retarget Solution->"Select whichever SDK you have installed"->OK
From there on you can simply build/debug your solution. Hope it helps
I know a simple answer!
Open your cmd, the type in: cd C:\directory your file is in
and then type python your progam.py
div {_x000D_
height:50px;_x000D_
}_x000D_
.short-div {_x000D_
height:25px;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
<div class="container">_x000D_
<h1>Responsive Bootstrap</h1>_x000D_
<div class="row">_x000D_
<div class="col-lg-5 col-md-5 col-sm-5 col-xs-5" style="background-color:red;">Span 5</div>_x000D_
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3" style="background-color:blue">Span 3</div>_x000D_
<div class="col-lg-2 col-md-2 col-sm-3 col-xs-2" style="padding:0px">_x000D_
<div class="short-div" style="background-color:green">Span 2</div>_x000D_
<div class="short-div" style="background-color:purple">Span 2</div>_x000D_
</div>_x000D_
<div class="col-lg-2 col-md-2 col-sm-3 col-xs-2" style="background-color:yellow">Span 2</div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="container-fluid">_x000D_
<div class="row-fluid">_x000D_
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">_x000D_
<div class="short-div" style="background-color:#999">Span 6</div>_x000D_
<div class="short-div">Span 6</div>_x000D_
</div>_x000D_
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6" style="background-color:#ccc">Span 6</div>_x000D_
</div>_x000D_
</div>
_x000D_
What you could also have a look at is the exposed method Application->loadEnvironmentFrom($file)
I needed one application to run on multiple subdomains. So in bootstrap/app.php
I added something like:
$envFile = '.env';
// change $envFile conditionally here
$app->loadEnvironmentFrom($envFile);
Use border-collapse and border-spacing to get spaces between the table cells. I would not recommend using floating cells as suggested by QQping.
If you want to create a table with the only structure to be copied from the original table then you can use the following command to do that.
create table <tablename> as select * from <sourcetablename> where 1>2;
By this false condition you can leave the records and copy the structure.
To search for multiple matches in each file, we can sequence several Select-String calls:
Get-ChildItem C:\Logs |
where { $_ | Select-String -Pattern 'VendorEnquiry' } |
where { $_ | Select-String -Pattern 'Failed' } |
...
At each step, files that do not contain the current pattern will be filtered out, ensuring that the final list of files contains all of the search terms.
Rather than writing out each Select-String call manually, we can simplify this with a filter to match multiple patterns:
filter MultiSelect-String( [string[]]$Patterns ) {
# Check the current item against all patterns.
foreach( $Pattern in $Patterns ) {
# If one of the patterns does not match, skip the item.
$matched = @($_ | Select-String -Pattern $Pattern)
if( -not $matched ) {
return
}
}
# If all patterns matched, pass the item through.
$_
}
Get-ChildItem C:\Logs | MultiSelect-String 'VendorEnquiry','Failed',...
Now, to satisfy the "Logtime about 11:30 am" part of the example would require finding the log time corresponding to each failure entry. How to do this is highly dependent on the actual structure of the files, but testing for "about" is relatively simple:
function AboutTime( [DateTime]$time, [DateTime]$target, [TimeSpan]$epsilon ) {
$time -le ($target + $epsilon) -and $time -ge ($target - $epsilon)
}
PS> $epsilon = [TimeSpan]::FromMinutes(5)
PS> $target = [DateTime]'11:30am'
PS> AboutTime '11:00am' $target $epsilon
False
PS> AboutTime '11:28am' $target $epsilon
True
PS> AboutTime '11:35am' $target $epsilon
True
Usually, I work with DATE columns, not the larger but more precise TIMESTAMP used by some answers.
The following will return the current UTC date as just that -- a DATE.
CAST(sys_extract_utc(SYSTIMESTAMP) AS DATE)
I often store dates like this, usually with the field name ending in _UTC
to make it clear for the developer. This allows me to avoid the complexity of time zones until last-minute conversion by the user's client. Oracle can store time zone detail with some data types, but those types require more table space than DATE, and knowledge of the original time zone is not always required.
A good seed generation for me is:
Random rand = new Random(Guid.NewGuid().GetHashCode());
It is very random. The seed is always different because the seed is also random generated.
There is a constructor accepting two pointer parameters, so the code is simply
std::string cppstr(cstr, cstr + min(max_length, strlen(cstr)));
this is also going to be as efficient as std::string cppstr(cstr)
if the length is smaller than max_length
.
I read solution from official website of Gson at here
And this code for you:
String json = "{"client":"127.0.0.1","servers":["8.8.8.8","8.8.4.4","156.154.70.1","156.154.71.1"]}";
JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class);
JsonArray jsonArray = jsonObject.getAsJsonArray("servers");
String[] arrName = new Gson().fromJson(jsonArray, String[].class);
List<String> lstName = new ArrayList<>();
lstName = Arrays.asList(arrName);
for (String str : lstName) {
System.out.println(str);
}
Result show on monitor:
8.8.8.8
8.8.4.4
156.154.70.1
156.154.71.1
Any future date in JavaScript (postman test uses JavaScript) can be retrieved as:
var dateNow = new Date();
var twoWeeksFutureDate = new Date(dateNow.setDate(dateNow.getDate() + 14)).toISOString();
postman.setEnvironmentVariable("future-date", twoWeeksFutureDate);
Python 3:
def is_prime(a):
return a > 1 and all(a % i for i in range(2, int(a**0.5) + 1))
Everything in the java.lang
package is implicitly imported (including String) and you do not need to do so yourself. This is simply a feature of the Java language. ArrayList and HashMap are however in the java.util
package, which is not implicitly imported.
The package java.lang mostly includes essential features, such a class version of primitives, basic exceptions and the Object class. This being integral to most programs, forcing people to import them is redundant and thus the contents of this package are implicitly imported.
Make sure to also add "C:\Python27\Scripts" to your path. pip.exe should be in that folder. Then you can just run:
C:\> pip install modulename
This worked for me on win replace REL_PATH_TO_FILE with the relative path to the file to remove Removing sensitive data from a repository The docs say full path - but that errored for me -so I tried rel path and it worked.
<from the repo dir>git filter-branch --force --index-filter "git rm --cached --ignore-unmatch REL_PATH_TO_FILE" --prune-empty --tag-name-filter cat -- --all
For a non ASP.NET control, i.e. HTML controls like div, table, td, tr
, etc. you need to first make them a server control, assign an ID, and then assign a property from server code:
<head>
<style type="text/css">
.top_rounded
{
height: 75px;
width: 75px;
border: 2px solid;
border-radius: 5px;
-moz-border-radius: 5px; /* Firefox 3.6 and earlier */
border-color: #9c1c1f;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div runat="server" id="myDiv">This is my div</div>
</form>
</body>
myDiv.Attributes.Add("class", "top_rounded");
If you just want direct subclasses then .__subclasses__()
works fine. If you want all subclasses, subclasses of subclasses, and so on, you'll need a function to do that for you.
Here's a simple, readable function that recursively finds all subclasses of a given class:
def get_all_subclasses(cls):
all_subclasses = []
for subclass in cls.__subclasses__():
all_subclasses.append(subclass)
all_subclasses.extend(get_all_subclasses(subclass))
return all_subclasses
When you assign a variable to empty curly braces {} eg: new_set = {}
, it becomes a dictionary.
To create an empty set, assign the variable to a 'set()' ie: new_set = set()
You shouldn't have to care that much. RFC 3339, according to itself, is a set of standards derived from ISO 8601. There's quite a few minute differences though, and they're all outlined in RFC 3339. I could go through them all here, but you'd probably do better just reading the document for yourself in the event you're worried:
I'm seeing this error code in rotation crashes on Xcode 12.0 Beta 6, only on the iOS 14 simulator. It doesn't crash on my real device running iOS 13 though! So if you're running beta stuff and seeing rotation crashes in the simulator, maybe you just need to run on a real device with a non-beta iOS version.
Try this
<head>
<style type ="text/css" >
.footer{
position: fixed;
text-align: center;
bottom: 0px;
width: 100%;
}
</style>
</head>
<body>
<div class="footer">All Rights Reserved</div>
</body>
Simpler and a Standard solution to increment the number and to retain the dot at the end. Even if you get the css right, it will not work if your HTML is not correct. see below.
ol {
counter-reset: item;
}
ol li {
display: block;
}
ol li:before {
content: counters(item, ". ") ". ";
counter-increment: item;
}
ol {
counter-reset: item;
li {
display: block;
&:before {
content: counters(item, ". ") ". ";
counter-increment: item
}
}
}
If you add the child make sure the it is under the parent li
.
<!-- WRONG -->
<ol>
<li>Parent 1</li> <!-- Parent is Individual. Not hugging -->
<ol>
<li>Child</li>
</ol>
<li>Parent 2</li>
</ol>
<!-- RIGHT -->
<ol>
<li>Parent 1
<ol>
<li>Child</li>
</ol>
</li> <!-- Parent is Hugging the child -->
<li>Parent 2</li>
</ol>
This exception will be returned if you attempt to count values in a null collection.
For example the below works when Errors is not null, however if Errors is null then the Value cannot be null. Parameter name: source exception occurs.
if (graphQLResponse.Errors.Count() > 0)
This exception can be avoided by checking for null instead.
if (graphQLResponse.Errors != null)
You can combine data from the two tables, order by goals highest first and then choose the top two like this:
MySQL
select *
from (
select * from tblMadrid
union all
select * from tblBarcelona
) alldata
order by goals desc
limit 0,2;
SQL Server
select top 2 *
from (
select * from tblMadrid
union all
select * from tblBarcelona
) alldata
order by goals desc;
If you only want Messi and Ronaldo
select * from tblBarcelona where name = 'messi'
union all
select * from tblMadrid where name = 'ronaldo'
To ensure that messi is at the top of the result, you can do something like this:
select * from (
select * from tblBarcelona where name = 'messi'
union all
select * from tblMadrid where name = 'ronaldo'
) stars
order by name;
You should place Scanner input = new Scanner (System.in);
into the main method rather than creating the input object outside.
mode: 'no-cors'
won’t magically make things work. In fact it makes things worse, because one effect it has is to tell browsers, “Block my frontend JavaScript code from looking at contents of the response body and headers under all circumstances.” Of course you almost never want that.
What happens with cross-origin requests from frontend JavaScript is that browsers by default block frontend code from accessing resources cross-origin. If Access-Control-Allow-Origin
is in a response, then browsers will relax that blocking and allow your code to access the response.
But if a site sends no Access-Control-Allow-Origin
in its responses, your frontend code can’t directly access responses from that site. In particular, you can’t fix it by specifying mode: 'no-cors'
(in fact that’ll ensure your frontend code can’t access the response contents).
However, one thing that will work: if you send your request through a CORS proxy.
You can also easily deploy your own proxy to Heroku in literally just 2-3 minutes, with 5 commands:
git clone https://github.com/Rob--W/cors-anywhere.git
cd cors-anywhere/
npm install
heroku create
git push heroku master
After running those commands, you’ll end up with your own CORS Anywhere server running at, for example, https://cryptic-headland-94862.herokuapp.com/
.
Prefix your request URL with your proxy URL; for example:
https://cryptic-headland-94862.herokuapp.com/https://example.com
Adding the proxy URL as a prefix causes the request to get made through your proxy, which then:
https://example.com
.https://example.com
.Access-Control-Allow-Origin
header to the response.The browser then allows the frontend code to access the response, because that response with the Access-Control-Allow-Origin
response header is what the browser sees.
This works even if the request is one that triggers browsers to do a CORS preflight OPTIONS
request, because in that case, the proxy also sends back the Access-Control-Allow-Headers
and Access-Control-Allow-Methods
headers needed to make the preflight successful.
I can hit this endpoint,
http://catfacts-api.appspot.com/api/facts?number=99
via Postman
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS explains why it is that even though you can access the response with Postman, browsers won’t let you access the response cross-origin from frontend JavaScript code running in a web app unless the response includes an Access-Control-Allow-Origin
response header.
http://catfacts-api.appspot.com/api/facts?number=99 has no Access-Control-Allow-Origin
response header, so there’s no way your frontend code can access the response cross-origin.
Your browser can get the response fine and you can see it in Postman and even in browser devtools—but that doesn’t mean browsers will expose it to your code. They won’t, because it has no Access-Control-Allow-Origin
response header. So you must instead use a proxy to get it.
The proxy makes the request to that site, gets the response, adds the Access-Control-Allow-Origin
response header and any other CORS headers needed, then passes that back to your requesting code. And that response with the Access-Control-Allow-Origin
header added is what the browser sees, so the browser lets your frontend code actually access the response.
So I am trying to pass in an object, to my Fetch which will disable CORS
You don’t want to do that. To be clear, when you say you want to “disable CORS” it seems you actually mean you want to disable the same-origin policy. CORS itself is actually a way to do that — CORS is a way to loosen the same-origin policy, not a way to restrict it.
But anyway, it’s true you can — in just your local environment — do things like give your browser runtime flags to disable security and run insecurely, or you can install a browser extension locally to get around the same-origin policy, but all that does is change the situation just for you locally.
No matter what you change locally, anybody else trying to use your app is still going to run into the same-origin policy, and there’s no way you can disable that for other users of your app.
You most likely never want to use mode: 'no-cors'
in practice except in a few limited cases, and even then only if you know exactly what you’re doing and what the effects are. That’s because what setting mode: 'no-cors'
actually says to the browser is, “Block my frontend JavaScript code from looking into the contents of the response body and headers under all circumstances.” In most cases that’s obviously really not what you want.
As far as the cases when you would want to consider using mode: 'no-cors'
, see the answer at What limitations apply to opaque responses? for the details. The gist of it is that the cases are:
In the limited case when you’re using JavaScript to put content from another origin into a <script>
, <link rel=stylesheet>
, <img>
, <video>
, <audio>
, <object>
, <embed>
, or <iframe>
element (which works because embedding of resources cross-origin is allowed for those) — but for some reason you don’t want to or can’t do that just by having the markup of the document use the resource URL as the href
or src
attribute for the element.
When the only thing you want to do with a resource is to cache it. As alluded to in the answer What limitations apply to opaque responses?, in practice the scenario that applies to is when you’re using Service Workers, in which case the API that’s relevant is the Cache Storage API.
But even in those limited cases, there are some important gotchas to be aware of; see the answer at What limitations apply to opaque responses? for the details.
I have also tried to pass in the object
{ mode: 'opaque'}
There is no mode: 'opaque'
request mode — opaque
is instead just a property of the response, and browsers set that opaque property on responses from requests sent with the no-cors
mode.
But incidentally the word opaque is a pretty explicit signal about the nature of the response you end up with: “opaque” means you can’t see it.
Not a definite answer but too much to fit in comments:
I hypothesize they gave you a cert that either has a wrong issuer (although their server could use a more specific alert code for that) or a wrong subject. We know the cert matches your privatekey -- because both curl
and openssl client
paired them without complaining about a mismatch; but we don't actually know it matches their desired CA(s) -- because your curl uses openssl and openssl SSL client does NOT enforce that a configured client cert matches certreq.CAs.
Do openssl x509 <clientcert.pem -noout -subject -issuer
and the same on the cert from the test P12 that works. Do openssl s_client
(or check the one you did) and look under Acceptable client certificate CA names
; the name there or one of them should match (exactly!) the issuer(s) of your certs. If not, that's most likely your problem and you need to check with them you submitted your CSR to the correct place and in the correct way. Perhaps they have different regimes in different regions, or business lines, or test vs prod, or active vs pending, etc.
If the issuer of your cert does match desiredCAs, compare its subject to the working (test-P12) one: are they in similar format? are there any components in the working one not present in yours? If they allow it, try generating and submitting a new CSR with a subject name exactly the same as the test-P12 one, or as close as you can get, and see if that produces a cert that works better. (You don't have to generate a new key to do this, but if you choose to, keep track of which certs match which keys so you don't get them mixed up.) If that doesn't help look at the certificate extensions with openssl x509 <cert -noout -text
for any difference(s) that might reasonably be related to subject authorization, like KeyUsage, ExtendedKeyUsage, maybe Policy, maybe Constraints, maybe even something nonstandard.
If all else fails, ask the server operator(s) what their logs say about the problem, or if you have access look at the logs yourself.
Based on the other answers it seems like this message has a lot of causes, I thought I'd just share my individual solution in case anyone has my exact problem in the future.
Our site loads the CSS files from an AWS Cloudfront distribution, which uses an S3 bucket as the origin. This particular S3 bucket was kept synced to a Linux server running Jenkins. The sync
command via s3cmd
sets the Content-Type for the S3 object automatically based on what the OS says (presumably based on the file extension). For some reason, in our server, all the types were being set correctly except .css
files, which it gave the type text/plain
. In S3, when you check the metadata in the properties of a file, you can set the type to whatever you want. Setting it to text/css
allowed our site to correctly interpret the files as CSS and load correctly.
import os
os.listdir("path") # returns list
This will not give you the first one as javascript objects are unordered, however this is fine in some cases.
myObject[Object.keys(myObject)[0]]
Actually the XSD is XML itself. Its purpose is to validate the structure of another XML document. The XSD is not mandatory for any XML, but it assures that the XML could be used for some particular purposes. The XML is only containing data in suitable format and structure.
Ok, i had a few problems because i was inside a
$('.my-dropdown').live('click', function(){
});
I had multiples inside my page that's why i used a class.
My drop down was filled automatically by a ajax request when i clicked it, so i only had the element $(this)
so...
I had to do:
$('.my-dropdown').live('click', function(){
total_tems = $(this).find('option').length;
});
In my case I had a float value expected where xml had a null value so be sure to search for float and int data type in your xsd map
Use parse_url()
as Pekka said:
<?php
$url = 'http://www.example.com/search.php?arg1=arg2';
$parts = parse_url($url);
$str = $parts['scheme'].'://'.$parts['host'].$parts['path'];
echo $str;
?>
In this example the optional username and password aren't output!
You can try saving (or writing) the Buffered Image with the changes you made and then opening it as an Image.
EDIT:
try {
// Retrieve Image
BufferedImage buffer = ImageIO.read(new File("old.png"));;
// Here you can rotate your image as you want (making your magic)
File outputfile = new File("saved.png");
ImageIO.write(buffer, "png", outputfile); // Write the Buffered Image into an output file
Image image = ImageIO.read(new File("saved.png")); // Opening again as an Image
} catch (IOException e) {
...
}
I was stuck trying to implement this in typescript, all of the above would not work. I had to first cast the element in order for typescript to have access to the contentWindow.
let iframe = document.getElementById('frameId') as HTMLIFrameElement;
iframe.contentWindow.print();
When you generate a JAXB model from an XML Schema, global elements that correspond to named complex types will have that metadata captured as an @XmlElementDecl
annotation on a create method in the ObjectFactory
class. Since you are creating the JAXBContext
on just the DocumentType
class this metadata isn't being processed. If you generated your JAXB model from an XML Schema then you should create the JAXBContext
on the generated package name or ObjectFactory
class to ensure all the necessary metadata is processed.
Example solution:
JAXBContext jaxbContext = JAXBContext.newInstance(my.generatedschema.dir.ObjectFactory.class);
DocumentType documentType = ((JAXBElement<DocumentType>) jaxbContext.createUnmarshaller().unmarshal(inputStream)).getValue();
Adding an answer because I was directed here after asking how to run a bash script from python. You receive an error OSError: [Errno 2] file not found
if your script takes in parameters. Lets say for instance your script took in a sleep time parameter: subprocess.call("sleep.sh 10")
will not work, you must pass it as an array: subprocess.call(["sleep.sh", 10])
Your problem is that at the moment your incoming_Cid
column defined as CHAR(1)
when it should be CHAR(34)
.
To fix this just issue this command to change your columns' length from 1 to 34
ALTER TABLE calls CHANGE incoming_Cid incoming_Cid CHAR(34);
Here is SQLFiddle demo
var form = document.getElementById("idOfForm");
form.onsubmit = function() {
return false;
}
This combination (and values near to these) seems to "magically" work for me to keep the colorbar scaled to the plot, no matter what size the display.
plt.colorbar(im,fraction=0.046, pad=0.04)
It also does not require sharing the axis which can get the plot out of square.
For who is searching to do it without creating a background sector, just add those lines to the TextView
android:background="?android:attr/selectableItemBackground"
android:clickable="true"
Also to make it selectable use:
android:textIsSelectable="true"
NSTimeInterval milisecondedDate = ([[NSDate date] timeIntervalSince1970] * 1000);
/^[a-zA-Z]+$/
Off the top of my head.
Edit:
Or if you don't like the weird looking literal syntax you can do it like this
new RegExp("^[a-zA-Z]+$");
there are multiple ways to achieve this objective :
using console.time
console.time('function');
//run the function in between these two lines for that you need to
//measure time taken by the function. ("ex. function();")
console.timeEnd('function');
this is the most efficient way : using performance.now(), e.g.
var v1 = performance.now();
//run the function here for which you have top measure the time
var v2 = performance.now();
console.log("total time taken = "+(v2-v1)+"milliseconds");
use +(add operator) or getTime()
var h2 = +new Date(); //or
var h2 = new Date().getTime();
for(i=0;i<500;i++) { /* do something */}
var h3 = +new Date(); //or
var h3 = new Date().getTime();
var timeTaken = h3-h2;
console.log("time ====", timeTaken);
Here's what happens when you apply the unary plus operator to a Date instance: Get the value of the Date instance in question Convert it to a Number
NOTE: getTime()
gives better performance than unary + operator.
Those three things you said are all true.
I suppose you could reverse your tree and put the smaller keys on the right, but really the "left" and "right" concept is just that: a visual concept to help us think about a data structure which doesn't really have a left or right, so it doesn't really matter.
I found "display:flex"
style is a good way to make these elements in same line. No matter what kind of element in the div. Especially if the input class is form-control,other solutions like bootstrap, inline-block will not work well.
Example:
<div style="display:flex; flex-direction: row; justify-content: center; align-items: center">
<label for="Student">Name:</label>
<input name="Student" />
</div>
More detail about display:flex:
flex-direction: row, column
justify-content: flex-end, center, space-between, space-around
align-items: stretch, flex-start, flex-end, center
Excel 2010 - if you're looking to reorder the series on a pivot chart:
textAlign
property only works when there is a more space left for the Text
's content. Below are 2 examples which shows when textAlign has impact and when not.
For instance, in this example, it won't have any impact because there is no extra space for the content of the Text
.
Text(
"Hello",
textAlign: TextAlign.end, // no impact
),
If you wrap it in a Container
and provide extra width
such that it has more extra space.
Container(
width: 200,
color: Colors.orange,
child: Text(
"Hello",
textAlign: TextAlign.end, // has impact
),
)
private static final String mText = "SHOP MA" + "\n" +
+ "----------------------------" + "\n" +
+ "Pannampitiya" + newline +
+ "09-10-2012 harsha no: 001" + "\n" +
+ "No Item Qty Price Amount" + "\n" +
+ "1 Bread 1 50.00 50.00" + "\n" +
+ "____________________________" + "\n";
This should work.
You can use a lookaround:
^(?=.*[A-Za-z0-9])[A-Za-z0-9 _]*$
It will check ahead that the string has a letter or number, if it does it will check that the rest of the chars meet your requirements. This can probably be improved upon, but it seems to work with my tests.
UPDATE:
Adding modifications suggested by Chris Lutz:
^(?=.*[^\W_])[\w ]*$/
you code is fine but never executed, cause of submit button [type="submit"] just replace it by type=button
<input value="Submit" type="button" onclick="submitform()">
inside your script; form is not declared.
let form = document.forms[0];
xhr.open(form.method, form.action, true);
Here is a script that does exactly what you want
https://github.com/UziTech/js-date-format
var d = new Date("2010-8-10");
document.write(d.format("DD-MMM-YYYY"));
Your line:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.
Try
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
The Android Developer pages still state how you can download and use the ADT plugin for Eclipse:
https://dl-ssl.google.com/android/eclipse/
Links for the Eclipse ADT Bundle (found using Archive.org's WayBackMachine) I don't know how future-proof these links are. They all worked on February 27th, 2017.
Update (2015-06-29): Google will end development and official support for ADT in Eclipse at the end of this year and recommends switching to Android Studio.
Simply with native html & css :
<div class="tooltip">Hover over me
<span class="tooltiptext">Tooltip text</span>
</div>
/* Tooltip container */
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black; /* If you want dots under the hoverable text */
}
/* Tooltip text */
.tooltip .tooltiptext {
visibility: hidden;
width: 120px;
background-color: #555;
color: #fff;
text-align: center;
padding: 5px 0;
border-radius: 6px;
/* Position the tooltip text */
position: absolute;
z-index: 1;
bottom: 125%;
left: 50%;
margin-left: -60px;
/* Fade in tooltip */
opacity: 0;
transition: opacity 0.3s;
}
/* Tooltip arrow */
.tooltip .tooltiptext::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;
}
/* Show the tooltip text when you mouse over the tooltip container */
.tooltip:hover .tooltiptext {
visibility: visible;
opacity: 1;
}
Here is the source of the example from w3schools
There is another way to pass multiple ranges to a function, which I think feels much cleaner for the user. When you call your function in the spreadsheet you wrap each set of ranges in brackets, for example: calculateIt( (A1,A3), (B6,B9) )
The above call assumes your two Sessions are in A1 and A3, and your two Customers are in B6 and B9.
To make this work, your function needs to loop through each of the Areas
in the input ranges. For example:
Function calculateIt(Sessions As Range, Customers As Range) As Single
' check we passed the same number of areas
If (Sessions.Areas.Count <> Customers.Areas.Count) Then
calculateIt = CVErr(xlErrNA)
Exit Function
End If
Dim mySession, myCustomers As Range
' run through each area and calculate
For a = 1 To Sessions.Areas.Count
Set mySession = Sessions.Areas(a)
Set myCustomers = Customers.Areas(a)
' calculate them...
Next a
End Function
The nice thing is, if you have both your inputs as a contiguous range, you can call this function just as you would a normal one, e.g. calculateIt(A1:A3, B6:B9)
.
Hope that helps :)
import os, win32api, win32con, win32process
han = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION|win32con.PROCESS_VM_READ, 0, os.getpid())
process_memory = int(win32process.GetProcessMemoryInfo(han)['WorkingSetSize'])
Cardinality of a set is the namber of the elements in set for we have a set a > a,b,c < so ths set contain 3 elements 3 is the cardinality of that set
may be this code may give you some idea.
http://blog.nemikor.com/2009/04/18/loading-a-page-into-a-dialog/
$(document).ready(function() {
$('#page-help').each(function() {
var $link = $(this);
var $dialog = $('<div></div>')
.load($link.attr('href'))
.dialog({
autoOpen: false,
title: $link.attr('title'),
width: 500,
height: 300
});
$link.click(function() {
$dialog.dialog('open');
return false;
});
});
});
GitHub
git config --global url.ssh://[email protected]/.insteadOf https://github.com/
BitBucket
git config --global url.ssh://[email protected]/.insteadOf https://bitbucket.org/
That tells git to always use SSH instead of HTTPS when connecting to GitHub/BitBucket, so you'll authenticate by certificate by default, instead of being prompted for a password.
MySQL is most likely in STRICT
mode, which isn't necessarily a bad thing, as you'll identify bugs/issues early and not just blindly think everything is working as you intended.
Change the column to allow null:
ALTER TABLE `x` CHANGE `display_name` `display_name` TEXT NULL
or, give it a default value as empty string:
ALTER TABLE `x` CHANGE `display_name` `display_name` TEXT NOT NULL DEFAULT ''
What is the current approach to make a custom AuthorizeAttribute
Easy: don't create your own AuthorizeAttribute
.
For pure authorization scenarios (like restricting access to specific users only), the recommended approach is to use the new authorization block: https://github.com/aspnet/MusicStore/blob/1c0aeb08bb1ebd846726232226279bbe001782e1/samples/MusicStore/Startup.cs#L84-L92
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AuthorizationOptions>(options =>
{
options.AddPolicy("ManageStore", policy => policy.RequireClaim("Action", "ManageStore"));
});
}
}
public class StoreController : Controller
{
[Authorize(Policy = "ManageStore"), HttpGet]
public async Task<IActionResult> Manage() { ... }
}
For authentication, it's best handled at the middleware level.
What are you trying to achieve exactly?
This is a firewall issue, if you are using a VMware application, make sure the firewall on the antivirus is turned off or allowing connections.
If this server is on a secure network, please have a look at firewall rules of the server.
Thanks Ganesh PNS
They are found on either one of the below locations depending on how chrome was installed
~/Users/<username>/Library/Application\ Support/Google/Chrome/Default/Extensions
/Library/Application\ Support/Google/Chrome/Default/Extensions
Why don't you check if text.trim() has a different length? :
if(text.length() == text.trim().length() || otherConditions){
//your code
}
According to the official doc (https://nodejs.org/api/esm.html#esm_code_import_code_statements):
import statements are permitted only in ES modules. For similar functionality in CommonJS, see import().
To make Node treat your file as a ES module you need to (https://nodejs.org/api/esm.html#esm_enabling):
select *
from YourTable
where ','+replace(col, ' ', '')+',' like '%,Cat,%'
Right click on the code, and you have "Format Document". In my case it is Ctrl+Shift+I
If the following conditions are true, then rewrite the URL:
If the requested filename is not a directory,
RewriteCond %{REQUEST_FILENAME} !-d
and if the requested filename is not a regular file that exists,
RewriteCond %{REQUEST_FILENAME} !-f
and if the requested filename is not a symbolic link,
RewriteCond %{REQUEST_FILENAME} !-l
then rewrite the URL in the following way:
Take the whole request filename and provide it as the value of a "url" query parameter to index.php. Append any query string from the original URL as further query parameters (QSA), and stop processing this .htaccess file (L).
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
Another Example:
RewriteRule "/pages/(.+)" "/page.php?page=$1" [QSA]
With the [QSA] flag, a request for
/pages/123?one=two
will be mapped to
/page.php?page=123&one=two
Fast and easy with HAVING:
SELECT * FROM tblpm n
FROM tblpm GROUP BY control_number
HAVING date_updated=MAX(date_updated);
In the context of HAVING
, MAX
finds the max of each group. Only the latest entry in each group will satisfy date_updated=max(date_updated)
. If there's a tie for latest within a group, both will pass the HAVING
filter, but GROUP BY
means that only one will appear in the returned table.
The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc
A set of simple examples:
Using Gson:
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class Gson {
public static void main(String[] args) {
}
public HttpResponse http(String url, String body) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPost request = new HttpPost(url);
StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
com.google.gson.Gson gson = new com.google.gson.Gson();
Response respuesta = gson.fromJson(json, Response.class);
System.out.println(respuesta.getExample());
System.out.println(respuesta.getFr());
} catch (IOException ex) {
}
return null;
}
public class Response{
private String example;
private String fr;
public String getExample() {
return example;
}
public void setExample(String example) {
this.example = example;
}
public String getFr() {
return fr;
}
public void setFr(String fr) {
this.fr = fr;
}
}
}
Using json-simple:
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JsonSimple {
public static void main(String[] args) {
}
public HttpResponse http(String url, String body) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPost request = new HttpPost(url);
StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
try {
JSONParser parser = new JSONParser();
Object resultObject = parser.parse(json);
if (resultObject instanceof JSONArray) {
JSONArray array=(JSONArray)resultObject;
for (Object object : array) {
JSONObject obj =(JSONObject)object;
System.out.println(obj.get("example"));
System.out.println(obj.get("fr"));
}
}else if (resultObject instanceof JSONObject) {
JSONObject obj =(JSONObject)resultObject;
System.out.println(obj.get("example"));
System.out.println(obj.get("fr"));
}
} catch (Exception e) {
// TODO: handle exception
}
} catch (IOException ex) {
}
return null;
}
}
etc...
Sometimes diff
is the utility you need, but sometimes join
is more appropriate. The files need to be pre-sorted or, if you are using a shell which supports process substitution such as bash, ksh or zsh, you can do the sort on the fly.
join -v 1 <(sort file1) <(sort file2)
Unique Key (UK): It's a column or a group of columns that can identify a uniqueness in a row.
Primary Key (PK): It's also a column or group of columns that can identify a uniqueness in a row.
So the Primary key is just another name for unique key, but the default implementation in SQL Server is different for Primary and Unique Key.
By Default:
It really depends what is your aim when deciding whether to create a UK or PK. It follows an analogy like "If there is a team of three people, so all of them are peers, but there will be one of them who will be a pair of peers: PK and UK has similar relation.". I would suggest reading this article: The example given by the author may not seem suitable, but try to get an overall idea.
http://tsqltips.blogspot.com/2012/06/difference-between-unique-key-and.html
As the message said, you should set permission as owner to your user. So you can use following:
ALTER AUTHORIZATION
ON DATABASE::[YourDBName]
TO [UserLogin];
Hope helpful! Leave comment if it's ok for you.
No one mentioned that case classes are also instances of Product
and thus inherit these methods:
def productElement(n: Int): Any
def productArity: Int
def productIterator: Iterator[Any]
where the productArity
returns the number of class parameters, productElement(i)
returns the ith parameter, and productIterator
allows iterating through them.
use android:theme="@android:style/Theme.NoTitleBar
in manifest file's application tag to remove the title bar for whole application or put it in activity tag to remove the title bar from a single activity screen.
Try this more succinct code:
Sub LoopOverEachColumn()
Dim WS As Worksheet
For Each WS In ThisWorkbook.Worksheets
ResizeColumns WS
Next WS
End Sub
Private Sub ResizeColumns(WS As Worksheet)
Dim StrSize As String
Dim ColIter As Long
StrSize = "20.14;9.71;35.86;30.57;23.57;21.43;18.43;23.86;27.43;36.71;30.29;31.14;31;41.14;33.86"
For ColIter = 1 To 15
WS.Columns(ColIter).ColumnWidth = Split(StrSize, ";")(ColIter - 1)
Next ColIter
End Sub
If you want additional columns, just change 1 to 15
to 1 to X
where X
is the column index of the column you want, and append the column size you want to StrSize
.
For example, if you want P:P
to have a width of 25
, just add ;25
to StrSize
and change ColIter...
to ColIter = 1 to 16
.
Hope this helps.
var sessionVal = '@Session["EnergyUnit"]';
alert(sessionVal);
Something as simple as [a-z]+
, or perhaps [\S]+
, or even [a-zA-Z]+
?
While entering the serial port name into the code in arduino IDE, enter the whole port address i.e:
/dev/cu.usbmodem*
or
/dev/cu.UG-*
where the *
is the port number.
And for the port number in case of mac just open terminal and type
ls /dev/*
and then search for the port that u have set in arduino IDE.
I also met the same problem and I was able to get it through. So let me explain the steps I applied. I shall explain it according to your scenario.
According to my method we need to use 'Path' class and 'Assembly' class in order to get the relative path.
So first Import System.IO and System.Reflection in using statements.
Then type the below given code line.
var outPutDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly(). CodeBase);
Actually above given line stores the path of the output directory of your project.(Here 'output' directory refers to the Debug folder of your project).
Now copy your FolderIcon directory in to the Debug folder. Then type the below given Line.
var iconPath = Path.Combine(outPutDirectory, "FolderIcon\\Folder.ico");
Now this 'iconPath ' variable contains the entire path of your Folder.ico. All you have to do is store it in a string variable. Use the line of code below for that.
string icon_path = new Uri(iconPath ).LocalPath;
Now you can use this icon_path string variable as your relative path to the icon.
Thanks.
So my question is: Is there a way to tell the compiler that a long long int is the also a int64_t, just like long int is?
This is a good question or problem, but I suspect the answer is NO.
Also, a long int
may not be a long long int
.
# if __WORDSIZE == 64 typedef long int int64_t; # else __extension__ typedef long long int int64_t; # endif
I believe this is libc. I suspect you want to go deeper.
In both 32-bit compile with GCC (and with 32- and 64-bit MSVC), the output of the program will be:
int: 0 int64_t: 1 long int: 0 long long int: 1
32-bit Linux uses the ILP32 data model. Integers, longs and pointers are 32-bit. The 64-bit type is a long long
.
Microsoft documents the ranges at Data Type Ranges. The say the long long
is equivalent to __int64
.
However, the program resulting from a 64-bit GCC compile will output:
int: 0 int64_t: 1 long int: 1 long long int: 0
64-bit Linux uses the LP64
data model. Longs are 64-bit and long long
are 64-bit. As with 32-bit, Microsoft documents the ranges at Data Type Ranges and long long is still __int64
.
There's a ILP64
data model where everything is 64-bit. You have to do some extra work to get a definition for your word32
type. Also see papers like 64-Bit Programming Models: Why LP64?
But this is horribly hackish and does not scale well (actual functions of substance, uint64_t, etc)...
Yeah, it gets even better. GCC mixes and matches declarations that are supposed to take 64 bit types, so its easy to get into trouble even though you follow a particular data model. For example, the following causes a compile error and tells you to use -fpermissive
:
#if __LP64__
typedef unsigned long word64;
#else
typedef unsigned long long word64;
#endif
// intel definition of rdrand64_step (http://software.intel.com/en-us/node/523864)
// extern int _rdrand64_step(unsigned __int64 *random_val);
// Try it:
word64 val;
int res = rdrand64_step(&val);
It results in:
error: invalid conversion from `word64* {aka long unsigned int*}' to `long long unsigned int*'
So, ignore LP64
and change it to:
typedef unsigned long long word64;
Then, wander over to a 64-bit ARM IoT gadget that defines LP64
and use NEON:
error: invalid conversion from `word64* {aka long long unsigned int*}' to `uint64_t*'
In my case, I forgot to add the ()
I was calling the method like this
obj = className.myMethod
But it should be is like this
obj = className.myMethod()
First, Set :
ALTER TABLE person ALTER COLUMN phone DROP NOT NULL;
this states that Account.deposit(Double.MAX_VALUE);
it is setting deposit value to MAX value of Double
dataType.to procced for running tests.
You can use jquery load for that.
<script type="text/javascript">
$(document).ready(function(e) {
$('#header').load('name.html',function(){alert('loaded')});
});
</script>
Don't forget to include jquery library befor above code.
Right after @mail($email_to, $email_subject, $email_message, $headers);
header('Location: nextpage.php');
Note that you will never see 'Thanks for subscribing to our mailing list'
That should be on the next page, if you echo any text you will get an error because the headers would have been already created, if you want to redirect never return any text, not even a space!
The following code will help you to get the element of the mouse pointer. The resulted elements will display in the console.
document.addEventListener('mousemove', function(e) {
console.log(document.elementFromPoint(e.pageX, e.pageY));
})
Note that $(element).offset()
tells you the position of an element relative to the document. This works great in most circumstances, but in the case of position:fixed
you can get unexpected results.
If your document is longer than the viewport and you have scrolled vertically toward the bottom of the document, then your position:fixed
element's offset()
value will be greater than the expected value by the amount you have scrolled.
If you are looking for a value relative to the viewport (window), rather than the document on a position:fixed element, you can subtract the document's scrollTop()
value from the fixed element's offset().top
value. Example: $("#el").offset().top - $(document).scrollTop()
If the position:fixed
element's offset parent is the document, you want to read parseInt($.css('top'))
instead.
There are multiple REST frameworks out there. I would strongly recommend looking into Slim mini Framework for PHP
Here is a list of others.
These are identical for printf
but different for scanf
. For printf
, both %d
and %i
designate a signed decimal integer. For scanf
, %d
and %i
also means a signed integer but %i
inteprets the input as a hexadecimal number if preceded by 0x
and octal if preceded by 0
and otherwise interprets the input as decimal.
I think you missed a equal sign at:
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);
Change to:
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null);
UPDATE: Keep in mind, at the time the answer was initially written in 2010, the bellow function toFixed() worked slightly different. toFixed() seems to do some rounding now, but not in the strictly mathematical manner. So be careful with it. Do your tests... The method described bellow will do rounding well, as mathematician would expect.
toFixed()
- method converts a number into a string, keeping a specified number of decimals. It does not actually rounds up a number, it truncates the number.Math.round(n)
- rounds a number to the nearest integer. Thus turning:0.5 -> 1; 0.05 -> 0
so if you want to round, say number 0.55555, only to the second decimal place; you can do the following(this is step-by-step concept):
0.55555 * 100
= 55.555 Math.Round(55.555)
-> 56.00056.000 / 100
= 0.56000 (0.56000).toFixed(2)
-> 0.56and this is the code:
(Math.round(number * 100)/100).toFixed(2);
For anyone who is using anaconda, you would install the certifi
package, see more at:
https://anaconda.org/anaconda/certifi
To install, type this line in your terminal:
conda install -c anaconda certifi
It means that the callback function you passed to this.dataStore.data.find
should return a boolean and have 3 parameters, two of which can be optional:
However, your callback function does not return anything (returns void). You should pass a callback function with the correct return value:
this.dataStore.data.find((element, index, obj) => {
// ...
return true; // or false
});
or:
this.dataStore.data.find(element => {
// ...
return true; // or false
});
Reason why it's this way: the function you pass to the find
method is called a predicate. The predicate here defines a boolean outcome based on conditions defined in the function itself, so that the find
method can determine which value to find.
In practice, this means that the predicate is called for each item in data
, and the first item in data
for which your predicate returns true
is the value returned by find
.
To add to @adilapapaya's answer. For ember-cli
users specifically, install tether
with
bower install --save tether
and then include it in your ember-cli-build.js
file before bootstrap, like so:
// tether (bootstrap 4 requirement)
app.import('bower_components/tether/dist/js/tether.min.js');
// bootstrap
app.import('bower_components/bootstrap/scss/bootstrap-flex.scss');
app.import('bower_components/bootstrap/dist/js/bootstrap.js');
Html.TextBox amd Html.DropDownList are not strongly typed and hence they doesn't require a strongly typed view. This means that we can hardcode whatever name we want. On the other hand, Html.TextBoxFor and Html.DropDownListFor are strongly typed and requires a strongly typed view, and the name is inferred from the lambda expression.
Strongly typed HTML helpers also provide compile time checking.
Since, in real time, we mostly use strongly typed views, prefer to use Html.TextBoxFor and Html.DropDownListFor over their counterparts.
Whether, we use Html.TextBox & Html.DropDownList OR Html.TextBoxFor & Html.DropDownListFor, the end result is the same, that is they produce the same HTML.
Strongly typed HTML helpers are added in MVC2.
I think this could work:
select
case when datepart(dw,[Date]) = 1 then 7 else DATEPART(DW,[Date])-1 end as WeekDay
Step 1 :- GO to My Apps App in iTunes Connect
Here you can see your all app which are currently on Appstore.
Step 2 :- Select your app which you want to delete.(click on app-name)
Step 3 :- Select Pricing and Availability Tab.
Step 4 :- Select Remove from sale option.
Step 5 :- Click on save Button.
Now you will see below your app like , Developer Removed it from sale in Red Symbol in place of Green.
Step 6 :- Now again Select your app and Go to App information Tab. you will see Delete App option. (need to scroll bit bottom)
Step 7 :- After clicking on Delete button you will get warning like this ,
Step 8 :- Click on Delete button.
Congratulation , You have Permanently deleted your app successfully from appstore. Now , you cant able to see app on appstore aswellas in your developer account.
Note :-
When you have selected only Remove from sale option you have not deleted app permanently. You can able to make your app live again by clicking on Available in all territories option Again.
This may work:
grant all on dbtest.* to 'dbuser'@'%' identified by 'mysql_password';
WebConfigurationManager.ConnectionStrings["YourConnectionString"].ProviderName;
I got this issue resolved by removing non-desirable characters from the password for the connection. For example, I had these characters: <##% and it caused the problem (most probably hash tag was the root cause of the problem).
You can use something like ng-change=someMethod({{user.id}}). By keeping your value in side {{expression}} it will evaluate expression in-line and gives you current value(value before ng-change method is called).
<select ng-model="selectedValue" ng-change="change(selectedValue, '{{selectedValue}}')">
For a multi-threaded implementation tuned for Intel processors I'd check out Intel's MKL library. It's not free, but it's afforable (less than $100) and blazing fast - but you'd need to call it's C dll's via P/Invokes. The Exocortex project stopped development 6 years ago, so I'd be careful using it if this is an important project.
Here's a list of languages that can be used to develop on android:
Java - primary android development language
Kotlin, language from JetBrains which received first-party support from Google, announced in Google I/O 2017
C++ - NDK for libraries, not apps
Python, bash, et. al. - Via the Scripting Environment
Corona- One is to use the Corona SDK . Corona is a high level SDK built on the Lua programming language. Lua is much simpler to learn than Java and the SDK takes away a lot of the pain in developing Android app.
Cordova - which uses HTML5, JavaScript, CSS, and can be extended with Java
Xamarin technology - that uses c# and in which mono is used for that. Here MonoTouch and Mono for Android are cross-platform implementations of the Common Language Infrastructure (CLI) and Common Language Specifications.
As for your second question: android is highly dependent on it's java architecture, I find it unlikely that there will be other primary development languages available any time soon. However, there's no particular reason why someone couldn't implement another language in Java (something like Jython) and use that. However, that surely won't be easier or as performant as just writing the code in Java.
Boolean is the object wrapper class for the primitive boolean. This class, as any class, can indeed be null. For performance and memory reasons it is always best to use the primitive.
The wrapper classes in the Java API serve two primary purposes:
To extend a little bit answer of Calimo I present few more things you may find useful while creating this quasi dictionaries in R:
a) how to return all the VALUES of the dictionary:
>as.numeric(foo)
[1] 12 22 33
b) check whether dictionary CONTAINS KEY:
>'tic' %in% names(foo)
[1] TRUE
c) how to ADD NEW key, value pair to dictionary:
c(foo,tic2=44)
results:
tic tac toe tic2
12 22 33 44
d) how to fulfill the requirement of REAL DICTIONARY - that keys CANNOT repeat(UNIQUE KEYS)? You need to combine b) and c) and build function which validates whether there is such key, and do what you want: e.g don't allow insertion, update value if the new differs from the old one, or rebuild somehow key(e.g adds some number to it so it is unique)
e) how to DELETE pair BY KEY from dictionary:
foo<-foo[which(foo!=foo[["tac"]])]
In XSLT 1.0 the upper-case()
and lower-case()
functions are not available.
If you're using a 1.0 stylesheet the common method of case conversion is translate()
:
<xsl:variable name="lowercase" select="'abcdefghijklmnopqrstuvwxyz'" />
<xsl:variable name="uppercase" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'" />
<xsl:template match="/">
<xsl:value-of select="translate(doc, $lowercase, $uppercase)" />
</xsl:template>
As the error message indicates, you have an indentation error. It is probably caused by a mix of tabs and spaces.
Sometimes you want to have your GridView as simple as:
<asp:GridView ID="grid" runat="server" />
You don't want to specify any BoundField, you just want to bind your grid to DataReader. The following code helped me to format DateTime in this situation.
protected void Page_Load(object sender, EventArgs e)
{
grid.RowDataBound += grid_RowDataBound;
// Your DB access code here...
// grid.DataSource = cmd.ExecuteReader(CommandBehavior.CloseConnection);
// grid.DataBind();
}
void grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.DataRow)
return;
var dt = (e.Row.DataItem as DbDataRecord).GetDateTime(4);
e.Row.Cells[4].Text = dt.ToString("dd.MM.yyyy");
}
The results shown here.
By using the -Xmx
command line parameter when you invoke java.
See http://download.oracle.com/javase/6/docs/technotes/tools/windows/java.html
itertools.combinations is in general the fastest way to get combinations from a Python container (if you do in fact want combinations, i.e., arrangements WITHOUT repetitions and independent of order; that's not what your code appears to be doing, but I can't tell whether that's because your code is buggy or because you're using the wrong terminology).
If you want something different than combinations perhaps other iterators in itertools, product
or permutations
, might serve you better. For example, it looks like your code is roughly the same as:
for val in itertools.product(np.arange(0, 1, 0.1), repeat=6):
print F(val)
All of these iterators yield tuples, not lists or numpy arrays, so if your F is picky about getting specifically a numpy array you'll have to accept the extra overhead of constructing or clearing and re-filling one at each step.
This has been discussed into spark mailing list, and please refer this mail.
You should use hadoop fs -put <localsrc> ... <dst>
copy the file into hdfs
:
${HADOOP_COMMON_HOME}/bin/hadoop fs -put /path/to/README.md README.md
This seems to happen from time to time with programs that are very sensitive to command lines, but one option is to just use the DOS path instead of the Windows path. This means that C:\Program Files\
would resolve to C:\PROGRA~1\
and generally avoid any issues with spacing.
To get the short path you can create a quick Batch file that echos the short path:
@ECHO OFF
echo %~s1
Which is then called as follows:
C:\>shortPath.bat "C:\Program Files"
C:\PROGRA~1
Try this:
var value;
for (var key in dictionary) {
value = dictionary[key];
// your code here...
}
I want to add a point that you can also (and should if what you are writing is complex) add a test variable to rollback if you are in test mode. Then you can execute the whole thing at once. Often I also add code to see the before and after results of various operations especially if it is a complex script.
Example below:
USE AdventureWorks;
GO
DECLARE @TEST INT = 1--1 is test mode, use zero when you are ready to execute
BEGIN TRANSACTION;
BEGIN TRY
IF @TEST= 1
BEGIN
SELECT *FROM Production.Product
WHERE ProductID = 980;
END
-- Generate a constraint violation error.
DELETE FROM Production.Product
WHERE ProductID = 980;
IF @TEST= 1
BEGIN
SELECT *FROM Production.Product
WHERE ProductID = 980;
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
END
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
END CATCH;
IF @@TRANCOUNT > 0 AND @TEST = 0
COMMIT TRANSACTION;
GO
I strongly recommend taking a look at Vuex, it is made for globally accessible data in Vue.
If you only need a few base variables that will never be modified, I would use ES6 imports:
// config.js
export default {
hostname: 'myhostname'
}
// .vue file
import config from 'config.js'
console.log(config.hostname)
You could also import a json
file in the same way, which can be edited by people without code knowledge or imported into SASS.
Eric Leschinski and Bartosz Milewski have given the answer already. Here, I will try to present it in a more beginner friendly manner.
Once a thread has been started within a scope (which itself is running on a thread), one must explicitly ensure one of the following happens before the thread goes out of scope:
Note, by the time the thread is joined with or detached, it may have well finished executing. Still either of the two operations must be performed explicitly.
For me the issue was that, i had added a lib project(autobahn lib) earlier and later switched the to Jar file of the same library.Though i had removed references to the older library project, i was getting this error. Following all the answers here i checked the build path etc. But i haven't added these libs to build path manually. So i had nothing to remove. Finally came across this folder.
bin/dexedLibs
I noticed that there were two jar files with the same name corresponding to autobahn Android which was causing the conflict. So i deleted all the jar files in the dexedLibs folder and rebuild the project. That resolved the issue.
It's certainly possible to grab a screenshot using the .NET Framework. The simplest way is to create a new Bitmap
object and draw into that using the Graphics.CopyFromScreen
method.
Sample code:
using (Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height))
using (Graphics g = Graphics.FromImage(bmpScreenCapture))
{
g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
Screen.PrimaryScreen.Bounds.Y,
0, 0,
bmpScreenCapture.Size,
CopyPixelOperation.SourceCopy);
}
Caveat: This method doesn't work properly for layered windows. Hans Passant's answer here explains the more complicated method required to get those in your screen shots.
A simpler if statement from AskUbuntu: How do I check whether a module is installed in Python?
import sys
print('eggs' in sys.modules)
It seems that I found a solution to my problem. Very good explanations are given here and here. Here is my example:
pulic class MyActivity extends FragmentActivity{
private ViewPager pager;
private TitlePageIndicator indicator;
private TabsAdapter adapter;
private Bundle savedInstanceState;
@Override
public void onCreate(Bundle savedInstanceState) {
....
this.savedInstanceState = savedInstanceState;
pager = (ViewPager) findViewById(R.id.pager);;
indicator = (TitlePageIndicator) findViewById(R.id.indicator);
adapter = new TabsAdapter(getSupportFragmentManager(), false);
if (savedInstanceState == null){
adapter.addFragment(new FirstFragment());
adapter.addFragment(new SecondFragment());
}else{
Integer count = savedInstanceState.getInt("tabsCount");
String[] titles = savedInstanceState.getStringArray("titles");
for (int i = 0; i < count; i++){
adapter.addFragment(getFragment(i), titles[i]);
}
}
indicator.notifyDataSetChanged();
adapter.notifyDataSetChanged();
// push first task
FirstTask firstTask = new FirstTask(MyActivity.this);
// set first fragment as listener
firstTask.setTaskListener((TaskListener) getFragment(0));
firstTask.execute();
}
private Fragment getFragment(int position){
return savedInstanceState == null ? adapter.getItem(position) : getSupportFragmentManager().findFragmentByTag(getFragmentTag(position));
}
private String getFragmentTag(int position) {
return "android:switcher:" + R.id.pager + ":" + position;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("tabsCount", adapter.getCount());
outState.putStringArray("titles", adapter.getTitles().toArray(new String[0]));
}
indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
Fragment currentFragment = adapter.getItem(position);
((Taskable) currentFragment).executeTask();
}
@Override
public void onPageScrolled(int i, float v, int i1) {}
@Override
public void onPageScrollStateChanged(int i) {}
});
The main idea in this code is that, while running your application normally, you create new fragments and pass them to the adapter. When you are resuming your application fragment manager already has this fragment's instance and you need to get it from fragment manager and pass it to the adapter.
UPDATE
Also, it is a good practice when using fragments to check isAdded before getActivity() is called. This helps avoid a null pointer exception when the fragment is detached from the activity. For example, an activity could contain a fragment that pushes an async task. When the task is finished, the onTaskComplete listener is called.
@Override
public void onTaskComplete(List<Feed> result) {
progress.setVisibility(View.GONE);
progress.setIndeterminate(false);
list.setVisibility(View.VISIBLE);
if (isAdded()) {
adapter = new FeedAdapter(getActivity(), R.layout.feed_item, result);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
If we open the fragment, push a task, and then quickly press back to return to a previous activity, when the task is finished, it will try to access the activity in onPostExecute() by calling the getActivity() method. If the activity is already detached and this check is not there:
if (isAdded())
then the application crashes.