Since this commit, this is is fixed in the development version of Tomcat. And now in released versions 9.0.13, 8.5.35, and 7.0.92.
From the 9.0.13 changelog:
Ignore an attribute named source on Context elements provided by StandardContext. This is to suppress warnings generated by the Eclipse / Tomcat integration provided by Eclipse. Based on a patch by mdfst13. (markt)
There are similar entries in the 7.0.92 and 8.5.35 changelogs.
The effect of this change is to suppress a warning when a source
attribute is declared on a Context
element in either server.xml or a context.xml. Since those are the two places that Eclipse puts such an attribute, that fixes this particular issue.
TL;DR: update to the latest Tomcat version in its branch, e.g. 9.0.13 or newer.
I had the same issue using Eclipse CDT (Kepler)
on Windows
with Cygwin
installed. After pointing the project properties at every Cygwin include I could think of, it still couldn't find cout
.
The final missing piece turned out to be C:cygwin64\lib\gcc\x86_64-pc-cygwin\4.8.2\install-tool\include
.
To sum up:
Properties
C/C++ General
> Paths and Symbols
> Includes
tabAdd...
File system...
lib\gcc\x86_64-pc-cygwin\4.8.2\install-tool\include
OK
Here is what my project includes ended up looking like when it was all said and done:
Check mvn dependency:tree
and see if there are multiple repos from where slf4j belongs to two different JARs.
If so, add exclusion in one of the dependencies:
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
To use cache-control in HTML, you use the meta tag, e.g.
<meta http-equiv="Cache-control" content="public">
The value in the content field is defined as one of the four values below.
Some information on the Cache-Control
header is as follows
HTTP 1.1. Allowed values = PUBLIC | PRIVATE | NO-CACHE | NO-STORE.
Public - may be cached in public shared caches.
Private - may only be cached in private cache.
No-Cache - may not be cached.
No-Store - may be cached but not archived.The directive CACHE-CONTROL:NO-CACHE indicates cached information should not be used and instead requests should be forwarded to the origin server. This directive has the same semantics as the PRAGMA:NO-CACHE.
Clients SHOULD include both PRAGMA: NO-CACHE and CACHE-CONTROL: NO-CACHE when a no-cache request is sent to a server not known to be HTTP/1.1 compliant. Also see EXPIRES.
Note: It may be better to specify cache commands in HTTP than in META statements, where they can influence more than the browser, but proxies and other intermediaries that may cache information.
None of the above code is working smoothly.i tried this
<HorizontalScrollView
android:id="@+id/horizontalScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</HorizontalScrollView>
Try this:
$('input[name=Comanda]')
.click(
function ()
{
$(this).hide();
}
);
For doing everything else you can use something like this one:
$('input[name=Comanda]')
.click(
function ()
{
$(this).hide();
$(".ClassNameOfShouldBeHiddenElements").hide();
}
);
For hidding any other elements based on their IDs, use this one:
$('input[name=Comanda]')
.click(
function ()
{
$(this).hide();
$("#FirstElement").hide();
$("#SecondElement").hide();
$("#ThirdElement").hide();
}
);
I've generally used xml drawables to create shadow/elevation on a pre-lollipop widget. Here, for example, is an xml drawable that can be used on pre-lollipop devices to simulate the floating action button's elevation.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:top="8px">
<layer-list>
<item>
<shape android:shape="oval">
<solid android:color="#08000000"/>
<padding
android:bottom="3px"
android:left="3px"
android:right="3px"
android:top="3px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#09000000"/>
<padding
android:bottom="2px"
android:left="2px"
android:right="2px"
android:top="2px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#10000000"/>
<padding
android:bottom="2px"
android:left="2px"
android:right="2px"
android:top="2px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#11000000"/>
<padding
android:bottom="1px"
android:left="1px"
android:right="1px"
android:top="1px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#12000000"/>
<padding
android:bottom="1px"
android:left="1px"
android:right="1px"
android:top="1px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#13000000"/>
<padding
android:bottom="1px"
android:left="1px"
android:right="1px"
android:top="1px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#14000000"/>
<padding
android:bottom="1px"
android:left="1px"
android:right="1px"
android:top="1px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#15000000"/>
<padding
android:bottom="1px"
android:left="1px"
android:right="1px"
android:top="1px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#16000000"/>
<padding
android:bottom="1px"
android:left="1px"
android:right="1px"
android:top="1px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#17000000"/>
<padding
android:bottom="1px"
android:left="1px"
android:right="1px"
android:top="1px"
/>
</shape>
</item>
</layer-list>
</item>
<item>
<shape android:shape="oval">
<solid android:color="?attr/colorPrimary"/>
</shape>
</item>
</layer-list>
In place of ?attr/colorPrimary
you can choose any color. Here's a screenshot of the result:
Non-javascript way . . aspx page:
<form id="form1" runat="server">
<div>
<asp:CheckBox ID="CheckBox1" runat="server" />
<asp:CustomValidator ID="CustomValidator1"
runat="server" ErrorMessage="CustomValidator" ControlToValidate="CheckBox1"></asp:CustomValidator>
</div>
</form>
Code Behind:
Protected Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
If Not CheckBox1.Checked Then
args.IsValid = False
End If
End Sub
For any actions you might need (business Rules):
If Page.IsValid Then
'do logic
End If
Sorry for the VB code . . . you can convert it to C# if that is your pleasure. The company I am working for right now requires VB :(
The linefeed character \n
is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n
instead, then it'll both see the line-break with only \n
and \r\n
, I've never had any problems using it.
Also, you should look into using a StringBuilder
instead of concatenating the String
in the while-loop at BookCatalog.toString()
, it is a lot more effective. For instance:
public String toString() {
BookNode current = front;
StringBuilder sb = new StringBuilder();
while (current!=null){
sb.append(current.getData().toString()+"\r\n ");
current = current.getNext();
}
return sb.toString();
}
Can this not be done simply by adding a additional "container" div and adding the removed alert div back into it each time. Seems to work for me?
HTML
<div id="alert_container"></div>
JS
$("#alert_container").html('<div id="alert"></div>');
$("#alert").addClass("alert alert-info alert-dismissible");
$("#alert").html('<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a><strong>Info!</strong>message');
I was recently working with IPFS and worked this out. A curl example for IPFS to upload a file looks like this:
curl -i -H "Content-Type: multipart/form-data; boundary=CUSTOM" -d $'--CUSTOM\r\nContent-Type: multipart/octet-stream\r\nContent-Disposition: file; filename="test"\r\n\r\nHello World!\n--CUSTOM--' "http://localhost:5001/api/v0/add"
The basic idea is that each part (split by string in boundary
with --
) has it's own headers (Content-Type
in the second part, for example.) The FormData
object manages all this for you, so it's a better way to accomplish our goals.
This translates to fetch API like this:
const formData = new FormData()
formData.append('blob', new Blob(['Hello World!\n']), 'test')
fetch('http://localhost:5001/api/v0/add', {
method: 'POST',
body: formData
})
.then(r => r.json())
.then(data => {
console.log(data)
})
try this, tested on windows platform and it works fine :
from selenium import webdriver
browser = webdriver.Chrome('C:\\Users\\yeivic\\Downloads\\chromedriver')
browser.fullscreen_window()
browser.get('http://google.com/')
Just in case anyone wants yet another solution:
Hope it helps someone.
-Ev
Here is another simple answer, but without using classes.
from tkinter import *
def raise_frame(frame):
frame.tkraise()
root = Tk()
f1 = Frame(root)
f2 = Frame(root)
f3 = Frame(root)
f4 = Frame(root)
for frame in (f1, f2, f3, f4):
frame.grid(row=0, column=0, sticky='news')
Button(f1, text='Go to frame 2', command=lambda:raise_frame(f2)).pack()
Label(f1, text='FRAME 1').pack()
Label(f2, text='FRAME 2').pack()
Button(f2, text='Go to frame 3', command=lambda:raise_frame(f3)).pack()
Label(f3, text='FRAME 3').pack(side='left')
Button(f3, text='Go to frame 4', command=lambda:raise_frame(f4)).pack(side='left')
Label(f4, text='FRAME 4').pack()
Button(f4, text='Goto to frame 1', command=lambda:raise_frame(f1)).pack()
raise_frame(f1)
root.mainloop()
Below is an example of such a query:
INSERT INTO [93275].[93276].[93277].[93278] ( [Mobile Number], [Mobile Series], [Full Name], [Full Address], [Active Date], company ) IN 'I:\For Test\90-Mobile Series.accdb
SELECT [1].[Mobile Number], [1].[Mobile Series], [1].[Full Name], [1].[Full Address], [1].[Active Date], [1].[Company Name]
FROM 1
WHERE ((([1].[Mobile Series])="93275" Or ([1].[Mobile Series])="93276")) OR ((([1].[Mobile Series])="93277"));OR ((([1].[Mobile Series])="93278"));
Here is a read/write example. The with statements insure the close() statement will be called by the file object regardless of whether an exception is thrown. http://effbot.org/zone/python-with-statement.htm
import sys
fIn = 'symbolsIn.csv'
fOut = 'symbolsOut.csv'
try:
with open(fIn, 'r') as f:
file_content = f.read()
print "read file " + fIn
if not file_content:
print "no data in file " + fIn
file_content = "name,phone,address\n"
with open(fOut, 'w') as dest:
dest.write(file_content)
print "wrote file " + fOut
except IOError as e:
print "I/O error({0}): {1}".format(e.errno, e.strerror)
except: #handle other exceptions such as attribute errors
print "Unexpected error:", sys.exc_info()[0]
print "done"
Here is simplest way how to change navbar color after window scroll:
Add follow JS to head:
$(function () {
$(document).scroll(function () {
var $nav = $(".navbar-fixed-top");
$nav.toggleClass('scrolled', $(this).scrollTop() > $nav.height());
});
});
and this CSS code
.navbar-fixed-top.scrolled {
background-color: #fff !important;
transition: background-color 200ms linear;
}
Background color of fixed navbar will be change to white when scroll exceeds height of navbar.
See follow JsFiddle
At the beginning of your main method, add this line of code :
final long startTime = System.nanoTime();
And then, at the last line of your main method, you can add :
final long duration = System.nanoTime() - startTime;
duration
now contains the time in nanoseconds that your program ran. You can for example print this value like this:
System.out.println(duration);
If you want to show duration time in seconds, you must divide the value by 1'000'000'000. Or if you want a Date
object: Date myTime = new Date(duration / 1000);
You can then access the various methods of Date
to print number of minutes, hours, etc.
If implemented Comparable<T>
(ex. Integer
, String
, Date
), you can do it using Comparator.reverseOrder()
.
List<Integer> list = Arrays.asList(1, 2, 3, 4);
list.stream()
.sorted(Comparator.reverseOrder())
.forEach(System.out::println);
For those using Bootstrap 4 is simple:
<span class="align-middle"><i class="fas fa-camera"></i></span>
There is little to be added to Garrett's great answer, but pandas also has a scatter
method. Using that, it's as easy as
df = pd.DataFrame(np.random.randn(10,2), columns=['col1','col2'])
df['col3'] = np.arange(len(df))**2 * 100 + 100
df.plot.scatter('col1', 'col2', df['col3'])
Use this code
Intent intent = new Intent(getApplicationContext(), SomeActvity.class);
PendingIntent pIntent = PendingIntent.getActivity(getApplicationContext(),
(int) System.currentTimeMillis(), intent, 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.your_notification_icon)
.setContentTitle("Notification title")
.setContentText("Notification message!")
.setContentIntent(pIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, mBuilder.build());
If you are using VS 2010 and it is a ASP.NET project make sure you have the Visual Developer installed from the VS 2010 CD. This is not the free one, but part of what is required to work on ASP.NET projects in Visual Studio.
You can also specify the range with the coord_cartesian command to set the y-axis range that you want, an like in the previous post use scales = free_x
p <- ggplot(plot, aes(x = pred, y = value)) +
geom_point(size = 2.5) +
theme_bw()+
coord_cartesian(ylim = c(-20, 80))
p <- p + facet_wrap(~variable, scales = "free_x")
p
This depends on implementation, but the general rule is that the domain is checked against all SANs and the common name. If the domain is found there, then the certificate is ok for connection.
RFC 5280, section 4.1.2.6 says "The subject name MAY be carried in the subject field and/or the subjectAltName extension". This means that the domain name must be checked against both SubjectAltName extension and Subject property (namely it's common name parameter) of the certificate. These two places complement each other, and not duplicate it. And SubjectAltName is a proper place to put additional names, such as www.domain.com or www2.domain.com
Update: as per RFC 6125, published in 2011, the validator must check SAN first, and if SAN exists, then CN should not be checked. Note that RFC 6125 is relatively recent and there still exist certificates and CAs that issue certificates, which include the "main" domain name in CN and alternative domain names in SAN. I.e. by excluding CN from validation if SAN is present, you can deny some otherwise valid certificate.
You don't want git revert
. That undoes a previous commit. You want git checkout
to get git's version of the file from master.
git checkout -- filename.txt
In general, when you want to perform a git operation on a single file, use -- filename
.
2020 Update
Git introduced a new command git restore
in version 2.23.0
. Therefore, if you have git version 2.23.0+
, you can simply git restore filename.txt
- which does the same thing as git checkout -- filename.txt
. The docs for this command do note that it is currently experimental.
You could use x ** (1. / 3)
to compute the (floating-point) cube root of x
.
The slight subtlety here is that this works differently for negative numbers in Python 2 and 3. The following code, however, handles that:
def is_perfect_cube(x):
x = abs(x)
return int(round(x ** (1. / 3))) ** 3 == x
print(is_perfect_cube(63))
print(is_perfect_cube(64))
print(is_perfect_cube(65))
print(is_perfect_cube(-63))
print(is_perfect_cube(-64))
print(is_perfect_cube(-65))
print(is_perfect_cube(2146689000)) # no other currently posted solution
# handles this correctly
This takes the cube root of x
, rounds it to the nearest integer, raises to the third power, and finally checks whether the result equals x
.
The reason to take the absolute value is to make the code work correctly for negative numbers across Python versions (Python 2 and 3 treat raising negative numbers to fractional powers differently).
If you have a class for each of your input box, then you can do it as
var checked = []
$('input.Booking').each(function ()
{
checked.push($(this).val());
});
As I was redirected here searching for a method to find digits in string in Kotlin
language, I'll leave my findings here for other folks wanting a solution specific to Kotlin.
Finding out if a string contains digit:
val hasDigits = sampleString.any { it.isDigit() }
Finding out if a string contains only digits:
val hasOnlyDigits = sampleString.all { it.isDigit() }
Extract digits from string:
val onlyNumberString = sampleString.filter { it.isDigit() }
Using TypeScript, and avoid multiples calls on the function
let el1= <HTMLInputElement>document.getElementById('searchUser');
el1.onkeypress = SearchListEnter;
function SearchListEnter(event: KeyboardEvent) {
if (event.which !== 13) {
return;
}
// more stuff
}
Looks like no, though it was requested, and there’s a UDF for it.
Edit: Or there’s… this. Ugh.
There are two ways to do the same instruction, that is, an empty string. The first way is to allocate an empty string on static memory:
char* my_variable = "";
or, if you want to be explicit:
char my_variable = '\0';
The way posted above is only for a character. And, the second way:
#include <string.h>
char* my_variable = strdup("");
Don't forget to use free() with this one because strdup() use malloc inside.
Upgrading NPM to the latest version can greatly help with this. dule's answer above is right to say that dependency management is a bit broken, but it seems that this is mainly for older versions of npm.
The command npm list
gives you a list of all installed node_modules
. When I upgraded from version 1.4.2 to version 2.7.4, many modules that were previously flagged with WARN unmet dependency
were no longer noted as such.
To update npm, you should type npm install -g npm
on MacOSX or Linux. On Windows, I found that re-downloading and re-running the nodejs installer was a more effective way to update npm.
There's no dedicated "character type" in C language. char
is an integer type, same (in that regard) as int
, short
and other integer types. char
just happens to be the smallest integer type. So, just like any other integer type, it can be signed or unsigned.
It is true that (as the name suggests) char
is mostly intended to be used to represent characters. But characters in C are represented by their integer "codes", so there's nothing unusual in the fact that an integer type char
is used to serve that purpose.
The only general difference between char
and other integer types is that plain char
is not synonymous with signed char
, while with other integer types the signed
modifier is optional/implied.
UPDATE for Django >= 1.7
Per Django 2.1 documentation: Serving files uploaded by a user during development
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
# ... the rest of your URLconf goes here ...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
You no longer need if settings.DEBUG
as Django will handle ensuring this is only used in Debug mode.
ORIGINAL answer for Django <= 1.6
Try putting this into your urls.py
from django.conf import settings
# ... your normal urlpatterns here
if settings.DEBUG:
# static files (images, css, javascript, etc.)
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}))
With this you can serve the static media from Django when DEBUG = True
(when you run on local computer) but you can let your web server configuration serve static media when you go to production and DEBUG = False
Try this:
var jIsHasKids = $('#chkIsHasKids').attr('checked');
jIsHasKids = jIsHasKids.toString().toLowerCase();
//OR
jIsHasKids = jIsHasKids.val().toLowerCase();
Possible duplicate with: How do I use jQuery to ignore case when selecting
First, note that the question presents an incorrect initialization of an aware datetime object:
>>> local_time=datetime.datetime(2010, 4, 27, 12, 0, 0, 0,
... tzinfo=pytz.timezone('Israel'))
creates an invalid instance. One can see the problem by computing the UTC offset of the resulting object:
>>> print(local_time.utcoffset())
2:21:00
(Note the result which is an odd fraction of an hour.)
To initialize an aware datetime properly using pytz one should use the localize()
method as follows:
>>> local_time=pytz.timezone('Israel').localize(datetime.datetime(2010, 4, 27, 12))
>>> print(local_time.utcoffset())
3:00:00
Now, if you require a local pytz timezone as the new tzinfo, you should use the tzlocal package as others have explained, but if all you need is an instance with a correct local time zone offset and abbreviation then tarting with Python 3.3, you can call the astimezone()
method with no arguments to convert an aware datetime
instance to your local timezone:
>>> local_time.astimezone().strftime('%Y-%m-%d %H:%M %Z %z')
'2010-04-27 05:00 EDT -0400'
After own diligent searches I found several solutions, where each has advantages and disadvantages. Use the most suitable for your task.
All examples tested with the CPython 3.5 on the operation system GNU/Linux Debian 8.
Using a recursion
Code
def get_digits_from_left_to_right(number, lst=None):
"""Return digits of an integer excluding the sign."""
if lst is None:
lst = list()
number = abs(number)
if number < 10:
lst.append(number)
return tuple(lst)
get_digits_from_left_to_right(number // 10, lst)
lst.append(number % 10)
return tuple(lst)
Demo
In [121]: get_digits_from_left_to_right(-64517643246567536423)
Out[121]: (6, 4, 5, 1, 7, 6, 4, 3, 2, 4, 6, 5, 6, 7, 5, 3, 6, 4, 2, 3)
In [122]: get_digits_from_left_to_right(0)
Out[122]: (0,)
In [123]: get_digits_from_left_to_right(123012312312321312312312)
Out[123]: (1, 2, 3, 0, 1, 2, 3, 1, 2, 3, 1, 2, 3, 2, 1, 3, 1, 2, 3, 1, 2, 3, 1, 2)
Using the function divmod
Code
def get_digits_from_right_to_left(number):
"""Return digits of an integer excluding the sign."""
number = abs(number)
if number < 10:
return (number, )
lst = list()
while number:
number, digit = divmod(number, 10)
lst.insert(0, digit)
return tuple(lst)
Demo
In [125]: get_digits_from_right_to_left(-3245214012321021213)
Out[125]: (3, 2, 4, 5, 2, 1, 4, 0, 1, 2, 3, 2, 1, 0, 2, 1, 2, 1, 3)
In [126]: get_digits_from_right_to_left(0)
Out[126]: (0,)
In [127]: get_digits_from_right_to_left(9999999999999999)
Out[127]: (9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9)
Using a construction tuple(map(int, str(abs(number)))
In [109]: tuple(map(int, str(abs(-123123123))))
Out[109]: (1, 2, 3, 1, 2, 3, 1, 2, 3)
In [110]: tuple(map(int, str(abs(1412421321312))))
Out[110]: (1, 4, 1, 2, 4, 2, 1, 3, 2, 1, 3, 1, 2)
In [111]: tuple(map(int, str(abs(0))))
Out[111]: (0,)
Using the function re.findall
In [112]: tuple(map(int, re.findall(r'\d', str(1321321312))))
Out[112]: (1, 3, 2, 1, 3, 2, 1, 3, 1, 2)
In [113]: tuple(map(int, re.findall(r'\d', str(-1321321312))))
Out[113]: (1, 3, 2, 1, 3, 2, 1, 3, 1, 2)
In [114]: tuple(map(int, re.findall(r'\d', str(0))))
Out[114]: (0,)
Using the module decimal
In [117]: decimal.Decimal(0).as_tuple().digits
Out[117]: (0,)
In [118]: decimal.Decimal(3441120391321).as_tuple().digits
Out[118]: (3, 4, 4, 1, 1, 2, 0, 3, 9, 1, 3, 2, 1)
In [119]: decimal.Decimal(-3441120391321).as_tuple().digits
Out[119]: (3, 4, 4, 1, 1, 2, 0, 3, 9, 1, 3, 2, 1)
In order to navigate to a different drive/directory you can do it in convenient way (instead of typing cd /e/Study/Codes), just type in cd[Space], and drag-and-drop your directory Codes with your mouse to git bash, hit [Enter].
Your code is actually attempting to make a Cross-domain (CORS) request, not an ordinary POST
.
That is: Modern browsers will only allow Ajax calls to services in the same domain as the HTML page.
Example: A page in http://www.example.com/myPage.html
can only directly request services that are in http://www.example.com
, like http://www.example.com/testservice/etc
. If the service is in other domain, the browser won't make the direct call (as you'd expect). Instead, it will try to make a CORS request.
To put it shortly, to perform a CORS request, your browser:
OPTION
request to the target URLOPTION
contains the adequate headers (Access-Control-Allow-Origin
is one of them) to allow the CORS request, the browse will perform the call (almost exactly the way it would if the HTML page was at the same domain).
How to solve it? The simplest way is to enable CORS (enable the necessary headers) on the server.
If you don't have server-side access to it, you can mirror the web service from somewhere else, and then enable CORS there.
Here's my JavaScript solution that is a little more functional through use of reduce/map, which eliminates almost all variables
function combinations(arr, size) {_x000D_
var len = arr.length;_x000D_
_x000D_
if (size > len) return [];_x000D_
if (!size) return [[]];_x000D_
if (size == len) return [arr];_x000D_
_x000D_
return arr.reduce(function (acc, val, i) {_x000D_
var res = combinations(arr.slice(i + 1), size - 1)_x000D_
.map(function (comb) { return [val].concat(comb); });_x000D_
_x000D_
return acc.concat(res);_x000D_
}, []);_x000D_
}_x000D_
_x000D_
var combs = combinations([1,2,3,4,5,6,7,8],3);_x000D_
combs.map(function (comb) {_x000D_
document.body.innerHTML += comb.toString() + '<br />';_x000D_
});_x000D_
_x000D_
document.body.innerHTML += '<br /> Total combinations = ' + combs.length;
_x000D_
You are providing a string representation of a dict to the DataFrame constructor, and not a dict itself. So this is the reason you get that error.
So if you want to use your code, you could do:
df = DataFrame(eval(data))
But better would be to not create the string in the first place, but directly putting it in a dict. Something roughly like:
data = []
for row in result_set:
data.append({'value': row["tag_expression"], 'key': row["tag_name"]})
But probably even this is not needed, as depending on what is exactly in your result_set
you could probably:
DataFrame(result_set)
read_sql_query
function to do this for you (see docs on this)Every public folder makes the permission to 755. Problem solved.
Couple of solutions I found to be helpful while looking this up, especially for larger data sets:
df[(df.sum(axis=1) != 0)] # 30% faster
df[df.values.sum(axis=1) != 0] # 3X faster
Continuing with the example from @U2EF1:
In [88]: df = pd.DataFrame({'a':[0,0,1,1], 'b':[0,1,0,1]})
In [91]: %timeit df[(df.T != 0).any()]
1000 loops, best of 3: 686 µs per loop
In [92]: df[(df.sum(axis=1) != 0)]
Out[92]:
a b
1 0 1
2 1 0
3 1 1
In [95]: %timeit df[(df.sum(axis=1) != 0)]
1000 loops, best of 3: 495 µs per loop
In [96]: %timeit df[df.values.sum(axis=1) != 0]
1000 loops, best of 3: 217 µs per loop
On a larger dataset:
In [119]: bdf = pd.DataFrame(np.random.randint(0,2,size=(10000,4)))
In [120]: %timeit bdf[(bdf.T != 0).any()]
1000 loops, best of 3: 1.63 ms per loop
In [121]: %timeit bdf[(bdf.sum(axis=1) != 0)]
1000 loops, best of 3: 1.09 ms per loop
In [122]: %timeit bdf[bdf.values.sum(axis=1) != 0]
1000 loops, best of 3: 517 µs per loop
To make it work I build my directory like this:
Project Public Restrict
So I edited my webconfig for my public folder:
<location path="Project/Public">
<system.web>
<authorization>
<allow users="?"/>
</authorization>
</system.web>
</location>
And for my Restricted folder:
<location path="Project/Restricted">
<system.web>
<authorization>
<allow users="*"/>
</authorizatio>
</system.web>
</location>
See here for the spec of * and ?:
https://docs.microsoft.com/en-us/iis/configuration/system.webserver/security/authorization/add
I hope I have helped.
You probably mean the difference between Http Only cookies and their counter part?
Http Only cookies cannot be accessed (read from or written to) in client side JavaScript, only server side. If the Http Only flag is not set, or the cookie is created in (client side) JavaScript, the cookie can be read from and written to in (client side) JavaScript as well as server side.
C# does have a preprocessor. It works just slightly differently than that of C++ and C.
Here is a MSDN links - the section on all preprocessor directives.
By adding following code of line in bundle to config it works for me
bundles.IgnoreList.Clear();
Because font doesn't have color, you need a panel to make a backgound color and give the foreground color for both JLabel (if you use JLabel) and JPanel to make font color, like example below :
JLabel lblusr = new JLabel("User name : ");
lblusr.setForeground(Color.YELLOW);
JPanel usrPanel = new JPanel();
Color maroon = new Color (128, 0, 0);
usrPanel.setBackground(maroon);
usrPanel.setOpaque(true);
usrPanel.setForeground(Color.YELLOW);
usrPanel.add(lblusr);
The background color of label is maroon with yellow font color.
In my case I had a cherry pick that produce a number of Merge Conflicts, so I decide to not complete the cherry pick. I discarded all my changes. Doing so put me into a state where I received the following error:
You have not concluded your merge (MERGE_HEAD exists
To fix the issue I performed the following git command which fixed the problem.
git cherry-pick --abort
That simply means that your server does not have access to the SMTP Server.
You can test this by doing:
telnet <smtpServer> <smtpPort>
You should get the Access denied error.
The solution is to just use another SMTP server that can be accessed by your server.
Method
$user = $stmt->fetch(PDO::FETCH_ASSOC);
returns a dictionary. You can simply get email and password:
$email = $user['email'];
$password = $user['password'];
Other method
$users = $stmt->fetchall(PDO::FETCH_ASSOC);
returns a list of a dictionary
Thanks to Steven's suggestion to use fetchColumn, here's my recommendation to cut short one line from your code.
$DBH = new PDO( "connection string goes here" );
$STH = $DBH->query( "select figure from table1" );
$result = $STH->fetchColumn();
echo $result;
$DBH = null;
A cleaner way to do this:
class Book {
public Title: string;
public Price: number;
public Description: string;
constructor(public BookId: number, public Author: string){}
}
Then
var bks: Book[] = [
new Book(1, "vamsee")
];
Unfortunately you cannot do it in one command. There is an open issue for the very feature.
Currently you'll have to do it by hand. If you need to do it often, you can create a custom gradle plugin, or just prepare your own project skeleton and copy it when needed.
EDIT
The JIRA issue mentioned above has been resolved, as of May 1, 2013, and fixed in 1.7-rc-1. The documentation on the Build Init Plugin is available, although it indicates that this feature is still in the "incubating" lifecycle.
When you add an object to $stateProvider.state
that object is then passed with the state. So you can add additional properties which you can read later on when needed.
Example route configuration
$stateProvider
.state('public', {
abstract: true,
module: 'public'
})
.state('public.login', {
url: '/login',
module: 'public'
})
.state('tool', {
abstract: true,
module: 'private'
})
.state('tool.suggestions', {
url: '/suggestions',
module: 'private'
});
The $stateChangeStart
event gives you acces to the toState
and fromState
objects. These state objects will contain the configuration properties.
Example check for the custom module property
$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
if (toState.module === 'private' && !$cookies.Session) {
// If logged out and transitioning to a logged in page:
e.preventDefault();
$state.go('public.login');
} else if (toState.module === 'public' && $cookies.Session) {
// If logged in and transitioning to a logged out page:
e.preventDefault();
$state.go('tool.suggestions');
};
});
I didn't change the logic of the cookies because I think that is out of scope for your question.
You can create a Helper to get you this to work more modular.
Value publicStates
myApp.value('publicStates', function(){
return {
module: 'public',
routes: [{
name: 'login',
config: {
url: '/login'
}
}]
};
});
Value privateStates
myApp.value('privateStates', function(){
return {
module: 'private',
routes: [{
name: 'suggestions',
config: {
url: '/suggestions'
}
}]
};
});
The Helper
myApp.provider('stateshelperConfig', function () {
this.config = {
// These are the properties we need to set
// $stateProvider: undefined
process: function (stateConfigs){
var module = stateConfigs.module;
$stateProvider = this.$stateProvider;
$stateProvider.state(module, {
abstract: true,
module: module
});
angular.forEach(stateConfigs, function (route){
route.config.module = module;
$stateProvider.state(module + route.name, route.config);
});
}
};
this.$get = function () {
return {
config: this.config
};
};
});
Now you can use the helper to add the state configuration to your state configuration.
myApp.config(['$stateProvider', '$urlRouterProvider',
'stateshelperConfigProvider', 'publicStates', 'privateStates',
function ($stateProvider, $urlRouterProvider, helper, publicStates, privateStates) {
helper.config.$stateProvider = $stateProvider;
helper.process(publicStates);
helper.process(privateStates);
}]);
This way you can abstract the repeated code, and come up with a more modular solution.
Note: the code above isn't tested
The Angular microsyntax lets you configure a directive in a compact, friendly string. The microsyntax parser translates that string into attributes on the <ng-template>
. The let keyword declares a template input variable that you reference within the template.
Try AndroidDBvieweR!
https://pythonhosted.org/pyexcel/iapi/pyexcel.sheets.Sheet.html see : row_range() Utility function to get row range
if you use pyexcel, can call row_range get max rows.
python 3.4 test pass.
It means the connection was successfully established at some point, but when you tried to commit right there, the connection was no longer open. The parameters you mentioned sound like connection pool settings. If so, they're unrelated to this problem. The most likely cause is a firewall between you and the database that is killing connections after a certain amount of idle time. The most common fix is to make your connection pool run a validation query when a connection is checked out from it. This will immediately identify and evict dead connnections, ensuring that you only get good connections out of the pool.
The join() method allows one thread to wait for the completion of another.However, as with sleep, join is dependent on the OS for timing, so you should not assume that join will wait exactly as long as you specify.
status of 200 will be the default when using res.send
, res.json
, etc.
You can set the status like res.status(500).json({ error: 'something is wrong' });
Often I'll do something like...
router.get('/something', function(req, res, next) {
// Some stuff here
if(err) {
res.status(500);
return next(err);
}
// More stuff here
});
Then have my error middleware send the response, and do anything else I need to do when there is an error.
Additionally: res.sendStatus(status)
has been added as of version 4.9.0
http://expressjs.com/4x/api.html#res.sendStatus
There is no =>
for if.
Use if %energy% GEQ %m2enc%
See if /?
for some other details.
I have Notepad++ v6.8.8
Find: [([a-zA-Z])]
Replace: [\'\1\']
Will produce: $array[XYZ] => $array['XYZ']
PowerShell will actually treat any comma-separated list as an array:
"server1","server2"
So the @ is optional in those cases. However, for associative arrays, the @ is required:
@{"Key"="Value";"Key2"="Value2"}
Officially, @ is the "array operator." You can read more about it in the documentation that installed along with PowerShell, or in a book like "Windows PowerShell: TFM," which I co-authored.
Style the ::-ms-clear
pseudo-element for the box:
.someinput::-ms-clear {
display: none;
}
Without any iteration with the --line-buffered grep option:
your_command | grep --line-buffered "your search"
Real life exemple with a Symfony PHP Framework router debug command ouput, to grep all "api" related routes:
php bin/console d:r | grep --line-buffered "api"
trim off everything after the last instance of ":"
cat fileListingPathsAndFiles.txt | grep -o '^.*:'
and if you wanted to drop that last ":"
cat file.txt | grep -o '^.*:' | sed 's/:$//'
@kp123: you'd want to replace :
with /
(where the sed colon should be \/
)
Execute Exec DBMS_XDB.SETHTTPPORT(8181);
as SYS/SYSTEM. Replace 8181 with the port you'd like changing to. Tested this with Oracle 10g.
Source : http://hodentekhelp.blogspot.com/2008/08/my-oracle-10g-xe-is-on-port-8080-can-i.html
First of all, based on your @extend
directive, it seems you're not using pure CSS, but a preprocessor such as SASS os Stylus.
Now, when we talk about "order of precedence" in CSS, there is a general rule involved: whatever rules set after other rules (in a top-down fashion) are applied. In your case, just by specifying .smallbox
after .smallbox-paysummary
you would be able to change the precedence of your rules.
However, if you wanna go a bit further, I suggest this reading: CSS cascade W3C specification. You will find that the precedence of a rule is based on:
Interfaces allow statically typed languages to support polymorphism. An Object Oriented purist would insist that a language should provide inheritance, encapsulation, modularity and polymorphism in order to be a fully-featured Object Oriented language. In dynamically-typed - or duck typed - languages (like Smalltalk,) polymorphism is trivial; however, in statically typed languages (like Java or C#,) polymorphism is far from trivial (in fact, on the surface it seems to be at odds with the notion of strong typing.)
Let me demonstrate:
In a dynamically-typed (or duck typed) language (like Smalltalk), all variables are references to objects (nothing less and nothing more.) So, in Smalltalk, I can do this:
|anAnimal|
anAnimal := Pig new.
anAnimal makeNoise.
anAnimal := Cow new.
anAnimal makeNoise.
That code:
makeNoise
to the pig.The same Java code would look something like this (making the assumption that Duck and Cow are subclasses of Animal:
Animal anAnimal = new Pig();
duck.makeNoise();
anAnimal = new Cow();
cow.makeNoise();
That's all well and good, until we introduce class Vegetable. Vegetables have some of the same behavior as Animal, but not all. For example, both Animal and Vegetable might be able to grow, but clearly vegetables don't make noise and animals cannot be harvested.
In Smalltalk, we can write this:
|aFarmObject|
aFarmObject := Cow new.
aFarmObject grow.
aFarmObject makeNoise.
aFarmObject := Corn new.
aFarmObject grow.
aFarmObject harvest.
This works perfectly well in Smalltalk because it is duck-typed (if it walks like a duck, and quacks like a duck - it is a duck.) In this case, when a message is sent to an object, a lookup is performed on the receiver's method list, and if a matching method is found, it is called. If not, some kind of NoSuchMethodError exception is thrown - but it's all done at runtime.
But in Java, a statically typed language, what type can we assign to our variable? Corn needs to inherit from Vegetable, to support grow, but cannot inherit from Animal, because it does not make noise. Cow needs to inherit from Animal to support makeNoise, but cannot inherit from Vegetable because it should not implement harvest. It looks like we need multiple inheritance - the ability to inherit from more than one class. But that turns out to be a pretty difficult language feature because of all the edge cases that pop up (what happens when more than one parallel superclass implement the same method?, etc.)
Along come interfaces...
If we make Animal and Vegetable classes, with each implementing Growable, we can declare that our Cow is Animal and our Corn is Vegetable. We can also declare that both Animal and Vegetable are Growable. That lets us write this to grow everything:
List<Growable> list = new ArrayList<Growable>();
list.add(new Cow());
list.add(new Corn());
list.add(new Pig());
for(Growable g : list) {
g.grow();
}
And it lets us do this, to make animal noises:
List<Animal> list = new ArrayList<Animal>();
list.add(new Cow());
list.add(new Pig());
for(Animal a : list) {
a.makeNoise();
}
The advantage to the duck-typed language is that you get really nice polymorphism: all a class has to do to provide behavior is provide the method. As long as everyone plays nice, and only sends messages that match defined methods, all is good. The downside is that the kind of error below isn't caught until runtime:
|aFarmObject|
aFarmObject := Corn new.
aFarmObject makeNoise. // No compiler error - not checked until runtime.
Statically-typed languages provide much better "programming by contract," because they will catch the two kinds of error below at compile-time:
// Compiler error: Corn cannot be cast to Animal.
Animal farmObject = new Corn();
farmObject makeNoise();
--
// Compiler error: Animal doesn't have the harvest message.
Animal farmObject = new Cow();
farmObject.harvest();
So....to summarize:
Interface implementation allows you to specify what kinds of things objects can do (interaction) and Class inheritance lets you specify how things should be done (implementation).
Interfaces give us many of the benefits of "true" polymorphism, without sacrificing compiler type checking.
To format the date using the local date format use:
<%#((DateTime)Eval("ExpDate")).ToString("d")%>
How to Format an Eval Statement to Display a Date using Date Locale
You need to set the value of $title
before echoing it.
Also, you should really sanitize any data before using it in queries as this is a security risk
Quick work around for the same is
Copy C:\Program Files\Java\jdk1.6.0_14\lib\tools.jar to C:\Program Files\Java\jre6\lib\
This exception is coming because JAVA_HOME is being set as C:\Program Files\Java\jre6 and Ant is not able to find tools.jar in it.
Normally Python throws NameError
if the variable is not defined:
>>> d[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined
However, you've managed to stumble upon a name that already exists in Python.
Because dict
is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.
The type of dict
is a type
. All types are objects in Python. Thus you are actually trying to index into the type
object. This is why the error message says that the "'type' object is not subscriptable."
>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable
Note that you can blindly assign to the dict
name, but you really don't want to do that. It's just going to cause you problems later.
>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'
The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:
d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))
To put it in another way, can we replicate the appearance of these text views without using the android:textAppearance attribute?
Like biegleux already said:
If you want to use the small, medium or large value on any text in your Android app, you can just create a dimens.xml
file in your values
folder and define the text size there with the following 3 lines:
<dimen name="text_size_small">14sp</dimen>
<dimen name="text_size_medium">18sp</dimen>
<dimen name="text_size_large">22sp</dimen>
Here is an example for a TextView with large text from the dimens.xml
file:
<TextView
android:id="@+id/hello_world"
android:text="hello world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="@dimen/text_size_large"/>
for Microsoft SQL Server Management Studio 2012,2008.. First Copy your database file .mdf and log file .ldf & Paste in your sql server install file in Programs Files->Microsoft SQL Server->MSSQL10.SQLEXPRESS->MSSQL->DATA. Then open Microsoft Sql Server . Right Click on Databases -> Select Attach...option.
Create an alias for gcc with your favorite includes.
alias mygcc='gcc -I /whatever/'
First you convert VARCHAR to DATE and then back to CHAR. I do this almost every day and never found any better way.
select TO_CHAR(TO_DATE(DOJ,'MM/DD/YYYY'), 'MM/DD/YYYY') from EmpTable
UTF-8 is prepared for world domination, Latin1 isn't.
If you're trying to store non-Latin characters like Chinese, Japanese, Hebrew, Russian, etc using Latin1 encoding, then they will end up as mojibake. You may find the introductory text of this article useful (and even more if you know a bit Java).
Note that full 4-byte UTF-8 support was only introduced in MySQL 5.5. Before that version, it only goes up to 3 bytes per character, not 4 bytes per character. So, it supported only the BMP plane and not e.g. the Emoji plane. If you want full 4-byte UTF-8 support, upgrade MySQL to at least 5.5 or go for another RDBMS like PostgreSQL. In MySQL 5.5+ it's called utf8mb4
.
This answer aims to force an image pull in a situation where your node has already downloaded an image with the same name, therefore even though you push a new image to container registry, when you spin up some pods, your pod says "image already present".
For a case in Azure Container Registry (probably AWS and GCP also provides this):
You can look to your Azure Container Registry and by checking the manifest creation date you can identify what image is the most recent one.
Then, copy its digest hash (which has a format of sha256:xxx...xxx
).
You can scale down your current replica by running command below. Note that this will obviously stop your container and cause downtime.
kubectl scale --replicas=0 deployment <deployment-name> -n <namespace-name>
kubectl get deployments.apps <deployment-name> -o yaml > deployment.yaml
Then change the line with image field from <image-name>:<tag>
to <image-name>@sha256:xxx...xxx
, save the file.
Now you can scale up your replicas again. New image will be pulled with its unique digest.
Note: It is assumed that, imagePullPolicy: Always field is present in the container.
right click somewhere on the file or in project explorer and choose 'run as'->'java application'
firstly create a function:
$.fn.is_exists = function(){ return document.getElementById(selector) }
then
if($(selector).is_exists()){ ... }
The tabularx
package gives you
X
, all X
columns will grow to fill up the total width.For your example:
\usepackage{tabularx}
% ...
\begin{document}
% ...
\begin{tabularx}{\textwidth}{|X|X|X|}
\hline
Input & Output& Action return \\
\hline
\hline
DNF & simulation & jsp\\
\hline
\end{tabularx}
its even simpler than that. Using HTML you can just add this metatag to your page (first thing on the page):
<meta http-equiv="X-UA-Compatible" content="IE=7" />
If you wanted to do it using.net, you just have to send your http request with that meta information in the header. This would require a page refresh to work though.
Also, you can look at a similar question here: Compatibility Mode in IE8 using VBScript
I have just written a blog article that addresses exactly this, which you may find useful: http://seewah.blogspot.com/2009/10/circle-overlay-on-google-map.html
Basically, you need to create a GGroundOverlay with the correct GLatLngBounds. The tricky bit is in working out the southwest corner coordinate and the northeast corner coordinate of this imaginery square (the GLatLngBounds) bounding this circle, based on the desired radius. The math is quite complicated, but you can just refer to getDestLatLng function in the blog. The rest should be pretty straightforward.
Use jdbc:h2:mem:testdb as your path when logging into the H2 console.
Obviously if you have altered Spring Boot properties your datasource may be different, but it seems like you're struggling with how to find the default. That's all there is to it! You'll see your schema after logging in to H2.
Use Spring's "PropertyPlaceholderConfigurer" class
A simple example showing property file read dynamically as bean's property
<bean id="placeholderConfig"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>/WEB-INF/classes/config_properties/dev/database.properties</value>
</list>
</property>
</bean>
<bean id="devDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${dev.app.jdbc.driver}"/>
<property name="jdbcUrl" value="${dev.app.jdbc.url}"/>
<property name="user" value="${dev.app.jdbc.username}"/>
<property name="password" value="${dev.app.jdbc.password}"/>
<property name="acquireIncrement" value="3"/>
<property name="minPoolSize" value="5"/>
<property name="maxPoolSize" value="10"/>
<property name="maxStatementsPerConnection" value="11000"/>
<property name="numHelperThreads" value="8"/>
<property name="idleConnectionTestPeriod" value="300"/>
<property name="preferredTestQuery" value="SELECT 0"/>
</bean>
Property File
dev.app.jdbc.driver=com.mysql.jdbc.Driver
dev.app.jdbc.url=jdbc:mysql://localhost:3306/addvertisement
dev.app.jdbc.username=root
dev.app.jdbc.password=root
CSS
solution works without a glitch!
https://www.w3schools.com/code/tryit.asp?filename=GJ4PCJMVQ4LN https://www.w3schools.com/code/tryit.asp?filename=GJ4PPLCCEBRG
.col-info:hover>.popoverIcon {
visibility: visible;
}
}
.popoverIcon {
visibility: hidden;
}
_x000D_
<div *ngFor="let i of [1,2,3,4]">
<div class="col-info">
<span class=" popoverIcon ">Show {{i}}</span>
</div>
</div>
_x000D_
the declaration is generally the most 'useful', but that depends on how you want to use the class.
both is not valid.
As of Jquery 3.0 and above .bind has been deprecated and they prefer using .on instead. As @Blazemonger answered earlier that it may be removed and its for sure that it will be removed. For the older versions .bind would also call .on internally and there is no difference between them. Please also see the api for more detail.
Sub GetUniqueAndCount()
Dim d As Object, c As Range, k, tmp As String
Set d = CreateObject("scripting.dictionary")
For Each c In Selection
tmp = Trim(c.Value)
If Len(tmp) > 0 Then d(tmp) = d(tmp) + 1
Next c
For Each k In d.keys
Debug.Print k, d(k)
Next k
End Sub
NSString *str1 = @"Share Role Play Photo via Facebook, or Twitter for free coins per photo.";
NSString *str2 = @"Like Role Play on facebook for 50 free coins.";
NSString *str3 = @"Check out 'What's Hot' on other ways to receive free coins";
NSString *msg = [NSString stringWithFormat:@"%@\n%@\n%@", str1, str2, str3];
Try echo $'a\nb'
.
If you want to store it in a variable and then use it with the newlines intact, you will have to quote your usage correctly:
var=$'a\nb\nc'
echo "$var"
Or, to fix your example program literally:
var="a b c"
for i in $var; do
p="`echo -e "$p\\n$i"`"
done
echo "$p"
If you really want a general promiseWhen()
function for this and other purposes, then by all means do so, using Bergi's simplifications. However, because of the way promises work, passing callbacks in this way is generally unnecessary and forces you to jump through complex little hoops.
As far as I can tell you're trying :
.then()
chain via recursion.Defined thus, the problem is actually the one discussed under "The Collection Kerfuffle" in Promise Anti-patterns, which offers two simple solutions :
Array.prototype.map()
Array.prototype.reduce()
.The parallel approach will (straightforwardly) give the issue that you are trying to avoid - that the order of the responses is uncertain. The serial approach will build the required .then()
chain - flat - no recursion.
function fetchUserDetails(arr) {
return arr.reduce(function(promise, email) {
return promise.then(function() {
return db.getUser(email).done(function(res) {
logger.log(res);
});
});
}, Promise.resolve());
}
Call as follows :
//Compose here, by whatever means, an array of email addresses.
var arrayOfEmailAddys = [...];
fetchUserDetails(arrayOfEmailAddys).then(function() {
console.log('all done');
});
As you can see, there's no need for the ugly outer var count
or it's associated condition
function. The limit (of 10 in the question) is determined entirely by the length of the array arrayOfEmailAddys
.
Help -> About Eclipse -> Installation Details -> tab Configuration
Look for -arch
, and below it you'll see either x86_64
(meaning 64bit) or x86
(meaning 32bit).
This will show an dialog error box if there is not network connectivity
ConnectivityManager connMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
// fetch data
} else {
new AlertDialog.Builder(this)
.setTitle("Connection Failure")
.setMessage("Please Connect to the Internet")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
The SQL definition of a table is in actuality the definition of one potential row of the table, not the collection. Therefore, the name used in that definition must designate the type of the row, not the name of the collection. People who prefer plural because it reads well in their English statements need to start thinking more logically and look at all of the logic and programming code that is involved with actually using a table. There are several very good reasons mentioned in these comments to use singular table names. These include very good reasons NOT to use plural table names. "Reading well" should not be any reason at all, especially since some may read the idea differently.
test[,sort(names(test))]
sort on names of columns can work easily.
Are you on Windows? The underlying socket implementation on Windows seems not to support the SO_TIMEOUT option very well. See also this answer: setSoTimeout on a client socket doesn't affect the socket
Objects are eligable for garbage collection once they go out of scope become unreachable (thanks ben!). The memory won't be freed unless the garbage collector believes you are running out of memory.
For managed resources, the garbage collector will know when this is, and you don't need to do anything.
For unmanaged resources (such as connections to databases or opened files) the garbage collector has no way of knowing how much memory they are consuming, and that is why you need to free them manually (using dispose, or much better still the using block)
If objects are not being freed, either you have plenty of memory left and there is no need, or you are maintaining a reference to them in your application, and therefore the garbage collector will not free them (in case you actually use this reference you maintained)
Difference between "return" and "print" can also be found in the following example:
RETURN:
def bigger(a, b):
if a > b:
return a
elif a <b:
return b
else:
return a
The above code will give correct results for all inputs.
PRINT:
def bigger(a, b):
if a > b:
print a
elif a <b:
print b
else:
print a
NOTE: This will fail for many test cases.
ERROR:
----
FAILURE
: Test case input: 3, 8.
Expected result: 8
FAILURE
: Test case input: 4, 3.
Expected result: 4
FAILURE
: Test case input: 3, 3.
Expected result: 3
You passed 0 out of 3 test cases
You can wrap the disabled button and put the tooltip on the wrapper:
<div class="tooltip-wrapper" data-title="Dieser Link führt zu Google">
<button class="btn btn-default" disabled>button disabled</button>
</div>
If the wrapper has display:inline
then the tooltip doesn't seem to work. Using display:block
and display:inline-block
seem to work fine. It also appears to work fine with a floated wrapper.
UPDATE Here's an updated JSFiddle that works with the latest Bootstrap (3.3.6). Thanks to @JohnLehmann for suggesting pointer-events: none;
for the disabled button.
Take a look at my answer here.
Answer to comment:
The FFT actually calculates the cross-correlation of the input signal with sine and cosine functions (basis functions) at a range of equally spaced frequencies. For a given FFT output, there is a corresponding frequency (F) as given by the answer I posted. The real part of the output sample is the cross-correlation of the input signal with cos(2*pi*F*t)
and the imaginary part is the cross-correlation of the input signal with sin(2*pi*F*t)
. The reason the input signal is correlated with sin
and cos
functions is to account for phase differences between the input signal and basis functions.
By taking the magnitude of the complex FFT output, you get a measure of how well the input signal correlates with sinusoids at a set of frequencies regardless of the input signal phase. If you are just analyzing frequency content of a signal, you will almost always take the magnitude or magnitude squared of the complex output of the FFT.
If you are working with maven project, then add following dependency to your pom.xml
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
none of the answers worked but this
\newcommand{\bcenter}{\begin{center}}
\newcommand{\ecenter}{\end{center}}
but then the following problem is that it works for only one figure and then will not for any other figures.
I just started learning R I knew it was going to be difficult but what's worst is that there is little to no info that I can refer to.
'entityManager.unwrap(Session.class)' is used to get session from EntityManager.
@Repository
@Transactional
public class EmployeeRepository {
@PersistenceContext
private EntityManager entityManager;
public Session getSession() {
Session session = entityManager.unwrap(Session.class);
return session;
}
......
......
}
Demo Application link.
No, you can't change scrollbars placement without any additional issues.
You can change text-direction to right-to-left ( rtl ), but it also change text position inside block.
This code can helps you, but I not sure it works in all browsers and OS.
<element style="direction: rtl; text-align: left;" />
You want this?
html,_x000D_
body {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
.container {_x000D_
display: grid;_x000D_
grid-template-columns: 1fr 1fr;_x000D_
grid-template-rows: 100vh;_x000D_
grid-gap: 0px 0px;_x000D_
}_x000D_
_x000D_
.left_bg {_x000D_
display: subgrid;_x000D_
background-color: #3498db;_x000D_
grid-column: 1 / 1;_x000D_
grid-row: 1 / 1;_x000D_
z-index: 0;_x000D_
}_x000D_
_x000D_
.right_bg {_x000D_
display: subgrid;_x000D_
background-color: #ecf0f1;_x000D_
grid-column: 2 / 2;_x000D_
grid_row: 1 / 1;_x000D_
z-index: 0;_x000D_
}_x000D_
_x000D_
.text {_x000D_
font-family: Raleway;_x000D_
font-size: large;_x000D_
text-align: center;_x000D_
}
_x000D_
<div class="container">_x000D_
<!--everything on the page-->_x000D_
_x000D_
<div class="left_bg">_x000D_
<!--left background color of the page-->_x000D_
<div class="text">_x000D_
<!--left side text content-->_x000D_
<p>Review my stuff</p>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="right_bg">_x000D_
<!--right background color of the page-->_x000D_
<div class="text">_x000D_
<!--right side text content-->_x000D_
<p>Hire me!</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Look at the types of those properties:
In [1]: import datetime
In [2]: d = datetime.date.today()
In [3]: type(d.month)
Out[3]: <type 'int'>
In [4]: type(d.day)
Out[4]: <type 'int'>
Both are integers. So there is no automatic way to do what you want. So in the narrow sense, the answer to your question is no.
If you want leading zeroes, you'll have to format them one way or another. For that you have several options:
In [5]: '{:02d}'.format(d.month)
Out[5]: '03'
In [6]: '%02d' % d.month
Out[6]: '03'
In [7]: d.strftime('%m')
Out[7]: '03'
In [8]: f'{d.month:02d}'
Out[8]: '03'
If you want to give a variable that contains the minutes.
Then I think this is a great way to achieve this.
$minutes = 10;
$maxAge = new DateTime('2011-11-17 05:05');
$maxAge->modify("+{$minutes} minutes");
If you are using HTML5, then using <br>
is the right way to go :)
Well, in java, you can also create a parameterized enum. Say you want to create a className enum, in which you need to store classCode as well as className, you can do that like this:
public enum ClassEnum {
ONE(1, "One"),
TWO(2, "Two"),
THREE(3, "Three"),
FOUR(4, "Four"),
FIVE(5, "Five")
;
private int code;
private String name;
private ClassEnum(int code, String name) {
this.code = code;
this.name = name;
}
public int getCode() {
return code;
}
public String getName() {
return name;
}
}
Firstly, I don't think spaces for an id is valid.
So i'd change the id to not include spaces.
<label year="2010" month="6" id="currentMonth"> June 2010</label>
then the jquery code is simple (keep in mind, its better to fetch the jquery object once and use over and over agian)
var label = $('#currentMonth');
var month = label.attr('month');
var year = label.attr('year');
var text = label.text();
The LocalLinks extension from the most popular answer didn't work for me (given, I was trying to use file:// to open a directory in windows explorer, not a file), so I looked into another workaround. I found that this "Open in IE" extension is a good workaround: https://chrome.google.com/webstore/detail/open-in-ie/iajffemldkkhodaedkcpnbpfabiglmdi
This isn't an ideal fix, as instead of clicking the link, users will have to right-click and choose Open in IE, but it at least makes the link functional.
One thing to note though, in IE10 (and IE9 after a certain update point) you will have to add the site to your Trusted Sites (Internet Options > Security > Trusted sites). If the site is not in trusted sites, the file:// link does not work in IE either.
You can run the DOS ping.exe command from javaScript using the folowing:
function ping(ip)
{
var input = "";
var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("c:/windows/system32/ping.exe " + ip);
while (!oExec.StdOut.AtEndOfStream)
{
input += oExec.StdOut.ReadLine() + "<br />";
}
return input;
}
Is this what was asked for, or am i missing something?
You can use the function RESHAPE:
B = reshape(A.',1,[]);
As of May 2017, multiple FROM
s can be used in a single Dockerfile.
See "Builder pattern vs. Multi-stage builds in Docker" (by Alex Ellis) and PR 31257 by Tõnis Tiigi.
The general syntax involves adding
FROM
additional times within your Dockerfile - whichever is the lastFROM
statement is the final base image. To copy artifacts and outputs from intermediate images useCOPY --from=<base_image_number>
.
FROM golang:1.7.3 as builder
WORKDIR /go/src/github.com/alexellis/href-counter/
RUN go get -d -v golang.org/x/net/html
COPY app.go .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .
FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /go/src/github.com/alexellis/href-counter/app .
CMD ["./app"]
The result would be two images, one for building, one with just the resulting app (much, much smaller)
REPOSITORY TAG IMAGE ID CREATED SIZE
multi latest bcbbf69a9b59 6 minutes ago 10.3MB
golang 1.7.3 ef15416724f6 4 months ago 672MB
what is a base image?
A set of files, plus EXPOSE
'd ports, ENTRYPOINT
and CMD
.
You can add files and build a new image based on that base image, with a new Dockerfile
starting with a FROM
directive: the image mentioned after FROM
is "the base image" for your new image.
does it mean that if I declare
neo4j/neo4j
in aFROM
directive, that when my image is run the neo database will automatically run and be available within the container on port 7474?
Only if you don't overwrite CMD
and ENTRYPOINT
.
But the image in itself is enough: you would use a FROM neo4j/neo4j
if you had to add files related to neo4j
for your particular usage of neo4j
.
You are using wrong JSON. In this case you should use JSON that looks like this:
["orange", "apple"]
If you have to accept JSON in that form :
{"fruits":["apple","orange"]}
You'll have to create wrapper object:
public class FruitWrapper{
List<String> fruits;
//getter
//setter
}
and then your controller method should look like this:
@RequestMapping(value = "/saveFruits", method = RequestMethod.POST,
consumes = "application/json")
@ResponseBody
public ResultObject saveFruits(@RequestBody FruitWrapper fruits){
...
}
This worked for me:
location / {
try_files $uri $uri/ /base.html;
}
The files managed by git are shown by git ls-files
. Check out its manual page.
Inline media queries are possible by using something like Breakpoint for Sass
This blog post does a good job explaining how inline media queries are more manageable than separate blocks: There Is No Breakpoint
Related to inline media queries is the idea of "element queries", a few interesting reads are:
Your HTML code:
<div>Stack Overflow is the BEST !!!</div>
CSS:
div {
width: 100px;
white-space:nowrap;
overflow:hidden;
text-overflow:ellipsis;
}
Now the result should be:
Stack Overf...
You can do this without needing external libraries also by doing the following:
class Program
{
static void Main(string[] args)
{
Bootstrapper bs = new Bootstrapper();
var getListTask = bs.GetList(); // returns the Task<List<TvChannel>>
Task.WaitAll(getListTask); // block while the task completes
var list = getListTask.Result;
}
}
Actually, your question is how to write a Higher Order Component (HOC). The main goal of using HOC is preventing copy-pasting. You can write your HOC as a purely functional component or as a class here is an example:
class Child extends Component {
render() {
return (
<div>
Child
</div>
);
}
}
If you want to write your parent component as a class-based component:
class Parent extends Component {
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
If you want to write your parent as a functional component:
const Parent=props=>{
return(
<div>
{props.children}
</div>
)
}
I had the same problem, but finally discovered that it was an issue with the way I was invoking the script from an ASP web user control. I was using ClientScript.RegisterStartupScript()
, but forgot to give the script a unique key (the second argument). With both scripts being assigned the same key, only the first box was actually being converted into a datepicker. So I decided to append the textbox's ID to the key to make it unique:
Page.ClientScript.RegisterStartupScript(this.GetType(), "DPSetup" + DPTextbox.ClientID, dpScript);
You can use sum
to sum the elements of a list, however if your list is coming from raw_input
, you probably want to convert the items to int
or float
first:
l = raw_input().split(' ')
sum(map(int, l))
Get is invoked when the property appears on the right-hand side (RHS) Set is invoked when the property appears on the left-hand side (LHS) of '=' symbol
For an auto-implemented property, the backing field works behind the scene and not visible.
Example:
public string Log { get; set; }
Whereas for a non auto-implemented property the backing field is upfront, visible as a private scoped variable.
Example:
private string log;
public string Log
{
get => log;
set => log = value;
}
Also, it is worth noted here is the 'getter' and 'setter' can use the different 'backing field'
The reason for using dictionaries in the first place is performance. Although it is correct that you can use named vectors and lists for the task the issue is that they are becoming quite slow and memory hungry with more data.
Yet what many people don't know is that R has indeed an inbuilt dictionary data structure: environments with the option hash = TRUE
See the following example for how to make it work:
# vectorize assign, get and exists for convenience
assign_hash <- Vectorize(assign, vectorize.args = c("x", "value"))
get_hash <- Vectorize(get, vectorize.args = "x")
exists_hash <- Vectorize(exists, vectorize.args = "x")
# keys and values
key<- c("tic", "tac", "toe")
value <- c(1, 22, 333)
# initialize hash
hash = new.env(hash = TRUE, parent = emptyenv(), size = 100L)
# assign values to keys
assign_hash(key, value, hash)
## tic tac toe
## 1 22 333
# get values for keys
get_hash(c("toe", "tic"), hash)
## toe tic
## 333 1
# alternatively:
mget(c("toe", "tic"), hash)
## $toe
## [1] 333
##
## $tic
## [1] 1
# show all keys
ls(hash)
## [1] "tac" "tic" "toe"
# show all keys with values
get_hash(ls(hash), hash)
## tac tic toe
## 22 1 333
# remove key-value pairs
rm(list = c("toe", "tic"), envir = hash)
get_hash(ls(hash), hash)
## tac
## 22
# check if keys are in hash
exists_hash(c("tac", "nothere"), hash)
## tac nothere
## TRUE FALSE
# for single keys this is also possible:
# show value for single key
hash[["tac"]]
## [1] 22
# create new key-value pair
hash[["test"]] <- 1234
get_hash(ls(hash), hash)
## tac test
## 22 1234
# update single value
hash[["test"]] <- 54321
get_hash(ls(hash), hash)
## tac test
## 22 54321
Edit: On the basis of this answer I wrote a blog post with some more context: http://blog.ephorie.de/hash-me-if-you-can
Here's how I get there using Version 3.0.6 on Windows
CSS has different pseudo selector by which you can achieve such effect. In your case you can use
:active : if you want background color only when the button is clicked and don't want to persist.
:focus: if you want background color untill the focus is on the button.
button:active{
background:olive;
}
and
button:focus{
background:olive;
}
P.S.: Please don't give the number in Id
attribute of html elements.
A quick recap of the 2 approaches with speed comparison being the important part.
Determining the caller at compile-time
static void Log(object message,
[CallerMemberName] string memberName = "",
[CallerFilePath] string fileName = "",
[CallerLineNumber] int lineNumber = 0)
{
// we'll just use a simple Console write for now
Console.WriteLine("{0}({1}):{2} - {3}", fileName, lineNumber, memberName, message);
}
Determining the caller using the stack
static void Log(object message)
{
// frame 1, true for source info
StackFrame frame = new StackFrame(1, true);
var method = frame.GetMethod();
var fileName = frame.GetFileName();
var lineNumber = frame.GetFileLineNumber();
// we'll just use a simple Console write for now
Console.WriteLine("{0}({1}):{2} - {3}", fileName, lineNumber, method.Name, message);
}
Comparison of the 2 approaches
Time for 1,000,000 iterations with Attributes: 196 ms
Time for 1,000,000 iterations with StackTrace: 5096 ms
So you see, using the attributes is much, much faster! Nearly 25x faster in fact.
I think this question is a bit misleading since, toString() in Java isn't just a way to cast something to a String. That is what casting via (string) or String.valueOf() does, and it works as well in PHP.
// Java
String myText = (string) myVar;
// PHP
$myText = (string) $myVar;
Note that this can be problematic as Java is type-safe (see here for more details).
But as I said, this is casting and therefore not the equivalent of Java's toString().
toString in Java doesn't just cast an object to a String. It instead will give you the String representation. And that's what __toString() in PHP does.
// Java
class SomeClass{
public String toString(){
return "some string representation";
}
}
// PHP
class SomeClass{
public function __toString()
{
return "some string representation";
}
}
And from the other side:
// Java
new SomeClass().toString(); // "Some string representation"
// PHP
strval(new SomeClass); // "Some string representation"
What do I mean by "giving the String representation"? Imagine a class for a library with millions of books.
These are both valid approaches but with very different goals, neither is a perfect solution for every case and you have to chose wisely which fits better for your needs.
Sure, there are even more options:
$no = 421337 // A number in PHP
$str = "$no"; // In PHP, stuff inside "" is calculated and variables are replaced
$str = print_r($no, true); // Same as String.format();
$str = settype($no, 'string'); // Sets $no to the String Type
$str = strval($no); // Get the string value of $no
$str = $no . ''; // As you said concatenate an empty string works too
All of these methods will return a String, some of them using __toString internally and some others will fail on Objects. Take a look at the PHP documentation for more details.
Here is the syntax to create a trigger:
CREATE TRIGGER trigger_name
ON { table | view }
[ WITH ENCRYPTION ]
{
{ { FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }
[ WITH APPEND ]
[ NOT FOR REPLICATION ]
AS
[ { IF UPDATE ( column )
[ { AND | OR } UPDATE ( column ) ]
[ ...n ]
| IF ( COLUMNS_UPDATED ( ) { bitwise_operator } updated_bitmask )
{ comparison_operator } column_bitmask [ ...n ]
} ]
sql_statement [ ...n ]
}
}
If you want to use On Update you only can do it with the IF UPDATE ( column )
section. That's not possible to do what you are asking.
If you have multiple projects in your solution and one of your projects fails to build because of this error then ensure you have installed the WebApi Core nuget package in that project. Simply adding a reference to the System.Web.Http does not help, you need to install the correct nuget package into that project.
I had multiple projects in my solution and WebApi Core was already installed in another project. I referenced the System.Web.Http assembly by right-clicking and ticking the assembly from the list and it did not work on Azure, though locally it would build okay. I had to remove the manual reference and add the WebApi Core nuget package to each project that needed the assembly reference.
function urlExists($url=NULL)
{
if($url == NULL) return false;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($httpcode>=200 && $httpcode<300){
return true;
} else {
return false;
}
}
This was grabbed from this post on how to check if a URL exists. Because Twitter should provide an error message above 300 when it is in maintenance, or a 404, this should work perfectly.
Try umount -f /mnt/share. Works OK with NFS, never tried with cifs.
Also, take a look at autofs, it will mount the share only when accessed, and will unmount it afterworlds.
There is a good tutorial at www.howtoforge.net
I did some development with Mifare Classic (ISO 14443A) cards about 7-8 years ago. You can read and write to all sectors of the card, IIRC the only data you can't change is the serial number. Back then we used a proprietary library from Philips Semiconductors. The command interface to the card was quite alike the ISO 7816-4 (used with standard Smart Cards).
I'd recomment that you look at the OpenPCD platform if you are into development.
This is also of interest regarding the cryptographic functions in some RFID cards.
Create file if not exist. If file exits, clear its content:
/**
* Create file if not exist.
*
* @param path For example: "D:\foo.xml"
*/
public static void createFile(String path) {
try {
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
} else {
FileOutputStream writer = new FileOutputStream(path);
writer.write(("").getBytes());
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Try this:
@echo off
setlocal
cd /d %~dp0
Call :UnZipFile "C:\Temp\" "c:\path\to\batch.zip"
exit /b
:UnZipFile <ExtractTo> <newzipfile>
set vbs="%temp%\_.vbs"
if exist %vbs% del /f /q %vbs%
>%vbs% echo Set fso = CreateObject("Scripting.FileSystemObject")
>>%vbs% echo If NOT fso.FolderExists(%1) Then
>>%vbs% echo fso.CreateFolder(%1)
>>%vbs% echo End If
>>%vbs% echo set objShell = CreateObject("Shell.Application")
>>%vbs% echo set FilesInZip=objShell.NameSpace(%2).items
>>%vbs% echo objShell.NameSpace(%1).CopyHere(FilesInZip)
>>%vbs% echo Set fso = Nothing
>>%vbs% echo Set objShell = Nothing
cscript //nologo %vbs%
if exist %vbs% del /f /q %vbs%
Revision
To have it perform the unzip on each zip file creating a folder for each use:
@echo off
setlocal
cd /d %~dp0
for %%a in (*.zip) do (
Call :UnZipFile "C:\Temp\%%~na\" "c:\path\to\%%~nxa"
)
exit /b
If you don't want it to create a folder for each zip, change
Call :UnZipFile "C:\Temp\%%~na\" "c:\path\to\%%~nxa"
to
Call :UnZipFile "C:\Temp\" "c:\path\to\%%~nxa"
If you only need to show time value in a datagrid or label similar, best way is convert directly time in datetime datatype.
SELECT CONVERT(datetime,myTimeField) as myTimeField FROM Table1
You don't really have that many options if the lines are of different length... you sadly need to process the line ending characters to know when you've progressed to the next line.
You can, however, dramatically speed this up AND reduce memory usage by changing the last parameter to "open" to something not 0.
0 means the file reading operation is unbuffered, which is very slow and disk intensive. 1 means the file is line buffered, which would be an improvement. Anything above 1 (say 8k.. ie: 8096, or higher) reads chunks of the file into memory. You still access it through for line in open(etc):
, but python only goes a bit at a time, discarding each buffered chunk after its processed.
I'm using just:
request.ContentType = "application/json; charset=utf-8"
There are some cases, when textbox will not handle enter key. I think it may be when you have accept button set on form. In that case, instead of KeyDown
event you should use textbox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
If you want to change inputs in an iframe then submit the form from that iframe, do this
...
var el = document.getElementById('targetFrame');
var doc, frame_win = getIframeWindow(el); // getIframeWindow is defined below
if (frame_win) {
doc = (window.contentDocument || window.document);
}
if (doc) {
doc.forms[0].someInputName.value = someValue;
...
doc.forms[0].submit();
}
...
Normally, you can only do this if the page in the iframe is from the same origin, but you can start Chrome in a debug mode to disregard the same origin policy and test this on any page.
function getIframeWindow(iframe_object) {
var doc;
if (iframe_object.contentWindow) {
return iframe_object.contentWindow;
}
if (iframe_object.window) {
return iframe_object.window;
}
if (!doc && iframe_object.contentDocument) {
doc = iframe_object.contentDocument;
}
if (!doc && iframe_object.document) {
doc = iframe_object.document;
}
if (doc && doc.defaultView) {
return doc.defaultView;
}
if (doc && doc.parentWindow) {
return doc.parentWindow;
}
return undefined;
}
Minimal runnable C POSIX reproduction example
I recommend understanding the underlying API to better see what is going on.
sleep.c
#define _XOPEN_SOURCE 700
#include <unistd.h>
int main(void) {
sleep(10000);
}
busy.c
#define _XOPEN_SOURCE 700
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(void) {
int ret = open("sleep.out", O_WRONLY|O_TRUNC);
assert(errno == ETXTBSY);
perror("");
assert(ret == -1);
}
Compile and run:
gcc -std=c99 -o sleep.out ./sleep.c
gcc -std=c99 -o busy.out ./busy.c
./sleep.out &
./busy.out
busy.out
passes the asserts, and perror
outputs:
Text file busy
so we deduce that the message is hardcoded in glibc itself.
Alternatively:
echo asdf > sleep.out
makes Bash output:
-bash: sleep.out: Text file busy
For a more complex application, you can also observe it with strace
:
strace ./busy.out
which contains:
openat(AT_FDCWD, "sleep.out", O_WRONLY) = -1 ETXTBSY (Text file busy)
Tested on Ubuntu 18.04, Linux kernel 4.15.0.
The error does not happen if you unlink
first
notbusy.c
#define _XOPEN_SOURCE 700
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main(void) {
assert(unlink("sleep.out") == 0);
assert(open("sleep.out", O_WRONLY|O_CREAT) != -1);
}
Then compile and run analogously to the above, and those asserts pass.
This explains why it works for certain programs but not others. E.g. if you do:
gcc -std=c99 -o sleep.out ./sleep.c
./sleep.out &
gcc -std=c99 -o sleep.out ./sleep.c
that does not generate an error, even though the second gcc
call is writing to sleep.out
.
A quick strace
shows that GCC first unlinks before writing:
strace -f gcc -std=c99 -o sleep.out ./sleep.c |& grep sleep.out
contains:
[pid 3992] unlink("sleep.out") = 0
[pid 3992] openat(AT_FDCWD, "sleep.out", O_RDWR|O_CREAT|O_TRUNC, 0666) = 3
The reason it does not fail is that when you unlink
and re-write the file, it creates a new inode, and keeps a temporary dangling inode for the running executable file.
But if you just write
without unlink
, then it tries to write to the same protected inode as the running executable.
POSIX 7 open()
http://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html
[ETXTBSY]
The file is a pure procedure (shared text) file that is being executed and oflag is O_WRONLY or O_RDWR.
man 2 open
ETXTBSY
pathname refers to an executable image which is currently being executed and write access was requested.
glibc source
A quick grep on 2.30 gives:
sysdeps/gnu/errlist.c:299: [ERR_REMAP (ETXTBSY)] = N_("Text file busy"),
sysdeps/mach/hurd/bits/errno.h:62: ETXTBSY = 0x4000001a, /* Text file busy */
and a manual hit in manual/errno.texi
:
@deftypevr Macro int ETXTBSY
@standards{BSD, errno.h}
@errno{ETXTBSY, 26, Text file busy}
An attempt to execute a file that is currently open for writing, or
write to a file that is currently being executed. Often using a
debugger to run a program is considered having it open for writing and
will cause this error. (The name stands for ``text file busy''.) This
is not an error on @gnuhurdsystems{}; the text is copied as necessary.
@end deftypevr
Dockerfile and Docker Compose are two different concepts in Dockerland. When we talk about Docker, the first things that come to mind are orchestration, OS level virtualization, images, containers, etc.. I will try to explain each as follows:
Image: An image is an immutable, shareable file that is stored in a Docker-trusted registry. A Docker image is built up from a series of read-only layers. Each layer represents an instruction that is being given in the image’s Dockerfile. An image holds all the required binaries to run.
Container: An instance of an image is called a container. A container is just an executable image binary that is to be run by the host OS. A running image is a container.
Dockerfile:
A Dockerfile is a text document that contains all of the commands / build instructions, a user could call on the command line to assemble an image. This will be saved as a Dockerfile
. (Note the lowercase 'f'.)
Docker-Compose:
Compose is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application’s services (containers). Then, with a single command, you create and start all the services from your configuration.
The Compose file would be saved as docker-compose.yml
.
A corresponding cross for ✓ ✓
would be ✗ ✗
I think (Dingbats).
var args = [ 'p0', 'p1', 'p2' ];
function call_me (param0, param1, param2 ) {
// ...
}
// Calling the function using the array with apply()
call_me.apply(this, args);
And here a link to the original post that I personally liked for its readability
If you have OS(64bit) and SSMS(64bit) and already install the AccessDatabaseEngine(64bit) and you still received an error, try this following solutions:
1: direct opening the sql server import and export wizard.
if you able to connect using direct sql server import and export wizard, then importing from SSMS is the issue, it's like activating 32bit if you import data from SSMS.
Instead of installing AccessDatabaseEngine(64bit) , try to use the AccessDatabaseEngine(32bit) , upon installation, windows will stop you for continuing the installation if you already have another app installed , if so , then use the following steps. This is from the MICROSOFT. The Quiet Installation.
If Office 365 is already installed, side by side detection will prevent the installation from proceeding. Instead perform a /quiet install of these components from command line. To do so, download the desired AccessDatabaseEngine.exe or AccessDatabaeEngine_x64.exe to your PC, open an administrative command prompt, and provide the installation path and switch Ex: C:\Files\AccessDatabaseEngine.exe /quiet
or check in the Addition Information content from the link below,
https://www.microsoft.com/en-us/download/details.aspx?id=54920
Well that's pretty easy actually with GCD. A typical workflow would be something like this:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
dispatch_async(queue, ^{
// Perform async operation
// Call your method/function here
// Example:
// NSString *result = [anObject calculateSomething];
dispatch_sync(dispatch_get_main_queue(), ^{
// Update UI
// Example:
// self.myLabel.text = result;
});
});
For more on GCD you can take a look into Apple's documentation here
You can use a String[]
instead of an ArrayList<String>
:
Hope it helps!
private String[] getStringArray(JSONArray jsonArray) throws JSONException {
if (jsonArray != null) {
String[] stringsArray = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
stringsArray[i] = jsonArray.getString(i);
}
return stringsArray;
} else
return null;
}
mylist = ['a', 'ab', 'abc']
assert 'ab' in mylist
Could it be more useful for you to use the length of the list len(n)
to inform your decision rather than checking n[i]
for each possible length?
in your baseadapter class constructor try to initialize LayoutInflater, normally i preferred this way,
public ClassBaseAdapter(Context context,ArrayList<Integer> listLoanAmount) {
this.context = context;
this.listLoanAmount = listLoanAmount;
this.layoutInflater = LayoutInflater.from(context);
}
at the top of the class create LayoutInflater variable, hope this will help you
var sVal = '234';
var iNum = parseInt(sVal); //Output will be 234.
http://www.jquerybyexample.net/2013/02/jquery-convert-string-to-integer.html
Old topic, but how about:
public static int? ParseToNullableInt(this string value)
{
return String.IsNullOrEmpty(value) ? null : (int.Parse(value) as int?);
}
I like this better as the requriement where to parse null, the TryParse version would not throw an error on e.g. ToNullableInt32(XXX). That may introduce unwanted silent errors.
Starting in Python 2.6, there is an alternative: the str.format()
method. Here are some examples using the existing string format operator (%
):
>>> "Name: %s, age: %d" % ('John', 35)
'Name: John, age: 35'
>>> i = 45
>>> 'dec: %d/oct: %#o/hex: %#X' % (i, i, i)
'dec: 45/oct: 055/hex: 0X2D'
>>> "MM/DD/YY = %02d/%02d/%02d" % (12, 7, 41)
'MM/DD/YY = 12/07/41'
>>> 'Total with tax: $%.2f' % (13.00 * 1.0825)
'Total with tax: $14.07'
>>> d = {'web': 'user', 'page': 42}
>>> 'http://xxx.yyy.zzz/%(web)s/%(page)d.html' % d
'http://xxx.yyy.zzz/user/42.html'
Here are the equivalent snippets but using str.format()
:
>>> "Name: {0}, age: {1}".format('John', 35)
'Name: John, age: 35'
>>> i = 45
>>> 'dec: {0}/oct: {0:#o}/hex: {0:#X}'.format(i)
'dec: 45/oct: 0o55/hex: 0X2D'
>>> "MM/DD/YY = {0:02d}/{1:02d}/{2:02d}".format(12, 7, 41)
'MM/DD/YY = 12/07/41'
>>> 'Total with tax: ${0:.2f}'.format(13.00 * 1.0825)
'Total with tax: $14.07'
>>> d = {'web': 'user', 'page': 42}
>>> 'http://xxx.yyy.zzz/{web}/{page}.html'.format(**d)
'http://xxx.yyy.zzz/user/42.html'
Like Python 2.6+, all Python 3 releases (so far) understand how to do both. I shamelessly ripped this stuff straight out of my hardcore Python intro book and the slides for the Intro+Intermediate Python courses I offer from time-to-time. :-)
Aug 2018 UPDATE: Of course, now that we have the f-string feature in 3.6, we need the equivalent examples of that, yes another alternative:
>>> name, age = 'John', 35
>>> f'Name: {name}, age: {age}'
'Name: John, age: 35'
>>> i = 45
>>> f'dec: {i}/oct: {i:#o}/hex: {i:#X}'
'dec: 45/oct: 0o55/hex: 0X2D'
>>> m, d, y = 12, 7, 41
>>> f"MM/DD/YY = {m:02d}/{d:02d}/{y:02d}"
'MM/DD/YY = 12/07/41'
>>> f'Total with tax: ${13.00 * 1.0825:.2f}'
'Total with tax: $14.07'
>>> d = {'web': 'user', 'page': 42}
>>> f"http://xxx.yyy.zzz/{d['web']}/{d['page']}.html"
'http://xxx.yyy.zzz/user/42.html'
I've got an example working.
Here's how my doc looks:
<html>
<head>
<link rel="stylesheet" href="css/main.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular-resource.min.js"></script>
<script src="js/app.js"></script>
<script src="controllers/ctrls.js"></script>
</head>
<body ng-app="app">
<div id="contnr">
<ng-view></ng-view>
</div>
</body>
</html>
Here's what my partial looks like:
<div id="welcome" ng-controller="Index">
<b>Welcome! Please Login!</b>
<form ng-submit="auth()">
<input class="input login username" type="text" placeholder="username" /><br>
<input class="input login password" type="password" placeholder="password" /><br>
<input class="input login submit" type="submit" placeholder="login!" />
</form>
</div>
Here's what my Ctrl looks like:
app.controller('Index', function($scope, $routeParams, $location){
$scope.auth = function(){
$location.url('/map');
};
});
app is my module:
var app = angular.module('app', ['ngResource']).config(function($routeProvider)...
Hope this is helpful!
The options object can be added to the chart when the new Chart object is created.
var chart1 = new Chart(canvas, {
type: "pie",
data: data,
options: {
legend: {
display: false
},
tooltips: {
enabled: false
}
}
});
Here is a STL-like class
File "csvfile.h"
#pragma once
#include <iostream>
#include <fstream>
class csvfile;
inline static csvfile& endrow(csvfile& file);
inline static csvfile& flush(csvfile& file);
class csvfile
{
std::ofstream fs_;
const std::string separator_;
public:
csvfile(const std::string filename, const std::string separator = ";")
: fs_()
, separator_(separator)
{
fs_.exceptions(std::ios::failbit | std::ios::badbit);
fs_.open(filename);
}
~csvfile()
{
flush();
fs_.close();
}
void flush()
{
fs_.flush();
}
void endrow()
{
fs_ << std::endl;
}
csvfile& operator << ( csvfile& (* val)(csvfile&))
{
return val(*this);
}
csvfile& operator << (const char * val)
{
fs_ << '"' << val << '"' << separator_;
return *this;
}
csvfile& operator << (const std::string & val)
{
fs_ << '"' << val << '"' << separator_;
return *this;
}
template<typename T>
csvfile& operator << (const T& val)
{
fs_ << val << separator_;
return *this;
}
};
inline static csvfile& endrow(csvfile& file)
{
file.endrow();
return file;
}
inline static csvfile& flush(csvfile& file)
{
file.flush();
return file;
}
File "main.cpp"
#include "csvfile.h"
int main()
{
try
{
csvfile csv("MyTable.csv"); // throws exceptions!
// Header
csv << "X" << "VALUE" << endrow;
// Data
csv << 1 << "String value" << endrow;
csv << 2 << 123 << endrow;
csv << 3 << 1.f << endrow;
csv << 4 << 1.2 << endrow;
}
catch (const std::exception& ex)
{
std::cout << "Exception was thrown: " << e.what() << std::endl;
}
return 0;
}
Latest version here
Convert digits to word in French language using JavaScript and html - original French words
<html>
<head>
<title>Number to word</title>
<script>
function toWords() {
var s = document.getElementById('value').value;
var th = ['','mille','million', 'milliard','billion'];
var dg = ['zéro','un','deux','trois','quatre', 'cinq','six','sept','huit','neuf'];
var tn =
['dix','onze','douze','treize', 'quatorze','quinze','seize', 'dix-sept','dix-huit','dix-neuf'];
var tw = ['vingt','trente','quarante','cinquante', 'soixante','soixante-dix','quatre-vingt','quatre-vingt-dix'];
s = s.toString();
s = s.replace(/[\, ]/g,'');
if (s != parseFloat(s)) return 'not a number';
var x = s.indexOf('.');
if (x == -1)
x = s.length;
if (x > 15)
return 'too big';
var n = s.split('');
var str = '';
var sk = 0;
for (var i=0; i < x; i++) {
if ((x-i)%3==2) {
if (n[i] == '1') {
str += tn[Number(n[i+1])] + ' ';
i++;
sk=1;
} else if (n[i]!=0) {
if(s!=21 && s!=31 && s!=41 && s!=51 && s!=61 && s!=71 && s!=72 && s!=73 && s!=74 && s!=75 && s!=76 && s!=100 && s!=91 && s!=92 && s!=93 && s!=94 && s!=95 && s!=96){
if(s==20 || s==30 || s==40 || s==50 || s==60 || s==70 || s==80 || s==90){
str += tw[n[i]-2] + ' ';} // for not to display hyphens for 20,30...90
else{
str += tw[n[i]-2] + '-';}
sk=1;
}
}
} else if (n[i]!=0) {
if(s!=21 && s!=31 && s!=41 && s!=51 && s!=61 && s!=71 && s!=72 && s!=73 && s!=74 && s!=75 && s!=76 && s!=100 && s!=91 && s!=92 && s!=93 && s!=94 && s!=95 && s!=96){
str += dg[n[i]] +' ';
if ((x-i)%3==0) str += 'hundert '; // for start from 101 -
sk=1;
}
}
if ((x-i)%3==1) {
if(s!=21 && s!=31 && s!=41 && s!=51 && s!=61 && s!=71 && s!=72 && s!=73 && s!=74 && s!=75 && s!=76 && s!=100 && s!=91 && s!=92 && s!=93 && s!=94 && s!=95 && s!=96){
if (sk)
str += th[(x-i-1)/3] + ' ';
sk=0;
}
}
}
if (x != s.length) {
var y = s.length;
//str += 'point ';
//for (var i=x+1; i<y; i++)
// str += dg[n[i]] +' ';
str += 'virgule ';
var counter=0;
for (var i=x+1; i<y; i++){
if ((y-i)%3==2) {
if (n[i] == '1') {
str += tn[Number(n[i+1])] + ' ';
i++;
counter=1;
} else if (n[i]!=0) {
str += tw[n[i]-2] + '-';
counter=1;
}
}else if (n[i]!=0) { // 0235
str += dg[n[i]] +' ';
}
}
}
if (s!=21 && s!=31 && s!=41 && s!=51 && s!=61 && s!=71 && s!=72 && s!=73 && s!=74 && s!=75 && s!=76 && s!=100 && s!=91 && s!=92 && s!=93 && s!=94 && s!=95 && s!=96){
document.getElementById("demo").innerHTML = str.replace(/\s+/g,' ')
}
else if (s==21){
str = 'vingt-et-un'
document.getElementById("demo").innerHTML = str;
}//alert(str.replace(/\s+/g,' '));
else if (s==31){
str = 'trente-et-un'
document.getElementById("demo").innerHTML = str;}
else if (s==41){
str = 'quarante-et-un'
document.getElementById("demo").innerHTML = str;}
else if (s==51){
str = 'cinquante-et-un'
document.getElementById("demo").innerHTML = str;}
else if (s==61){
str = 'soixante-et-un'
document.getElementById("demo").innerHTML = str;}
else if (s==71){
str = 'soixante-et-onze'
document.getElementById("demo").innerHTML = str;}
else if (s==72){
str = 'soixante-douze'
document.getElementById("demo").innerHTML = str;}
else if (s==73){
str = 'soixante-treize'
document.getElementById("demo").innerHTML = str;}
else if (s==74){
str = 'soixante-quatorze'
document.getElementById("demo").innerHTML = str;}
else if (s==75){
str = 'soixante-quinze'
document.getElementById("demo").innerHTML = str;}
else if (s==76){
str = 'soixante-seize'
document.getElementById("demo").innerHTML = str;}
else if (s==100){
str = 'cent'
document.getElementById("demo").innerHTML = str;}
else if (s==91){
str = 'quatre-vingt-onze'
document.getElementById("demo").innerHTML = str;}
else if (s==92){
str = 'quatre-vingt-douze'
document.getElementById("demo").innerHTML = str;}
else if (s==93){
str = 'quatre-vingt-treize'
document.getElementById("demo").innerHTML = str;}
else if (s==94){
str = 'quatre-vingt-quatorze'
document.getElementById("demo").innerHTML = str;}
else if (s==95){
str = 'quatre-vingt-quinze'
document.getElementById("demo").innerHTML = str;}
else if (s==96){
str = 'quatre-vingt-seize'
document.getElementById("demo").innerHTML = str;}
}
</script>
</head>
<body>
<p>Enter only numbers (max 15 digits) : </p>
<input type="text" name="value" id='value' /><br>
<input type="button" value="submit" onclick="toWords()" />
<p id="demo"></p>
<p id="demo1"></p>
</body>
</html>
_x000D_
you can easily access elements by index , by use System.Linq
Here is the sample
First add using in your class file
using System.Linq;
Then
yourDictionaryData.ElementAt(i).Key
yourDictionaryData.ElementAt(i).Value
Hope this helps.
If you are willing to install a plugin, I recommend https://github.com/vim-scripts/CycleColor.
to cycle through all installed colorschemes. Nice way to easily choose a colorscheme.
Assign after the EXEC
token:
DECLARE @returnValue INT
EXEC @returnValue = SP_One
You can do that with lambda expressions;
private static final String BASE_URL = "http://api.example.org/data/2.5/forecast/daily";
private String getBaseUrl(Map<String, String> params) {
final Uri.Builder builder = Uri.parse(BASE_URL).buildUpon();
params.entrySet().forEach(entry -> builder.appendQueryParameter(entry.getKey(), entry.getValue()));
return builder.build().toString();
}
and you can create params like that;
Map<String, String> params = new HashMap<String, String>();
params.put("zip", "94043,us");
params.put("units", "metric");
Btw. If you will face any issue like “lambda expressions not supported at this language level”
, please check this URL;
Please set your form action attribute as below it will solve your problem.
<form name="addProductForm" id="addProductForm" action="javascript:;" enctype="multipart/form-data" method="post" accept-charset="utf-8">
jQuery code:
$(document).ready(function () {
$("#addProductForm").submit(function (event) {
//disable the default form submission
event.preventDefault();
//grab all form data
var formData = $(this).serialize();
$.ajax({
url: 'addProduct.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function () {
alert('Form Submitted!');
},
error: function(){
alert("error in ajax form submission");
}
});
return false;
});
});
The following code will create a list of files based on the accept method of the FileNameFilter
.
List<File> list = Arrays.asList(dir.listFiles(new FilenameFilter(){
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".exe"); // or something else
}}));
What does $rootScope.$broadcast do?
It broadcasts the message to respective listeners all over the angular app, a very powerful means to transfer messages to scopes at different hierarchical level(be it parent , child or siblings)
Similarly, we have $rootScope.$emit, the only difference is the former is also caught by $scope.$on while the latter is caught by only $rootScope.$on .
refer for examples :- http://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/
Found this on Dzone
Pad with zeros:
String.format("|%020d|", 93); // prints: |00000000000000000093|
I know this is an old post, but I wanted to add something for posterity. The simple way of handling the issue that you have is to make another table, of value to key.
ie. you have 2 tables that have the same value, one pointing one direction, one pointing the other.
function addValue(key, value)
if (value == nil) then
removeKey(key)
return
end
_primaryTable[key] = value
_secodaryTable[value] = key
end
function removeKey(key)
local value = _primaryTable[key]
if (value == nil) then
return
end
_primaryTable[key] = nil
_secondaryTable[value] = nil
end
function getValue(key)
return _primaryTable[key]
end
function containsValue(value)
return _secondaryTable[value] ~= nil
end
You can then query the new table to see if it has the key 'element'. This prevents the need to iterate through every value of the other table.
If it turns out that you can't actually use the 'element' as a key, because it's not a string for example, then add a checksum or tostring
on it for example, and then use that as the key.
Why do you want to do this? If your tables are very large, the amount of time to iterate through every element will be significant, preventing you from doing it very often. The additional memory overhead will be relatively small, as it will be storing 2 pointers to the same object, rather than 2 copies of the same object. If your tables are very small, then it will matter much less, infact it may even be faster to iterate than to have another map lookup.
The wording of the question however strongly suggests that you have a large number of items to deal with.
find files: ls -l /home | grep "^-" | tr -s ' ' | cut -d ' ' -f 9
find directories: ls -l /home | grep "^d" | tr -s ' ' | cut -d ' ' -f 9
find links: ls -l /home | grep "^l" | tr -s ' ' | cut -d ' ' -f 9
tr -s ' ' turns the output into a space-delimited file the cut command says the delimiter is a space, and return the 9th field (always the filename/directory name/linkname).
I use this all the time!
I ran into a similar issue. To check if SELinux is the problem, one can check its running status with
sestatus
and temporarily disable it with
setenforce 0
This could at least help to narrow down the problem.
Below code works for me:
JsonConvert.SerializeObject(JToken.Parse(yourobj.ToString()))
in
is the intended way to test for the existence of a key in a dict
.
d = {"key1": 10, "key2": 23}
if "key1" in d:
print("this will execute")
if "nonexistent key" in d:
print("this will not")
If you wanted a default, you can always use dict.get()
:
d = dict()
for i in range(100):
key = i % 10
d[key] = d.get(key, 0) + 1
and if you wanted to always ensure a default value for any key you can either use dict.setdefault()
repeatedly or defaultdict
from the collections
module, like so:
from collections import defaultdict
d = defaultdict(int)
for i in range(100):
d[i % 10] += 1
but in general, the in
keyword is the best way to do it.
I could not get this working with the accepted answer, mainly because I did not know where to enter that code. I looked everywhere for some explanation of the URL Rewrite tool that made sense, but could not find any. I ended up using the HTTP Redirect tool in IIS.
Hope this helps.
If your rename
doesn't support -N
, you can do something like this:
ls -1 --color=never -c | xargs rename -n 's/.*/our $i; sprintf("%04d.jpg", $i++)/e'
Edit To start with a given number, you can use the (somewhat ugly-looking) code below, just replace 123 with the number you want:
ls -1 --color=never -c | xargs rename -n 's/.*/our $i; if(!$i) { $i=123; } sprintf("%04d.jpg", $i++)/e'
This lists files in order by creation time (newest first, add -r
to ls to reverse sort), then sends this list of files to rename. Rename uses perl code in the regex to format and increment counter.
However, if you're dealing with JPEG images with EXIF information, I'd recommend exiftool
This is from the exiftool documentation, under "Renaming Examples"
exiftool '-FileName<CreateDate' -d %Y%m%d_%H%M%S%%-c.%%e dir
Rename all images in "dir" according to the "CreateDate" date and time, adding a copy number with leading '-' if the file already exists ("%-c"), and
preserving the original file extension (%e). Note the extra '%' necessary to escape the filename codes (%c and %e) in the date format string.
Try this also, that is remove new { } and replace it with string.
<%: Html.TextBoxFor(x => x.Age,"0") %>
Note: This answer does not explicitly answer the asked question. the other answers do it. Since the question is specific to a scenario and the raised exception is general, This answer points to the general case.
Hash values are just integers which are used to compare dictionary keys during a dictionary lookup quickly.
Internally, hash()
method calls __hash__()
method of an object which are set by default for any object.
>>> a = [1,2,3,4,[5,6,7],8,9]
>>> set(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
This happens because of the list inside a list which is a list which cannot be hashed. Which can be solved by converting the internal nested lists to a tuple,
>>> set([1, 2, 3, 4, (5, 6, 7), 8, 9])
set([1, 2, 3, 4, 8, 9, (5, 6, 7)])
>>> hash([1, 2, 3, [4, 5,], 6, 7])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> hash(tuple([1, 2, 3, [4, 5,], 6, 7]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> hash(tuple([1, 2, 3, tuple([4, 5,]), 6, 7]))
-7943504827826258506
The solution to avoid this error is to restructure the list to have nested tuples instead of lists.
Total number of cells in a range minus the blank cells of the same range.
=(115 - (COUNTBLANK(C2:C116)))
This counts everything in the range so, maybe not what you're looking for.
Found a nice solution in another Stackoverflow post (using only standard libraries + dealing with jpg as well): JohnTESlade answer
And another solution (the quick way) for those who can afford running 'file' command within python, run:
import os
info = os.popen("file foo.jpg").read()
print info
Output:
foo.jpg: JPEG image data...density 28x28, segment length 16, baseline, precision 8, 352x198, frames 3
All you gotta do now is to format the output to capture the dimensions. 352x198 in my case.
MacOS
If you want to set up a windows environment with Virtualbox on a mac, just use the default NAT settings on the adapter, and in your windows VM, go to hosts file and add the following:
10.0.2.2 localhost
10.0.2.2 127.0.0.1
Differently from the answers above, it's important to include both lines, otherwise it won't work.
Tenary Operator helps keep it short and simple.
echo (isset($_SERVER['HTTPS']) ? 'http' : 'https' ). "://" . $_SERVER['SERVER_NAME'] ;
There are other mechanisms to handle overflow than the simple minded linked list of overflow entries which e.g. wastes a lot of memory.
Which mechanism to use depends among other things on if you can choose the hash function and possible pick more than one (to implement e.g. double hashing to handle collisions); if you expect to often add items or if the map is static once filled; if you intend to remove items or not; ...
The best way to implement this is to first think about all these parameters and then not code it yourself but to pick a mature existing implementation. Google has a few good implementations -- e.g. http://code.google.com/p/google-sparsehash/
After creating your QVBoxLayout
in Qt Designer, right-click on the background of your widget/dialog/window (not the QVBoxLayout
, but the parent widget) and select Lay Out -> Lay Out in a Grid from the bottom of the context-menu. The QVBoxLayout
should now stretch to fit the window and will resize automatically when the entire window is resized.
Use the static exit()
method in the SpringApplication class for closing your spring boot application gracefully.
public class SomeClass {
@Autowire
private ApplicationContext context
public void close() {
SpringApplication.exit(context);
}
}
Here's another step I had to go through, after receiving an error on completing Step 9:
ImportError: dlopen(/Users/rick/.python-eggs/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib
sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib
Reference: Thanks! http://ageekstory.blogspot.com/2011_04_01_archive.html
you can write events on elements like chain,
$(element).on('click',function(){
//action on click
}).on('mouseup',function(){
//action on mouseup (just before click event)
});
i've used it for removing cart items. same object, doing some action, after another action
When you put the username and password in front of the host, this data is not sent that way to the server. It is instead transformed to a request header depending on the authentication schema used. Most of the time this is going to be Basic Auth which I describe below. A similar (but significantly less often used) authentication scheme is Digest Auth which nowadays provides comparable security features.
With Basic Auth, the HTTP request from the question will look something like this:
GET / HTTP/1.1
Host: example.com
Authorization: Basic Zm9vOnBhc3N3b3Jk
The hash like string you see there is created by the browser like this: base64_encode(username + ":" + password)
.
To outsiders of the HTTPS transfer, this information is hidden (as everything else on the HTTP level). You should take care of logging on the client and all intermediate servers though. The username will normally be shown in server logs, but the password won't. This is not guaranteed though. When you call that URL on the client with e.g. curl
, the username and password will be clearly visible on the process list and might turn up in the bash history file.
When you send passwords in a GET request as e.g. http://example.com/login.php?username=me&password=secure the username and password will always turn up in server logs of your webserver, application server, caches, ... unless you specifically configure your servers to not log it. This only applies to servers being able to read the unencrypted http data, like your application server or any middleboxes such as loadbalancers, CDNs, proxies, etc. though.
Basic auth is standardized and implemented by browsers by showing this little username/password popup you might have seen already. When you put the username/password into an HTML form sent via GET or POST, you have to implement all the login/logout logic yourself (which might be an advantage and allows you to more control over the login/logout flow for the added "cost" of having to implement this securely again). But you should never transfer usernames and passwords by GET parameters. If you have to, use POST instead. The prevents the logging of this data by default.
When implementing an authentication mechanism with a user/password entry form and a subsequent cookie-based session as it is commonly used today, you have to make sure that the password is either transported with POST requests or one of the standardized authentication schemes above only.
Concluding I could say, that transfering data that way over HTTPS is likely safe, as long as you take care that the password does not turn up in unexpected places. But that advice applies to every transfer of any password in any way.
With respect to the String class:
The equals() method compares the "value" inside String instances (on the heap) irrespective if the two object references refer to the same String instance or not. If any two object references of type String refer to the same String instance then great! If the two object references refer to two different String instances .. it doesn't make a difference. Its the "value" (that is: the contents of the character array) inside each String instance that is being compared.
On the other hand, the "==" operator compares the value of two object references to see whether they refer to the same String instance. If the value of both object references "refer to" the same String instance then the result of the boolean expression would be "true"..duh. If, on the other hand, the value of both object references "refer to" different String instances (even though both String instances have identical "values", that is, the contents of the character arrays of each String instance are the same) the result of the boolean expression would be "false".
As with any explanation, let it sink in.
I hope this clears things up a bit.
One thing, regardless of how you initialize the field, use of the final
qualifier, if possible, will ensure the visibility of the field's value in a multi-threaded environment.
All I needed was to expose the keyboard, in a very precise moment. This worked for me! Thanks Benites.
private Handler mHandler= new Handler();
And in the very precise moment:
mHandler.post(
new Runnable() {
public void run() {
InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInputFromWindow(yourEditText.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0);
yourEditText.requestFocus();
}
});
Had the same problem, while differently from other answers in my case I use ASP.NET to develop the WebAPI server.
I already had Corps allowed and it worked for GET requests. To make POST requests work I needed to add 'AllowAnyHeader()' and 'AllowAnyMethod()' options to the list of Corp options.
Here are essential parts of related functions in Start class look like:
ConfigureServices method:
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder
.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod()
//.AllowCredentials()
;
});
});
Configure method:
app.UseCors(MyAllowSpecificOrigins);
Found this from:
Or.... Call your main .bat file from another .bat file and output the result to a result file i.e.
runner.bat > mainresults.txt
Where runner.bat calls the main .bat file
You should see all the actions performed in the main .bat file now
add this to you CSS:
html, body
{
height: 100%;
}
when you say to wrap
to be 100%
, 100% of what? of its parent (body), so his parent has to have some height.
and the same goes for body
, his parent his html
. html
parent his the viewport..
so, by setting them both to 100%, wrap
can also have a percentage height.
also: the elements have some default padding/margin, that causes them to span a little more then the height you applied to them. (causing a scroll bar) you can use
*
{
padding: 0;
margin: 0;
}
to disable that.
Look at That Fiddle
Fix This issue by this command
In Windows Platform
cd android && gradlew clean && cd..
In Mac Platform
cd android && ./gradlew clean && cd ..
Simply call InetAddress.getByName(String host)
passing in your textual IP address.
From the javadoc: The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address.