We have two files, foo.c and bar.c.
Here is foo.c
#include <stdio.h>
volatile unsigned int stop_now = 0;
extern void bar_function(void);
int main(void)
{
while (1) {
bar_function();
stop_now = 1;
}
return 0;
}
Now, here is bar.c
#include <stdio.h>
extern volatile unsigned int stop_now;
void bar_function(void)
{
if (! stop_now) {
printf("Hello, world!\n");
sleep(30);
}
}
As you can see, we have no shared header between foo.c and bar.c , however bar.c needs something declared in foo.c when it's linked, and foo.c needs a function from bar.c when it's linked.
By using 'extern', you are telling the compiler that whatever follows it will be found (non-static) at link time; don't reserve anything for it in the current pass since it will be encountered later. Functions and variables are treated equally in this regard.
It's very useful if you need to share some global between modules and don't want to put / initialize it in a header.
Technically, every function in a library public header is 'extern', however labeling them as such has very little to no benefit, depending on the compiler. Most compilers can figure that out on their own. As you see, those functions are actually defined somewhere else.
In the above example, main() would print hello world only once, but continue to enter bar_function(). Also note, bar_function() is not going to return in this example (since it's just a simple example). Just imagine stop_now being modified when a signal is serviced (hence, volatile) if this doesn't seem practical enough.
Externs are very useful for things like signal handlers, a mutex that you don't want to put in a header or structure, etc. Most compilers will optimize to ensure that they don't reserve any memory for external objects, since they know they'll be reserving it in the module where the object is defined. However, again, there's little point in specifying it with modern compilers when prototyping public functions.
Hope that helps :)
if you are looking to generate all the number within a specific rang randomly then you can try
r = randi([a b],1,d)
a
= start point
b
= end point
d
= how many number you want to generate but keep in mind that d should be less than or equal to b-a
For simple structures you can either use memcpy
like you do, or just assign from one to the other:
RTCclk = RTCclkBuffert;
The compiler will create code to copy the structure for you.
An important note about the copying: It's a shallow copy, just like with memcpy
. That means if you have e.g. a structure containing pointers, it's only the actual pointers that will be copied and not what they point to, so after the copy you will have two pointers pointing to the same memory.
Here is my solution for this :
mkdir temp
mkdir results
cp /usr/share/dict/american-english ~/temp/american-english-dictionary
cp /usr/share/dict/british-english ~/temp/british-english-dictionary
cat ~/temp/american-english-dictionary | wc -l > ~/results/count-american-english-dictionary
cat ~/temp/british-english-dictionary | wc -l > ~/results/count-british-english-dictionary
grep -Fxf ~/temp/american-english-dictionary ~/temp/british-english-dictionary > ~/results/common-english
grep -Fxvf ~/results/common-english ~/temp/american-english-dictionary > ~/results/unique-american-english
grep -Fxvf ~/results/common-english ~/temp/british-english-dictionary > ~/results/unique-british-english
Yes, it's safe to delete these, although it may force a dynamic recompilation of any .NET applications you run on the server.
For background, see the Understanding ASP.NET dynamic compilation article on MSDN.
Select * from table
where CONTAINS([Column], '"A00*"')
will act as % same as
where [Column] Like 'A00%'
For substracting in moment.js:
moment().subtract(1, 'months').format('MMM YYYY');
Documentation:
http://momentjs.com/docs/#/manipulating/subtract/
Before version 2.8.0, the moment#subtract(String, Number) syntax was also supported. It has been deprecated in favor of moment#subtract(Number, String).
moment().subtract('seconds', 1); // Deprecated in 2.8.0
moment().subtract(1, 'seconds');
As of 2.12.0 when decimal values are passed for days and months, they are rounded to the nearest integer. Weeks, quarters, and years are converted to days or months, and then rounded to the nearest integer.
moment().subtract(1.5, 'months') == moment().subtract(2, 'months')
moment().subtract(.7, 'years') == moment().subtract(8, 'months') //.7*12 = 8.4, rounded to 8
As of Xcode 6.0.1 (at least, not sure when they added it), your original example now works:
class MyClass {
var count = 0
}
let mc = MyClass()
mc.dynamicType === MyClass.self // returns `true`
To answer the original question, you can actually use the Objective-C runtime with plain Swift objects successfully.
Try the following:
import Foundation
class MyClass { }
class SubClass: MyClass { }
let mc = MyClass()
let m2 = SubClass()
// Both of these return .Some("__lldb_expr_35.SubClass"), which is the fully mangled class name from the playground
String.fromCString(class_getName(m2.dynamicType))
String.fromCString(object_getClassName(m2))
// Returns .Some("__lldb_expr_42.MyClass")
String.fromCString(object_getClassName(mc))
For people just migrating from java
, In Kotlin
List
is by default immutable and mutable version of Lists is called MutableList
.
Hence if you have something like :
val list: List<String> = ArrayList()
In this case you will not get an add()
method as list is immutable. Hence you will have to declare a MutableList
as shown below :
val list: MutableList<String> = ArrayList()
Now you will see an add()
method and you can add elements to any list.
I had similar issues with the threads being started in Spring bean. These threads were not closing properly after i called executor.shutdownNow() in @PreDestroy method. So the solution for me was to let the thread finsih with IO already started and start no more IO, once @PreDestroy was called. And here is the @PreDestroy method. For my application the wait for 1 second was acceptable.
@PreDestroy
public void beandestroy() {
this.stopThread = true;
if(executorService != null){
try {
// wait 1 second for closing all threads
executorService.awaitTermination(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
Here I have explained all the issues faced while trying to close threads.http://programtalk.com/java/executorservice-not-shutting-down/
Use the Out-File
cmdlet
Compare-Object ... | Out-File C:\filename.txt
Optionally, add -Encoding utf8
to Out-File
as the default encoding is not really ideal for many uses.
I wrote the following function. It replaces the following:
Single quote ['] with a slash and a single quote [\'].
Backslash [\] with two backslashes [\\]
function escapePhpString($target) {
$replacements = array(
"'" => '\\\'',
"\\" => '\\\\'
);
return strtr($target, $replacements);
}
You can modify it to add or remove character replacements in the $replacements array. For example, to replace \r\n, it becomes "\r\n" => "\r\n" and "\n" => "\n".
/**
* With new line replacements too
*/
function escapePhpString($target) {
$replacements = array(
"'" => '\\\'',
"\\" => '\\\\',
"\r\n" => "\\r\\n",
"\n" => "\\n"
);
return strtr($target, $replacements);
}
The neat feature about strtr is that it will prefer long replacements.
Example, "Cool\r\nFeature" will escape \r\n rather than escaping \n along.
it's better use this example.
Call action and controller using a ActionLink
:
@Html.ActionLink("Submit", "Action", "Controller", route, new { @class = "btn btn-block"})
It sounds like you need to some background reading on what an FFT is (e.g. http://en.wikipedia.org/wiki/FFT). But to answer your questions:
Why does the x-axis (frequency) end at 500?
Because the input vector is length 1000. In general, the FFT of a length-N
input waveform will result in a length-N
output vector. If the input waveform is real, then the output will be symmetrical, so the first 501 points are sufficient.
Edit: (I didn't notice that the example padded the time-domain vector.)
The frequency goes to 500 Hz because the time-domain waveform is declared to have a sample-rate of 1 kHz. The Nyquist sampling theorem dictates that a signal with sample-rate fs
can support a (real) signal with a maximum bandwidth of fs/2
.
How do I know the frequencies are between 0 and 500?
See above.
Shouldn't the FFT tell me, in which limits the frequencies are?
No.
Does the FFT only return the amplitude value without the frequency?
The FFT simply assigns an amplitude (and phase) to every frequency bin.
Try below code :
Assign the path of the folder to variable FolderPath
before running the below code.
Sub sample()
Dim FolderPath As String, path As String, count As Integer
FolderPath = "C:\Documents and Settings\Santosh\Desktop"
path = FolderPath & "\*.xls"
Filename = Dir(path)
Do While Filename <> ""
count = count + 1
Filename = Dir()
Loop
Range("Q8").Value = count
'MsgBox count & " : files found in folder"
End Sub
For older versions of jQuery
jQuery().jquery (or)
jQuery().fn.jquery
For newer versions of jQuery
$().jquery (or)
$().fn.jquery
Uncheck "Size Classes" checkbox works for me as well, but you could also add the missing constraints in the interface builder. Just use the built-in function if you don't want to add the constraints on your own. Using constraints is - in my opinion - the better way because the layout is independent from the device (iPhone or iPad).
You should set both autoplay and autoplayTimeout properties. I used this code, and it works for me:
$('.owl-carousel').owlCarousel({
autoplay: true,
autoplayTimeout: 5000,
navigation: false,
margin: 10,
responsive: {
0: {
items: 1
},
600: {
items: 2
},
1000: {
items: 2
}
}
})
You use it like this:
SELECT age, name
FROM users
UNION
SELECT 25 AS age, 'Betty' AS name
Use UNION ALL
to allow duplicates: if there is a 25-years old Betty among your users, the second query will not select her again with mere UNION
.
Wikipedia has a very good answer http://en.wikipedia.org/wiki/Universally_unique_identifier#Collisions
the number of random version 4 UUIDs which need to be generated in order to have a 50% probability of at least one collision is 2.71 quintillion, computed as follows:
...
This number is equivalent to generating 1 billion UUIDs per second for about 85 years, and a file containing this many UUIDs, at 16 bytes per UUID, would be about 45 exabytes, many times larger than the largest databases currently in existence, which are on the order of hundreds of petabytes.
...
Thus, for there to be a one in a billion chance of duplication, 103 trillion version 4 UUIDs must be generated.
Try putting it in quotes:
find . -name '*test.c'
Run command rndc querylog on
or add querylog yes;
to options{};
section in named.conf
to activate that channel.
Also make sure you’re checking correct directory if your bind is chrooted.
My program with two arguments, args[0] and args[1]:
public static void main(String[] args) throws Exception {
System.out.println(args);
String host = args[0];
System.out.println(host);
int port = Integer.parseInt(args[1]);
my build.gradle
run {
if ( project.hasProperty("appArgsWhatEverIWant") ) {
args Eval.me(appArgsWhatEverIWant)
}
}
my terminal prompt:
gradle run -PappArgsWhatEverIWant="['localhost','8080']"
footerText {
line-height: 20px;
}
you don't need to start playing with position or even layout of other elements... use this simple solution
I seem to have a blind spot as regards your html structure, but I think that this is what you're looking for. It should find the currently-selected option from the select
input, assign its text to the newVal
variable and then apply that variable to the value
attribute of the #costLabel
label:
$(document).ready(
function() {
$('select[name=package]').change(
function(){
var newText = $('option:selected',this).text();
$('#costLabel').text('Total price: ' + newText);
}
);
}
);
<form name="thisForm" id="thisForm" action="#" method="post">
<fieldset>
<select name="package" id="package">
<option value="standard">Standard - €55 Monthly</option>
<option value="standardAnn">Standard - €49 Monthly</option>
<option value="premium">Premium - €99 Monthly</option>
<option value="premiumAnn" selected="selected">Premium - €89 Monthly</option>
<option value="platinum">Platinum - €149 Monthly</option>
<option value="platinumAnn">Platinum - €134 Monthly</option>
</select>
</fieldset>
<fieldset>
<label id="costLabel" name="costLabel">Total price: </label>
</fieldset>
</form>
Working demo of the above at: JS Bin
Use .get()
, which if the key is not found, returns None
.
for i in keySet:
temp = myDict.get(i)
if temp is not None:
print temp
break
Use padding-left:1em; text-indent:-1em
for the <li>
tag.
Then, list-style-position: inside
for the <ul>
tag.
<ul style='list-style-position: inside;'>
<li style='padding-left: 1em; text-indent: -1em;'>Item 1</li>
</ul>
One way to skip this is by creating a specific app password variable.
And you can use that generated password
to access or to push commits from your terminal, when using a Google Account to sign in into Bitbucket.
If the file that this script lives in is executable, the hash-bang (#!
) tells the operating system what interpreter to use to run the script. In this case it's /bin/sh
, for example.
There's a Wikipedia article about it for more information.
One way to do this would be to pass the instance of ParentClass
to the ChildClass
on construction
public ChildClass
{
private ParentClass parent;
public ChildClass(ParentClass parent)
{
this.parent = parent;
}
public void LoadData(DateTable dt)
{
// do something
parent.CurrentRow++; // or whatever.
parent.UpdateProgressBar(); // Call the method
}
}
Make sure to pass the reference to this
when constructing ChildClass
inside parent:
if(loadData){
ChildClass childClass = new ChildClass(this); // here
childClass.LoadData(this.Datatable);
}
Caveat: This is probably not the best way to organise your classes, but it directly answers your question.
EDIT: In the comments you mention that more than 1 parent class wants to use ChildClass
. This is possible with the introduction of an interface, eg:
public interface IParentClass
{
void UpdateProgressBar();
int CurrentRow{get; set;}
}
Now, make sure to implement that interface on both (all?) Parent Classes and change child class to this:
public ChildClass
{
private IParentClass parent;
public ChildClass(IParentClass parent)
{
this.parent = parent;
}
public void LoadData(DateTable dt)
{
// do something
parent.CurrentRow++; // or whatever.
parent.UpdateProgressBar(); // Call the method
}
}
Now anything that implements IParentClass
can construct an instance of ChildClass
and pass this
to its constructor.
In onMapReady() Method
change the zoomLevel to any desired value.
float zoomLevel = (float) 18.0;
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoomLevel));
https://www.agnosticdev.com/content/how-detect-network-connectivity-android
please follow this tutorial it should help anyone looking for answers.
note networkInfo has been deprecated hence replace it is isNetworkReacheable() with @vidha answer below passing getApplicationContext() as parameter
public static boolean isNetworkReacheable(Context context) {
boolean result = false;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (cm != null) {
NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork());
if (capabilities != null) {
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
result = true;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
result = true;
}
}
}
} else {
if (cm != null) {
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
// connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
result = true;
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
result = true;
}
}
}
}
return result;
}
Your code can get messy fast when dealing with CSS3 transitions. I would recommend using a plugin such as jQuery Transit that handles the complexity of CSS3 animations/transitions.
Moreover, the plugin uses webkit-transform rather than webkit-transition, which allows for mobile devices to use hardware acceleration in order to give your web apps that native look and feel when the animations occur.
Javascript:
$("#startTransition").on("click", function()
{
if( $(".boxOne").is(":visible"))
{
$(".boxOne").transition({ x: '-100%', opacity: 0.1 }, function () { $(".boxOne").hide(); });
$(".boxTwo").css({ x: '100%' });
$(".boxTwo").show().transition({ x: '0%', opacity: 1.0 });
return;
}
$(".boxTwo").transition({ x: '-100%', opacity: 0.1 }, function () { $(".boxTwo").hide(); });
$(".boxOne").css({ x: '100%' });
$(".boxOne").show().transition({ x: '0%', opacity: 1.0 });
});
Most of the hard work of getting cross-browser compatibility is done for you as well and it works like a charm on mobile devices.
string a = "", b = a , c = a, d = a, e = a, f =a;
To solve this you must ensure the following is true on the machine hosting SQL Server...
You can configure your pod with a grace period (for example 30 seconds or more, depending on container startup time and image size) and set "imagePullPolicy: "Always"
. And use kubectl delete pod pod_name
.
A new container will be created and the latest image automatically downloaded, then the old container terminated.
Example:
spec:
terminationGracePeriodSeconds: 30
containers:
- name: my_container
image: my_image:latest
imagePullPolicy: "Always"
I'm currently using Jenkins for automated builds and image tagging and it looks something like this:
kubectl --user="kube-user" --server="https://kubemaster.example.com" --token=$ACCESS_TOKEN set image deployment/my-deployment mycontainer=myimage:"$BUILD_NUMBER-$SHORT_GIT_COMMIT"
Another trick is to intially run:
kubectl set image deployment/my-deployment mycontainer=myimage:latest
and then:
kubectl set image deployment/my-deployment mycontainer=myimage
It will actually be triggering the rolling-update but be sure you have also imagePullPolicy: "Always"
set.
Update:
another trick I found, where you don't have to change the image name, is to change the value of a field that will trigger a rolling update, like terminationGracePeriodSeconds
. You can do this using kubectl edit deployment your_deployment
or kubectl apply -f your_deployment.yaml
or using a patch like this:
kubectl patch deployment your_deployment -p \
'{"spec":{"template":{"spec":{"terminationGracePeriodSeconds":31}}}}'
Just make sure you always change the number value.
The above answers tell how to get the position using different API, onScroll
, onMomentumScrollEnd
etc; If you want to know the page index, you can calculate it using the offset value.
<ScrollView
pagingEnabled={true}
onMomentumScrollEnd={this._onMomentumScrollEnd}>
{pages}
</ScrollView>
_onMomentumScrollEnd = ({ nativeEvent }: any) => {
// the current offset, {x: number, y: number}
const position = nativeEvent.contentOffset;
// page index
const index = Math.round(nativeEvent.contentOffset.x / PAGE_WIDTH);
if (index !== this.state.currentIndex) {
// onPageDidChanged
}
};
In iOS, the relationship between ScrollView and the visible region is as follow:
This should also work and is a closer answer to what is asked in the question:
for i in range(len(x)):
if valeur.item(i) <= 0.6:
print ("this works")
else:
print ("valeur is too high")
Thanks for the input. Tried the stuff that has been mentioned here and these are the 2 I got to work:
(
select 'OK', * from WorkItems t1
where exists(select 1 from workitems t2 where t1.TextField01=t2.TextField01 AND (BoolField05=1) )
AND TimeStamp=(select max(t2.TimeStamp) from workitems t2 where t2.TextField01=t1.TextField01)
AND TimeStamp>'2009-02-12 18:00:00'
AND (BoolField05=1)
)
UNION
(
select 'DEL', * from WorkItems t1
where exists(select 1 from workitems t2 where t1.TextField01=t2.TextField01 AND (BoolField05=1) )
AND TimeStamp=(select max(t2.TimeStamp) from workitems t2 where t2.TextField01=t1.TextField01)
AND TimeStamp>'2009-02-12 18:00:00'
AND NOT (BoolField05=1)
)
AND
select
case
when
(BoolField05=1)
then 'OK'
else 'DEL'
end,
*
from WorkItems t1
Where
exists(select 1 from workitems t2 where t1.TextField01=t2.TextField01 AND (BoolField05=1) )
AND TimeStamp=(select max(t2.TimeStamp) from workitems t2 where t2.TextField01=t1.TextField01)
AND TimeStamp>'2009-02-12 18:00:00'
Which would be the most efficient of these (edit: the second as it only scans the table once), and is it possible to make it even more efficient? (The BoolField=1) is really a variable (dyn sql) that can contain any where statement on the table.
I am running on MS SQL 2005. Tried Quassnoi examples but did not work as expected.
I fear i incur upset reactions but nevertheless, to clarify for me if i'm wrong or those seeing this question and being interested in an answer:
my understanding of https://tools.ietf.org/html/rfc1122 whose status is "an official specification" and as such is the reference for the terminology used in this question and which is neither superseded by another RFC nor has errata contradicting the following:
theoretically, ie. based on the written spec., UDP like given by https://tools.ietf.org/html/rfc1122#section-4 has no "packet size". Thus the answer could be "indefinite"
In practice, which is what this questions likely seeked (and which could be updated for current tech in action), this might be different and I don't know.
I apologize if i caused upsetting. https://tools.ietf.org/html/rfc1122#page-8 The "Internet Protocol Suite" and "Architectural Assumptions" don't make clear to me the "assumption" i was on, based on what I heard, that the layers are separate. Ie. the layer UDP is in does not have to concern itself with the layer IP is in (and the IP layer does have things like Reassembly, EMTU_R, Fragmentation and MMS_R (https://tools.ietf.org/html/rfc1122#page-56))
Add the text-align
css property to its parent style attribute
Eg:
<div style="text-align:center">
<a href="http://www.example.com">example</a>????????????????????????????????????
</div>?
Or using a class (recommended)
<div class="my-class">
<a href="http://www.example.com">example</a>????????????????????????????????????
</div>?
.my-class {
text-align: center;
}
See below working example:
.my-class {_x000D_
text-align: center;_x000D_
background:green;_x000D_
width:400px;_x000D_
padding:15px; _x000D_
}_x000D_
.my-class a{text-decoration:none; color:#fff;}
_x000D_
<!--EXAMPLE-ONE-->_x000D_
<div style="text-align:center; border:solid 1px #000; padding:15px;">_x000D_
<a href="http://www.example.com">example</a>????????????????????????????????????_x000D_
</div>?_x000D_
_x000D_
<!--EXAMPLE-TWO-->_x000D_
<div class="my-class">_x000D_
<a href="http://www.example.com">example</a>????????????????????????????????????_x000D_
</div>?
_x000D_
Q: Why doesn't the text-align
style get applied to the a
element instead of the div
?
A: The text-align
style describes how inline
content is aligned within a block
element. In this case the div
is an block element and it's inline content is the a
. To further explore this consider how little sense it would make to apply the text-align
style to the a
element when it is accompanied by more text
<div>
Plain text is inline content.
<a href="http://www.example.com" style="text-align: center">example</a>
<span>Spans are also inline content</span>
</div>
Even though threre are line breaks here all the contents of div
are inline content and therefore will produce something like:
Plain text is inline content. example Spans are also inline content
It doesnt' make much sense as to how "example" in this case would be displayed if the text-align
property were to be applied it it.
It is also possible to use FormData()
. But you need to set contentType
as false
:
var data = new FormData();
data.append('name', 'Bob');
function sendData() {
$.ajax({
url: '/helloworld',
type: 'POST',
contentType: false,
data: data,
dataType: 'json'
});
}
You might want to do this.
input[type=checkbox] {
-ms-transform: scale(2); /* IE */
-moz-transform: scale(2); /* FF */
-webkit-transform: scale(2); /* Safari and Chrome */
-o-transform: scale(2); /* Opera */
padding: 10px;
}
ApplicationId must be of type UniqueIdentifier
. Your code works fine if you do:
DECLARE @TTEST TABLE
(
TEST UNIQUEIDENTIFIER
)
DECLARE @UNIQUEX UNIQUEIDENTIFIER
SET @UNIQUEX = NEWID();
INSERT INTO @TTEST
(TEST)
VALUES
(@UNIQUEX);
SELECT * FROM @TTEST
Therefore I would say it is safe to assume that ApplicationId
is not the correct data type.
I Just came across to a similar to this question solution with included some performance statistics.
It seems that example below is faster:
document.getElementById('container').insertAdjacentHTML('beforeend', '<div id="idChild"> content html </div>');
_x000D_
InnerHTML vs jQuery 1 vs appendChild vs innerAdjecentHTML.
Reference: 1) Performance stats 2) API - insertAdjacentHTML
I hope this will help.
You actually can't manually "free" memory in C, in the sense that the memory is released from the process back to the OS ... when you call malloc()
, the underlying libc-runtime will request from the OS a memory region. On Linux, this may be done though a relatively "heavy" call like mmap()
. Once this memory region is mapped to your program, there is a linked-list setup called the "free store" that manages this allocated memory region. When you call malloc()
, it quickly looks though the free-store for a free block of memory at the size requested. It then adjusts the linked list to reflect that there has been a chunk of memory taken out of the originally allocated memory pool. When you call free()
the memory block is placed back in the free-store as a linked-list node that indicates its an available chunk of memory.
If you request more memory than what is located in the free-store, the libc-runtime will again request more memory from the OS up to the limit of the OS's ability to allocate memory for running processes. When you free memory though, it's not returned back to the OS ... it's typically recycled back into the free-store where it can be used again by another call to malloc()
. Thus, if you make a lot of calls to malloc()
and free()
with varying memory size requests, it could, in theory, cause a condition called "memory fragmentation", where there is enough space in the free-store to allocate your requested memory block, but not enough contiguous space for the size of the block you've requested. Thus the call to malloc()
fails, and you're effectively "out-of-memory" even though there may be plenty of memory available as a total amount of bytes in the free-store.
sed -n 's/^potato:[[:space:]]*//p' file.txt
One can think of Grep as a restricted Sed, or of Sed as a generalized Grep. In this case, Sed is one good, lightweight tool that does what you want -- though, of course, there exist several other reasonable ways to do it, too.
Or if you want a ripple pulse effect, you could use this:
http://jsfiddle.net/Fy8vD/3041/
.gps_ring {
border: 2px solid #fff;
-webkit-border-radius: 50%;
height: 18px;
width: 18px;
position: absolute;
left:20px;
top:214px;
-webkit-animation: pulsate 1s ease-out;
-webkit-animation-iteration-count: infinite;
opacity: 0.0;
}
.gps_ring:before {
content:"";
display:block;
border: 2px solid #fff;
-webkit-border-radius: 50%;
height: 30px;
width: 30px;
position: absolute;
left:-8px;
top:-8px;
-webkit-animation: pulsate 1s ease-out;
-webkit-animation-iteration-count: infinite;
-webkit-animation-delay: 0.1s;
opacity: 0.0;
}
.gps_ring:after {
content:"";
display:block;
border:2px solid #fff;
-webkit-border-radius: 50%;
height: 50px;
width: 50px;
position: absolute;
left:-18px;
top:-18px;
-webkit-animation: pulsate 1s ease-out;
-webkit-animation-iteration-count: infinite;
-webkit-animation-delay: 0.2s;
opacity: 0.0;
}
@-webkit-keyframes pulsate {
0% {-webkit-transform: scale(0.1, 0.1); opacity: 0.0;}
50% {opacity: 1.0;}
100% {-webkit-transform: scale(1.2, 1.2); opacity: 0.0;}
}
For editing this is possible in nano
via +n
from command line, e.g.,
nano +16 file.txt
To open file.txt
to line 16.
Use HTTPFUL
Httpful is a simple, chainable, readable PHP library intended to make speaking HTTP sane. It lets the developer focus on interacting with APIs instead of sifting through curl set_opt pages and is an ideal PHP REST client.
Httpful includes...
Ex.
Send off a GET request. Get automatically parsed JSON response.
The library notices the JSON Content-Type in the response and automatically parses the response into a native PHP object.
$uri = "https://www.googleapis.com/freebase/v1/mqlread?query=%7B%22type%22:%22/music/artist%22%2C%22name%22:%22The%20Dead%20Weather%22%2C%22album%22:%5B%5D%7D";
$response = \Httpful\Request::get($uri)->send();
echo 'The Dead Weather has ' . count($response->body->result->album) . " albums.\n";
This is nothing to do with hardware nor software. Simply that RGB are the 3 primary colours which can be combined in various ways to produce every other colour. It is more about the human convention/perception of colours which carried over.
You may find this article interesting.
I'm also having the same issue with a very latest Tomcat server (7.0.40). It goes non-responsive once for a couple of days.
To see open connections, you may use:
sudo netstat -tonp | grep jsvc | grep --regexp="127.0.0.1:443" --regexp="127.0.0.1:80" | grep CLOSE_WAIT
As mentioned in this post, you may use /proc/sys/net/ipv4/tcp_keepalive_time
to view the values. The value seems to be in seconds and defaults to 7200 (i.e. 2 hours).
To change them, you need to edit /etc/sysctl.conf
.
Open/create `/etc/sysctl.conf`
Add `net.ipv4.tcp_keepalive_time = 120` and save the file
Invoke `sysctl -p /etc/sysctl.conf`
Verify using `cat /proc/sys/net/ipv4/tcp_keepalive_time`
You are better off running the command in the console to get a better idea on what is wrong with the settings. In my case, when I ran gradlew check
it actually tells me which referenced project was missing.
* What went wrong:
Could not determine the dependencies of task ':test'.
Could not resolve all task dependencies for configuration ':testRuntimeClasspath'.
Could not resolve project :lib-blah.
Required by:
project :
> Unable to find a matching configuration of project :lib-blah: None of the consumable configurations have attributes.
The annoying thing was that, it would not show any meaningful error message during the import failure. And if I commented out all the project references, sure it let me import it, but then once I uncomment it out, it would only print that ambiguous message and not tell you what is wrong.
>>> a = '&#'
>>> print a.replace('&', r'\&')
\&#
>>> print a.replace('#', r'\#')
&\#
>>>
You want to use a 'raw' string (denoted by the 'r' prefixing the replacement string), since raw strings to not treat the backslash specially.
The pattern must have delimiters. Delimiters can be a forward slash (/) or any non alphanumeric characters(#,$,*,...). Examples
$pattern = "/My name is '(.*)' and im fine/";
$pattern = "#My name is '(.*)' and im fine#";
$pattern = "@My name is '(.*)' and im fine@";
move all files(not include except file) to except_file
find -maxdepth 1 -mindepth 1 -not -name except_file -print0 |xargs -0 mv -t ./except_file
for example(cache is current except file)
find -maxdepth 1 -mindepth 1 -not -name cache -print0 |xargs -0 mv -t ./cache
You can do it with a sub-query:
SELECT * FROM (
SELECT * FROM table ORDER BY id DESC LIMIT 50
) sub
ORDER BY id ASC
This will select the last 50 rows from table
, and then order them in ascending order.
Update for Swift 2:
sequence.contains(element): Returns true if a given sequence (such as an array) contains the specified element.
Swift 1:
If you're looking just to check if an element is contained inside an array, that is, just get a boolean indicator, use contains(sequence, element)
instead of find(array, element)
:
contains(sequence, element): Returns true if a given sequence (such as an array) contains the specified element.
See example below:
var languages = ["Swift", "Objective-C"]
contains(languages, "Swift") == true
contains(languages, "Java") == false
contains([29, 85, 42, 96, 75], 42) == true
if (contains(languages, "Swift")) {
// Use contains in these cases, instead of find.
}
The Django documentation for database queries includes a section on copying model instances. Assuming your primary keys are autogenerated, you get the object you want to copy, set the primary key to None
, and save the object again:
blog = Blog(name='My blog', tagline='Blogging is easy')
blog.save() # blog.pk == 1
blog.pk = None
blog.save() # blog.pk == 2
In this snippet, the first save()
creates the original object, and the second save()
creates the copy.
If you keep reading the documentation, there are also examples on how to handle two more complex cases: (1) copying an object which is an instance of a model subclass, and (2) also copying related objects, including objects in many-to-many relations.
Note on miah's answer: Setting the pk to None
is mentioned in miah's answer, although it's not presented front and center. So my answer mainly serves to emphasize that method as the Django-recommended way to do it.
Historical note: This wasn't explained in the Django docs until version 1.4. It has been possible since before 1.4, though.
Possible future functionality: The aforementioned docs change was made in this ticket. On the ticket's comment thread, there was also some discussion on adding a built-in copy
function for model classes, but as far as I know they decided not to tackle that problem yet. So this "manual" way of copying will probably have to do for now.
it "should call 'bar' with appropriate arguments" do
expect(subject).to receive(:bar).with("an argument I want")
subject.foo
end
delete from table where id <> 2
edit: to correct syntax for MySQL
In the file: $your_eclipse_installation\configuration.settings\org.eclipse.core.net.prefs
you need the option: systemProxiesEnabled=true
You can set it also by the Eclipse GUI: Go to Window -> Preferences -> General -> Network Connections Change the provider to "Native"
The first way is working even if your Eclipse is broken due to wrong configuration attempts.
Using wget
wget -O /tmp/myfile 'http://www.google.com/logo.jpg'
or curl:
curl -o /tmp/myfile 'http://www.google.com/logo.jpg'
What if you don't immediately set the button to disabled, but delay that through setTimeout? Your 'disable' function would return and the submit would continue.
You have to establish some kind of connection to do that android-out-of-the-box, like via tcp/ip and adb, so no not w/o installing at least adb and a listener on the computer.
But if you have an activity that sends the hardware keyboard like data via usb then why not? Won't be easy i guess. At this point the usuas forum answer comes right away: "Why don't you change your plans and ...." :)
It should work fine, are you wrapping the code in a $(document).ready()
call? If not use that or use live
i.e.
$('#fileupload1').live('change', function(){
alert("hola");
});
Here is a jsFiddle of this working against jQuery 1.4.4
This answer is for TextInputEditText :
In the layout XML file set your input method options to your required type. for example done.
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/textInputLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeOptions="actionGo"/>
</com.google.android.material.textfield.TextInputLayout>
Similarly, you can also set imeOptions to actionSubmit, actionSearch, etc
In the java add the editor action listener.
TextInputLayout textInputLayout = findViewById(R.id.textInputLayout);
textInputLayout.getEditText().setOnEditorActionListener(new
TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_GO) {
performYourAction();
return true;
}
return false;
}
});
If you're using kotlin :
textInputLayout.editText.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_GO) {
performYourAction()
}
true
}
As a side note, you can include the separators while splitting the string in Go. To do so, use strings.SplitAfter
as in the example below.
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Printf("%q\n", strings.SplitAfter("z,o,r,r,o", ","))
}
In case you're wondering about the performance of the different approaches, here are some timings:
In [1]: words = [str(i) for i in range(10000)]
In [2]: %timeit replaced = [w.replace('1', '<1>') for w in words]
100 loops, best of 3: 2.98 ms per loop
In [3]: %timeit replaced = map(lambda x: str.replace(x, '1', '<1>'), words)
100 loops, best of 3: 5.09 ms per loop
In [4]: %timeit replaced = map(lambda x: x.replace('1', '<1>'), words)
100 loops, best of 3: 4.39 ms per loop
In [5]: import re
In [6]: r = re.compile('1')
In [7]: %timeit replaced = [r.sub('<1>', w) for w in words]
100 loops, best of 3: 6.15 ms per loop
as you can see for such simple patterns the accepted list comprehension is the fastest, but look at the following:
In [8]: %timeit replaced = [w.replace('1', '<1>').replace('324', '<324>').replace('567', '<567>') for w in words]
100 loops, best of 3: 8.25 ms per loop
In [9]: r = re.compile('(1|324|567)')
In [10]: %timeit replaced = [r.sub('<\1>', w) for w in words]
100 loops, best of 3: 7.87 ms per loop
This shows that for more complicated substitutions a pre-compiled reg-exp (as in 9-10
) can be (much) faster. It really depends on your problem and the shortest part of the reg-exp.
# Copy the certificate into the directory Java_home\Jre\Lib\Security
# Change your directory to Java_home\Jre\Lib\Security>
# Import the certificate to a trust store.
keytool -import -alias ca -file somecert.cer -keystore cacerts -storepass changeit [Return]
Trust this certificate: [Yes]
changeit is the default truststore password
For store associative arrays you can use serialize
:
$arr = array(
'a' => 1,
'b' => 2,
'c' => 3
);
file_put_contents('stored-array.txt', serialize($arr));
And load using unserialize
:
$arr = unserialize(file_get_contents('stored-array.txt'));
print_r($arr);
But if need creat dinamic .php
files with array (for example config files), you can use var_export(..., true);
, like this:
Save in file:
$arr = array(
'a' => 1,
'b' => 2,
'c' => 3
);
$str = preg_replace('#,(\s+|)\)#', '$1)', var_export($arr, true));
$str = '<?php' . PHP_EOL . 'return ' . $str . ';';
file_put_contents('config.php', $str);
Get array values:
$arr = include 'config.php';
print_r($arr);
you can use document.document.querySelectorAll("#divId")
This path worked for me. on a 32 bit machine.
C:\Windows\System32\mmc.exe /32 C:\Windows\system32\SQLServerManager10.msc
await setTimeout(()=>{}, 200);
Will work if your Node version is 15 and above.
var currencyInput = document.querySelector('input[type="currency"]')
var currency = 'USD' // https://www.currency-iso.org/dam/downloads/lists/list_one.xml
// format inital value
onBlur({target:currencyInput})
// bind event listeners
currencyInput.addEventListener('focus', onFocus)
currencyInput.addEventListener('blur', onBlur)
function localStringToNumber( s ){
return Number(String(s).replace(/[^0-9.-]+/g,""))
}
function onFocus(e){
var value = e.target.value;
e.target.value = value ? localStringToNumber(value) : ''
}
function onBlur(e){
var value = e.target.value
var options = {
maximumFractionDigits : 2,
currency : currency,
style : "currency",
currencyDisplay : "symbol"
}
e.target.value = value
? localStringToNumber(value).toLocaleString(undefined, options)
: ''
}
_x000D_
input{
padding: 10px;
font: 20px Arial;
width: 70%;
}
_x000D_
<input type='currency' value="123" placeholder='Type a number & click outside' />
_x000D_
var part = location.hostname.split('.');
var subdomains = part.shift();
var upperleveldomains = part.join('.');
second-level-domain, you might use
var sleveldomain = parts.slice(-2).join('.');
The .NET documentation says: State Property: A bitwise combination of the ConnectionState values
So I think you should check
!myConnection.State.HasFlag(ConnectionState.Open)
instead of
myConnection.State != ConnectionState.Open
because State can have multiple flags.
I have found this to be really useful:
df = pd.DataFrame({'A' : range(0,10) * 2, 'B' : np.random.randint(20,30,20)})
# A ascending, B descending
df.sort(**skw(columns=['A','-B']))
# A descending, B ascending
df.sort(**skw(columns=['-A','+B']))
Note that unlike the standard columns=,ascending=
arguments, here column names and their sort order are in the same place. As a result your code gets a lot easier to read and maintain.
Note the actual call to .sort
is unchanged, skw
(sortkwargs) is just a small helper function that parses the columns and returns the usual columns=
and ascending=
parameters for you. Pass it any other sort kwargs as you usually would. Copy/paste the following code into e.g. your local utils.py
then forget about it and just use it as above.
# utils.py (or anywhere else convenient to import)
def skw(columns=None, **kwargs):
""" get sort kwargs by parsing sort order given in column name """
# set default order as ascending (+)
sort_cols = ['+' + col if col[0] != '-' else col for col in columns]
# get sort kwargs
columns, ascending = zip(*[(col.replace('+', '').replace('-', ''),
False if col[0] == '-' else True)
for col in sort_cols])
kwargs.update(dict(columns=list(columns), ascending=ascending))
return kwargs
IntelliJ IDEA 14 & 15 & 2017:
View > Tool Windows > Terminal
or
Alt + F12
Check the setting in your user config /home/username/.netbeans/version/etc/netbeans.conf
I had the problem where I was specifying the location globally, but my user setting was overriding the global setting.
CentOS 7/Netbeans 8.1
I'm not sure what you mean by "then again by the parser". After the splitting has been done, there's no further traversal of the string, only a traversal of the list of split strings. This will probably actually be the fastest way to accomplish this, so long as the size of your string isn't absolutely huge. The fact that python uses immutable strings means that you must always create a new string, so this has to be done at some point anyway.
If your string is very large, the disadvantage is in memory usage: you'll have the original string and a list of split strings in memory at the same time, doubling the memory required. An iterator approach can save you this, building a string as needed, though it still pays the "splitting" penalty. However, if your string is that large, you generally want to avoid even the unsplit string being in memory. It would be better just to read the string from a file, which already allows you to iterate through it as lines.
However if you do have a huge string in memory already, one approach would be to use StringIO, which presents a file-like interface to a string, including allowing iterating by line (internally using .find to find the next newline). You then get:
import StringIO
s = StringIO.StringIO(myString)
for line in s:
do_something_with(line)
Actually, passing a bitmap as a Parcelable will result in a "JAVA BINDER FAILURE" error. Try passing the bitmap as a byte array and building it for display in the next activity.
I shared my solution here:
how do you pass images (bitmaps) between android activities using bundles?
The CSS styles for text input controls such as TextField for JavaFX 8 are defined in the modena.css stylesheet as below. Create a custom CSS stylesheet and modify the colors as you wish. Use the CSS reference guide if you need help understanding the syntax and available attributes and values.
.text-input {
-fx-text-fill: -fx-text-inner-color;
-fx-highlight-fill: derive(-fx-control-inner-background,-20%);
-fx-highlight-text-fill: -fx-text-inner-color;
-fx-prompt-text-fill: derive(-fx-control-inner-background,-30%);
-fx-background-color: linear-gradient(to bottom, derive(-fx-text-box-border, -10%), -fx-text-box-border),
linear-gradient(from 0px 0px to 0px 5px, derive(-fx-control-inner-background, -9%), -fx-control-inner-background);
-fx-background-insets: 0, 1;
-fx-background-radius: 3, 2;
-fx-cursor: text;
-fx-padding: 0.333333em 0.583em 0.333333em 0.583em; /* 4 7 4 7 */
}
.text-input:focused {
-fx-highlight-fill: -fx-accent;
-fx-highlight-text-fill: white;
-fx-background-color:
-fx-focus-color,
-fx-control-inner-background,
-fx-faint-focus-color,
linear-gradient(from 0px 0px to 0px 5px, derive(-fx-control-inner-background, -9%), -fx-control-inner-background);
-fx-background-insets: -0.2, 1, -1.4, 3;
-fx-background-radius: 3, 2, 4, 0;
-fx-prompt-text-fill: transparent;
}
Although using an external stylesheet is a preferred way to do the styling, you can style inline, using something like below:
textField.setStyle("-fx-text-inner-color: red;");
Used this :)
$days = (strtotime($endDate) - strtotime($startDate)) / (60 * 60 * 24);
print $days;
Now it works
I think that you should make the reference to your config file
26399:C 16 Jan 08:51:13.413 # Warning: no config file specified, using the default config. In order to specify a config file use ./redis-server /path/to/redis.conf
you can try to start your redis server like
./redis-server /path/to/redis-stable/redis.conf
valgrind (only avail for *nix platforms) is a very nice memory checker
A full instruction relating to James Fletcher's answer can be found here
Particularly for Anaconda distribution I had to modify it this way:
cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D PYTHON3_PACKAGES_PATH=/anaconda/lib/python3.4/site-packages/ \
-D PYTHON3_LIBRARY=/anaconda/lib/libpython3.4m.dylib \
-D PYTHON3_INCLUDE_DIR=/anaconda/include/python3.4m \
-D INSTALL_C_EXAMPLES=ON \
-D INSTALL_PYTHON_EXAMPLES=ON \
-D BUILD_EXAMPLES=ON \
-D BUILD_opencv_python3=ON \
-D OPENCV_EXTRA_MODULES_PATH=../opencv_contrib/modules ..
Last line can be ommited (see link above)
you can put this tag into your html.
<button class='btn btn-primary' onfocus='this.blur'>
Button Text
</button>
I used on focus because onclick still displayed the glow for a microsecond and made a horrible looking flash in terms of using it. This seemed to get rid after all the css methods failed.
I have added screenshots of a working environment, because it cost me several hours of R&D.
First, add a key to your launch.json
file.
See the below screenshot, I have added Development
as my environment.
Then, in your project, create a new appsettings.{environment}.json
file that includes the name of the environment.
In the following screenshot, look for two different files with the names:
appsettings.Development.Json
appSetting.json
And finally, configure it to your StartUp
class like this:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
And at last, you can run it from the command line like this:
dotnet run --environment "Development"
where "Development"
is the name of my environment.
At least in the current versions of PHPMailers, there's a function clearReplyTos() to empty the reply-to array.
$mail->ClearReplyTos();
$mail->addReplyTo([email protected], 'EXAMPLE');
No one mentioned the short form of the .format
method:
Needs at least Python 3.6
f"{Decimal('40800000000.00000000000000'):.2E}"
(I believe it's the same as Cees Timmerman, just a bit shorter)
Technically, you will be sending these headers through the connect function before the protocol upgrade phase. This worked for me in a nodejs
project:
var WebSocketClient = require('websocket').client;
var ws = new WebSocketClient();
ws.connect(url, '', headers);
What I do is I try to reset hard to HEAD. This will wipe out all the local commits:
git reset --hard HEAD^
This one I found simple solutions:
row = myArray.map((cell, i) => {
if (i == myArray.length - 1) {
return <div> Test Data 1</div>;
}
return <div> Test Data 2</div>;
});
This SO answer might help in this case.
If the main project already references the resource project, then you could just explicitly work with your generated-resource class in your code, and access its ResourceManager
from that. Hence, something along the lines of:
ResourceManager resMan = YeagerTechResources.Resources.ResourceManager;
// then, you could go on working with that
ResourceSet resourceSet = resMan.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
// ...
You could convert the dataframe to be a single column with stack
(this changes the shape from 5x3 to 15x1) and then take the standard deviation:
df.stack().std() # pandas default degrees of freedom is one
Alternatively, you can use values
to convert from a pandas dataframe to a numpy array before taking the standard deviation:
df.values.std(ddof=1) # numpy default degrees of freedom is zero
Unlike pandas, numpy will give the standard deviation of the entire array by default, so there is no need to reshape before taking the standard deviation.
A couple of additional notes:
The numpy approach here is a bit faster than the pandas one, which is generally true when you have the option to accomplish the same thing with either numpy or pandas. The speed difference will depend on the size of your data, but numpy was roughly 10x faster when I tested a few different sized dataframes on my laptop (numpy version 1.15.4 and pandas version 0.23.4).
The numpy and pandas approaches here will not give exactly the same answers, but will be extremely close (identical at several digits of precision). The discrepancy is due to slight differences in implementation behind the scenes that affect how the floating point values get rounded.
Something like this?
>>> st = "hello world"
>>> ' '.join(format(ord(x), 'b') for x in st)
'1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100'
#using `bytearray`
>>> ' '.join(format(x, 'b') for x in bytearray(st, 'utf-8'))
'1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100'
Another Way That worked for me is to Subclass UINavigationBar And leave the drawRect Method empty !!
@IBDesignable class MONavigationBar: UINavigationBar {
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}}
<script type="text/javascript">
function iframeDidLoad() {
alert('Done');
}
function newSite() {
var sites = ['http://getprismatic.com',
'http://gizmodo.com/',
'http://lifehacker.com/']
document.getElementById('myIframe').src = sites[Math.floor(Math.random() * sites.length)];
}
</script>
<input type="button" value="Change site" onClick="newSite()" />
<iframe id="myIframe" src="http://getprismatic.com/" onLoad="iframeDidLoad();"></iframe>
Example at http://jsfiddle.net/MALuP/
You should get the array like in $_POST['id']. So you should be able to do this:
foreach ($_POST['id'] as $key => $value) {
echo $value . "<br />";
}
Input names should be same:
<input name='id[]' type='checkbox' value='1'>
<input name='id[]' type='checkbox' value='2'>
...
That is not possible. A function that has a non-void return type (even if it's Void
) has to return a value. However you could add static methods to Action
that allows you to "create" a Action
:
interface Action<T, U> {
U execute(T t);
public static Action<Void, Void> create(Runnable r) {
return (t) -> {r.run(); return null;};
}
public static <T, U> Action<T, U> create(Action<T, U> action) {
return action;
}
}
That would allow you to write the following:
// create action from Runnable
Action.create(()-> System.out.println("Hello World")).execute(null);
// create normal action
System.out.println(Action.create((Integer i) -> "number: " + i).execute(100));
This is one "trick" you can do since your out of an async function so can't use await keywork
Do what you want to do with vm.feed inside a setTimeout
vm.feed = getFeed().then(function(data) {return data;});
setTimeout(() => {
// do you stuf here
// after the time you promise will be revolved or rejected
// if you need some of the values in here immediately out of settimeout
// might occur an error if promise wore not yet resolved or rejected
console.log("vm.feed",vm.feed);
}, 100);
Parsing PKCS1 (only PKCS8 format works out of the box on Android) key turned out to be a tedious task on Android because of the lack of ASN1 suport, yet solvable if you include Spongy castle jar to read DER Integers.
String privKeyPEM = key.replace(
"-----BEGIN RSA PRIVATE KEY-----\n", "")
.replace("-----END RSA PRIVATE KEY-----", "");
// Base64 decode the data
byte[] encodedPrivateKey = Base64.decode(privKeyPEM, Base64.DEFAULT);
try {
ASN1Sequence primitive = (ASN1Sequence) ASN1Sequence
.fromByteArray(encodedPrivateKey);
Enumeration<?> e = primitive.getObjects();
BigInteger v = ((DERInteger) e.nextElement()).getValue();
int version = v.intValue();
if (version != 0 && version != 1) {
throw new IllegalArgumentException("wrong version for RSA private key");
}
/**
* In fact only modulus and private exponent are in use.
*/
BigInteger modulus = ((DERInteger) e.nextElement()).getValue();
BigInteger publicExponent = ((DERInteger) e.nextElement()).getValue();
BigInteger privateExponent = ((DERInteger) e.nextElement()).getValue();
BigInteger prime1 = ((DERInteger) e.nextElement()).getValue();
BigInteger prime2 = ((DERInteger) e.nextElement()).getValue();
BigInteger exponent1 = ((DERInteger) e.nextElement()).getValue();
BigInteger exponent2 = ((DERInteger) e.nextElement()).getValue();
BigInteger coefficient = ((DERInteger) e.nextElement()).getValue();
RSAPrivateKeySpec spec = new RSAPrivateKeySpec(modulus, privateExponent);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey pk = kf.generatePrivate(spec);
} catch (IOException e2) {
throw new IllegalStateException();
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
} catch (InvalidKeySpecException e) {
throw new IllegalStateException(e);
}
A more elegant way for Don Wakefield method:
#include <iostream>
#include <fstream>
using namespace std;
int main(){
int tSize = 0, resident = 0, share = 0;
ifstream buffer("/proc/self/statm");
buffer >> tSize >> resident >> share;
buffer.close();
long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages
double rss = resident * page_size_kb;
cout << "RSS - " << rss << " kB\n";
double shared_mem = share * page_size_kb;
cout << "Shared Memory - " << shared_mem << " kB\n";
cout << "Private Memory - " << rss - shared_mem << "kB\n";
return 0;
}
Just like with nextSibling and nextElementSibling, just remember that, properties with "element" in their name always returns Element
or null
. Properties without can return any other kind of node.
console.log(document.body.parentNode, "is body's parent node"); // returns <html>
console.log(document.body.parentElement, "is body's parent element"); // returns <html>
var html = document.body.parentElement;
console.log(html.parentNode, "is html's parent node"); // returns document
console.log(html.parentElement, "is html's parent element"); // returns null
After you granted the permissions to the specified user you have to do this at filtering:
First step:
Second step:
Now you will be able to display the tables after you changed the default load Alter session to the desire schema (using a Trigger after LOG ON).
Give below command it will add in migration file on its own
rails g migration RemoveColumnFromModel
After running above command you can check migration file remove_column code must be added there on its own
Then migrate the db
rake db:migrate
If you are using Ant and trying to build then you need to :
Specify tomcat location by <property name="tomcat-home" value="C:\xampp\tomcat" />
Add tomcat libs to your already defined path for jars by
<path id="libs">
<fileset includes="*.jar" dir="${WEB-INF}/lib" />
<fileset includes="*.jar" dir="${tomcat-home}/bin" />
<fileset includes="*.jar" dir="${tomcat-home}/lib" />
</path>
I know I'm a bit late to this, but in case you wanted to perform relative padding (aka edge padding), here's how you can implement it. Note that the very first instance of assignment results in zero-padding, so you can use this for both zero-padding and relative padding (this is where you copy the edge values of the original array into the padded array).
def replicate_padding(arr):
"""Perform replicate padding on a numpy array."""
new_pad_shape = tuple(np.array(arr.shape) + 2) # 2 indicates the width + height to change, a (512, 512) image --> (514, 514) padded image.
padded_array = np.zeros(new_pad_shape) #create an array of zeros with new dimensions
# perform replication
padded_array[1:-1,1:-1] = arr # result will be zero-pad
padded_array[0,1:-1] = arr[0] # perform edge pad for top row
padded_array[-1, 1:-1] = arr[-1] # edge pad for bottom row
padded_array.T[0, 1:-1] = arr.T[0] # edge pad for first column
padded_array.T[-1, 1:-1] = arr.T[-1] # edge pad for last column
#at this point, all values except for the 4 corners should have been replicated
padded_array[0][0] = arr[0][0] # top left corner
padded_array[-1][0] = arr[-1][0] # bottom left corner
padded_array[0][-1] = arr[0][-1] # top right corner
padded_array[-1][-1] = arr[-1][-1] # bottom right corner
return padded_array
The optimal solution for this is numpy's pad method.
After averaging for 5 runs, np.pad with relative padding is only 8%
better than the function defined above. This shows that this is fairly an optimal method for relative and zero-padding padding.
#My method, replicate_padding
start = time.time()
padded = replicate_padding(input_image)
end = time.time()
delta0 = end - start
#np.pad with edge padding
start = time.time()
padded = np.pad(input_image, 1, mode='edge')
end = time.time()
delta = end - start
print(delta0) # np Output: 0.0008790493011474609
print(delta) # My Output: 0.0008130073547363281
print(100*((delta0-delta)/delta)) # Percent difference: 8.12316715542522%
You will need to customise the control quite a lot to achieve this.
Please follow the guide at: http://www.quirksmode.org/dom/inputfile.html
The simplest way that doesn't require third party libraries it to create a URL object and then call either openConnection or openStream on it. Note that this is a pretty basic API, so you won't have a lot of control over the headers.
I have had to unpack a .ab
-file, too and found this post while looking for an answer. My suggested solution is Android Backup Extractor, a free Java tool for Windows, Linux and Mac OS.
Make sure to take a look at the README, if you encounter a problem. You might have to download further files, if your .ab
-file is password-protected.
Usage:java -jar abe.jar [-debug] [-useenv=yourenv] unpack <backup.ab> <backup.tar> [password]
Example:
Let's say, you've got a file test.ab
, which is not password-protected, you're using Windows and want the resulting .tar
-Archive to be called test.tar
. Then your command should be:
java.exe -jar abe.jar unpack test.ab test.tar ""
Use below command to create a package.json file.
npm init
npm init --yes or -y flag
[This method will generate a default package.json using information extracted from the current directory.]
Try below code
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners
android:bottomLeftRadius="30dp"
android:bottomRightRadius="30dp"
android:topLeftRadius="30dp"
android:topRightRadius="30dp" />
<solid android:color="#1271BB" />
<stroke
android:width="5dp"
android:color="#1271BB" />
<padding
android:bottom="1dp"
android:left="1dp"
android:right="1dp"
android:top="1dp" /></shape>
Copied from the stacktrace:
BeanInstantiationException: Could not instantiate bean class [com.gestEtu.project.model.dao.CompteDAOHib]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.gestEtu.project.model.dao.CompteDAOHib.<init>()
By default, Spring will try to instantiate beans by calling a default (no-arg) constructor. The problem in your case is that the implementation of the CompteDAOHib
has a constructor with a SessionFactory
argument. By adding the @Autowired
annotation to a constructor, Spring will attempt to find a bean of matching type, SessionFactory
in your case, and provide it as a constructor argument, e.g.
@Autowired
public CompteDAOHib(SessionFactory sessionFactory) {
// ...
}
For lists or dicts, the answer is more clear, according to http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#default-parameter-values use None as default parameter.
But also for strings, a (empty) string object is instanciated at runtime for the keyword parameter.
The cleanest way is probably:
def myfunc(self, my_string=None):
self.my_string = my_string or "" # or a if-else-branch, ...
Another possibility of making.
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#0000ff")));
You probably need to specify which rows you want to update...
UPDATE
mytable
SET
column1 = value1,
column2 = value2
WHERE
key_value = some_value;
I am posting an update to this old thread. I found one solution that worked, but requires opening each file. I opened my csv file in LibreOffice, chose Save As > edit filter settings. In the drop-down menu I chose UTF8 encoding. Then I added encoding="utf-8-sig"
to the data = pd.read_csv(r'C:\fullpathtofile\filename.csv', sep = ',', encoding="utf-8-sig")
.
Hope this helps someone.
Use:
Target= "_blank" property of anchor tag
Check this out! It was built no longer ago in 2014.
Get a list of country/state/city in a hierarchy using geonames webservice
From requests 2.4.2 (https://pypi.python.org/pypi/requests), the "json" parameter is supported. No need to specify "Content-Type". So the shorter version:
requests.post('http://httpbin.org/post', json={'test': 'cheers'})
To convert any JSON to array, use the below code:
const usersJson: any[] = Array.of(res.json());
I, too, have need for this! My situation involves comparing actuals with budget for cost centers, where expenses may have been mis-applied and therefore need to be re-allocated to the correct cost center so as to match how they were budgeted. It is very time consuming to try and scan row-by-row to see if each expense item has been correctly allocated. I decided that I should apply conditional formatting to highlight any cells where the actuals did not match the budget. I set up the conditional formatting to change the background color if the actual amount under the cost center did not match the budgeted amount.
Here's what I did:
Start in cell A1 (or the first cell you want to have the formatting). Open the Conditional Formatting dialogue box and select Apply formatting based on a formula. Then, I wrote a formula to compare one cell to another to see if they match:
=A1=A50
If the contents of cells A1 and A50 are equal, the conditional formatting will be applied. NOTICE: no $$, so the cell references are RELATIVE! Therefore, you can copy the formula from cell A1 and PasteSpecial (format). If you only click on the cells that you reference as you write your conditional formatting formula, the cells are by default locked, so then you wouldn't be able to apply them anywhere else (you would have to write out a new rule for each line- YUK!)
What is really cool about this is that if you insert rows under the conditionally formatted cell, the conditional formatting will be applied to the inserted rows as well!
Something else you could also do with this: Use ISBLANK if the amounts are not going to be exact matches, but you want to see if there are expenses showing up in columns where there are no budgeted amounts (i.e., BLANK) .
This has been a real time-saver for me. Give it a try and enjoy!
I also had this problem, and none of the solutions in this thread worked for me. As it turns out, the problem was that I had this line in ~/.bash_profile
:
alias php="/usr/local/php/bin/php"
And, as it turns out, /usr/local/php
was just a symlink to /usr/local/Cellar/php54/5.4.24/
. So when I invoked php -i
I was still invoking php54. I just deleted this line from my bash profile, and then php worked.
For some reason, even though php55 was now running, the php.ini
file from php54 was still loaded, and I received this warning every time I invoked php:
PHP Warning: PHP Startup: Unable to load dynamic library '/usr/local/Cellar/php54/5.4.38/lib/php/extensions/no-debug-non-zts-20100525/memcached.so' - dlopen(/usr/local/Cellar/php54/5.4.38/lib/php/extensions/no-debug-non-zts-20100525/memcached.so, 9): image not found in Unknown on line 0
To fix this, I just added the following line to my bash profile:
export PHPRC=/usr/local/etc/php/5.5/php.ini
And then everything worked as normal!
It is just a typo(I guess)-
p+=1;
instead of p +1=p;
is required .
As name suggest lvalue
expression should be left-hand operand of the assignment operator.
multipart/form-data
is used when you want to upload files to the server. Please check this article for details.
Can use CSS to show error message only on error.
.form-group.has-error .help-block {
display: block;
}
.form-group .help-block {
display: none;
}
<div class="form-group has-error">
<label class="control-label" for="inputError">Input with error</label>
<input type="text" class="form-control" id="inputError">
<span class="help-block">Please correct the error</span>
</div>
$sql = "select count(*) as row from login WHERE firstname = '" . $username . "' AND password = '" . $password . "'";
$query = $this->db->query($sql);
print_r($query);exit;
if ($query->num_rows() == 1) {
return true;
} else {
return false;
}
we can use append and pop to do it
def rev(s):
i = list(s)
o = list()
while len(i) > 0:
o.append(t.pop())
return ''.join(o)
Just an addition to @Andy Hayden's answer:
Since DataFrame.mask
is the opposite twin of DataFrame.where
, they have the exactly same signature but with opposite meaning:
DataFrame.where
is useful for Replacing values where the condition is False. DataFrame.mask
is used for Replacing values where the condition is True.So in this question, using df.mask(df.isna(), other=None, inplace=True)
might be more intuitive.
I got tired of waiting for this to get built into SVN. I was using tortoiseSVN with ignore-on-commit, but that pops up a user dialog box that you can't suppress from the command line, and when I run my build script and go and make a cup of tea, I hate it when I come back to discover it's waiting for user input 10% of the way through.
So here's a windows powershell script that commits only files that aren't in a changelist:
# get list of changed files into targets
[XML]$svnStatus = svn st -q --xml C:\SourceCode\Monad
# select the nodes that aren't in a changelist
$fileList = $svnStatus.SelectNodes('/status/target/entry[wc-status/@item != "unversioned"]') | Foreach-Object {$_.path};
# create a temp file of targets
$fileListPath = [IO.Path]::GetTempFileName();
$fileList | out-file $fileListPath -Encoding ASCII
# do the commit
svn commit --targets $fileListPath -m "Publish $version" --keep-changelists
# remove the temp file
Remove-Item $filelistPath
If you are using jupyter notebook, You can remove it like this:
pip uninstall notebook
You should use conda uninstall if you installed it with conda.
On many source packages (e.g. for most GNU software), the building system may know about the DESTDIR
make variable, so you can often do:
make install DESTDIR=/tmp/myinst/
sudo cp -va /tmp/myinst/ /
The advantage of this approach is that make install
don't need to run as root, so you cannot end up with files compiled as root (or root-owned files in your build tree).
According to this SO link you can print a specific div with
w=window.open();
w.document.write(document.getElementsByClassName('report_left_inner')[0].innerH??TML);
w.print();
w.close();
Thank you very much for the replies!
Saggi Malachi, that query unfortunately sums the invoice amount in cases where there is more than one payment. Say there are two payments to a $39 invoice of $18 and $12. So rather than ending up with a result that looks like:
1 39.00 9.00
You'll end up with:
1 78.00 48.00
Charles Bretana, in the course of trimming my query down to the simplest possible query I (stupidly) omitted an additional table, customerinvoices, which provides a link between customers and invoices. This can be used to see invoices for which payments haven't made.
After much struggling, I think that the following query returns what I need it to:
SELECT DISTINCT i.invoiceid, i.amount, ISNULL(i.amount - p.amount, i.amount) AS amountdue
FROM invoices i
LEFT JOIN invoicepayments ip ON i.invoiceid = ip.invoiceid
LEFT JOIN customerinvoices ci ON i.invoiceid = ci.invoiceid
LEFT JOIN (
SELECT invoiceid, SUM(p.amount) amount
FROM invoicepayments ip
LEFT JOIN payments p ON ip.paymentid = p.paymentid
GROUP BY ip.invoiceid
) p
ON p.invoiceid = ip.invoiceid
LEFT JOIN payments p2 ON ip.paymentid = p2.paymentid
LEFT JOIN customers c ON ci.customerid = c.customerid
WHERE c.customernumber='100'
Would you guys concur?
Not an answer to the original question, but an example to the how-to-make-reusable and working custom renderers without breaking MVC :-)
// WRONG
public class DataWrapper {
final Data data;
final String description;
public DataWrapper(Object data, String description) {
this.data = data;
this.description = description;
}
....
@Override
public String toString() {
return description;
}
}
// usage
myModel.add(new DataWrapper(data1, data1.getName());
It is wrong in a MVC environment, because it is mixing data and view: now the model doesn't contain the data but a wrapper which is introduced for view reasons. That's breaking separation of concerns and encapsulation (every class interacting with the model needs to be aware of the wrapped data).
The driving forces for breaking of rules were:
As in Swing a custom renderer is the small coin designed to accomodate for custom visual representation, a default manager which can't cope is ... broken. Tweaking design just to accommodate for such a crappy default is the wrong way round, kind of upside-down. The correct is, to implement a coping manager.
While re-use is fine, doing so at the price of breaking the basic architecture is not a good bargin.
We have a problem in the presentation realm, let's solve it in the presentation realm with the elements designed to solve exactly that problem. As you might have guessed, SwingX already has such a solution :-)
In SwingX, the provider of a string representation is called StringValue, and all default renderers take such a StringValue to configure themselves:
StringValue sv = new StringValue() {
@Override
public String getString(Object value) {
if (value instanceof Data) {
return ((Data) value).getSomeProperty();
}
return TO_STRING.getString(value);
}
};
DefaultListRenderer renderer = new DefaultListRenderer(sv);
As the defaultRenderer is-a StringValue (implemented to delegate to the given), a well-behaved implementation of KeySelectionManager now can delegate to the renderer to find the appropriate item:
public BetterKeySelectionManager implements KeySelectionManager {
@Override
public int selectionForKey(char ch, ComboBoxModel model) {
....
if (getCellRenderer() instance of StringValue) {
String text = ((StringValue) getCellRenderer()).getString(model.getElementAt(row));
....
}
}
}
Outlined the approach because it is easily implementable even without using SwingX, simply define implement something similar and use it:
All except the string provider is reusable as-is (that is exactly one implemenation of the custom renderer and the keySelectionManager). There can be general implementations of the string provider, f.i. those formatting value or using bean properties via reflection. And all without breaking basic rules :-)
And using the joiner
from http://jinja.pocoo.org/docs/dev/templates/#joiner
{% set comma = joiner(",") %}
{% for user in userlist %}
{{ comma() }}<a href="/profile/{{ user }}/">{{ user }}</a>
{% endfor %}
It's made for this exact purpose. Normally a join or a check of forloop.last would suffice for a single list, but for multiple groups of things it's useful.
A more complex example on why you would use it.
{% set pipe = joiner("|") %}
{% if categories %} {{ pipe() }}
Categories: {{ categories|join(", ") }}
{% endif %}
{% if author %} {{ pipe() }}
Author: {{ author() }}
{% endif %}
{% if can_edit %} {{ pipe() }}
<a href="?action=edit">Edit</a>
{% endif %}
MS-DOS Editor (or just edit
) is a 16-bit text editor that is still included with 32-bit versions of Windows XP, Vista, 7, 8 and 8.1. It can edit files upto 65,279 lines long and has mouse support. Being an 16-bit DOS editor, it cannot run directly on 64-bit versions of Windows. It can be launched by typing edit
at the command prompt.
pcntl_fork
won't work in a web server environment if it has safe mode turned on. In this case, it will only work in the CLI version of PHP.
if your int variable is declared as a class level variable (instance variable) it would be defaulted to 0. But that does not indicate if the value sent from the client was 0 or a null. may be you could have a setter method which could be called to initialize/set the value sent by the client. then you can define your indicator value , may be a some negative value to indicate the null..
Work with vectors is usually most effective to contact String.
I suggest the following function:
String.prototype.replaceAt=function(index, char) {
var a = this.split("");
a[index] = char;
return a.join("");
}
Run this snippet:
String.prototype.replaceAt=function(index, char) {_x000D_
var a = this.split("");_x000D_
a[index] = char;_x000D_
return a.join("");_x000D_
}_x000D_
_x000D_
var str = "hello world";_x000D_
str = str.replaceAt(3, "#");_x000D_
_x000D_
document.write(str);
_x000D_
Wrote the below function that allows me to quickly check to see if an index exists; works just like OBJECT_ID.
CREATE FUNCTION INDEX_OBJECT_ID (
@tableName VARCHAR(128),
@indexName VARCHAR(128)
)
RETURNS INT
AS
BEGIN
DECLARE @objectId INT
SELECT @objectId = i.object_id
FROM sys.indexes i
WHERE i.object_id = OBJECT_ID(@tableName)
AND i.name = @indexName
RETURN @objectId
END
GO
EDIT: This just returns the OBJECT_ID of the table, but it will be NULL if the index doesn't exist. I suppose you could set this to return index_id, but that isn't super useful.
There are a number of times you might consider using an interface over an abstract implementation
Generally speaking, interfaces were introduced to overcome the lack of multiple inheritancy, amongst other things
Invalid Example:
function findAll() {
$query=<<<SQL
SELECT * FROM `table_1`;
SQL;
// ... omitted
}
This will throw an exception that resembles the following:
<br />
<b>Parse error</b>: syntax error, unexpected end of file in <b>[...][...]</b> on line <b>5</b><br />
where number 5 might be the last line number of your file.
According to php manual:
Warning It is very important to note that the line with the closing identifier must contain no other characters, except a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs before or after the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by the local operating system. This is \n on UNIX systems, including macOS. The closing delimiter must also be followed by a newline.
TLDR: Closing identifiers should NOT be indented.
Valid Example:
function findAll() {
$query=<<<SQL
SELECT * FROM `table_1`;
SQL;
// closing identifier should not be indented, although it might look ugly
// ... omitted
}
I've just downloaded SQL Developer 4.0 for OS X (10.9), it just got out of beta. I also downloaded the latest Postgres JDBC jar. On a lark I decided to install it (same method as other third party db drivers in SQL Dev), and it accepted it. Whenever I click "new connection", there is a tab now for Postgres... and clicking it shows a panel that asks for the database connection details.
The answer to this question has changed, whether or not it is supported, it seems to work. There is a "choose database" button, that if clicked, gives you a dropdown list filled with available postgres databases. You create the connection, open it, and it lists the schemas in that database. Most postgres commands seem to work, though no psql commands (\list, etc).
Those who need a single tool to connect to multiple database engines can now use SQL Developer.
I'm not sure about changing the tint vs the background color but this is how you change the tint color of the Navigation Bar:
Try this code..
[navigationController.navigationBar setTintColor:[UIColor redColor];
//Red as an example.
I'm new to powershell but this seems to be most effective:
doSomething -arg myArg
if (-not $?) {throw "Failed to doSomething"}
It seems you have to use is null
in the HQL, (which can lead to complex permutations if there are more than one parameters with null potential.) but here is a possible solution:
String statusTerm = status==null ? "is null" : "= :status";
String typeTerm = type==null ? "is null" : "= :type";
Query query = getSession().createQuery("from CountryDTO c where c.status " + statusTerm + " and c.type " + typeTerm);
if(status!=null){
query.setParameter("status", status, Hibernate.STRING)
}
if(type!=null){
query.setParameter("type", type, Hibernate.STRING)
}
If you are still getting that error after installing the 64 bit JRE, it means that the JVM running Gurobi package is still using the 32 bit JRE.
Check that you have updated the PATH and JAVA_HOME globally and in the command shell that you are using. (Maybe you just need to exit and restart it.)
Check that your command shell runs the right version of Java by running "java -version" and checking that it says it is a 64bit JRE.
If you are launching the example via a wrapper script / batch file, make sure that the script is using the right JRE. Modify as required ...
I want to add a "late" answer, because I struggled with change
, keyup
and search
today, and maybe what I found in the end may be useful for others too.
Basically, I have a search-as-type panel, and I just wanted to react properly to the press of the little X (under Chrome and Opera, FF does not implement it), and clear a content pane as a result.
I had this code:
$(some-input).keyup(function() {
// update panel
}
$(some-input).change(function() {
// update panel
}
$(some-input).on("search", function() {
// update panel
}
(They are separate because I wanted to check when and under which circumstances each was called).
It turns out that Chrome and Firefox react differently.
In particular, Firefox treats change
as "every change to the input", while Chrome treats it as "when focus is lost AND the content is changed".
So, on Chrome the "update panel" function was called once, on FF twice for every keystroke (one in keyup
, one in change
)
Additionally, clearing the field with the small X (which is not present under FF) fired the search
event under Chrome: no keyup
, no change
.
The conclusion? Use input
instead:
$(some-input).on("input", function() {
// update panel
}
It works with the same behaviour under all the browsers I tested, reacting at every change in the input content (copy-paste with the mouse, autocompletion and "X" included).
Updated to use the more modern Luxon instead of MomentJS.
Don't reinvent the wheel. Use a tried and tested library do this for you, Luxon for example: https://moment.github.io/luxon/index.html
From their site:
//=> 'Thu, Apr 20, 11:27 AM'
DateTime.local().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' });
Try:
SELECT convert(datetime, '23/07/2009', 103)
this is British/French standard.
Try this code
$(document).ready(function(){
$('.sendButton').attr('disabled',true);
$('#message').keyup(function(){
if($(this).val().length !=0){
$('.sendButton').attr('disabled', false);
}
else
{
$('.sendButton').attr('disabled', true);
}
})
});
Check demo Fiddle
You are missing the else part of the if statement (to disable the button again if textbox is empty) and parentheses ()
after val
function in if($(this).val.length !=0){
You can check for empty string (when stderr is empty)
- name: Check script
shell: . {{ venv_name }}/bin/activate && myscritp.py
args:
chdir: "{{ home }}"
sudo_user: "{{ user }}"
register: test_myscript
- debug: msg='myscritp is Ok'
when: test_myscript.stderr == ""
If you want to check for fail:
- debug: msg='myscritp has error: {{test_myscript.stderr}}'
when: test_myscript.stderr != ""
Also look at this stackoverflow question
You need to close the connection before you can use the output parameters. Something like this
con.Close();
MessageBox.Show(cmd.Parameters["@code"].Value.ToString());
I just solved this and wanted to share. This works with Bootstrap 4. It works with img
but I didn't test it with video
. Here is the HAML and SCSS
HAML
.container
.detail-img.d-flex.align-items-center
%img{src: 'http://placehold.it/1000x700'}
SCSS
.detail-img { // simulate background: center/cover
max-height: 400px;
overflow: hidden;
img {
width: 100%;
}
}
/* simulate background: center/cover */_x000D_
.center-cover { _x000D_
max-height: 400px;_x000D_
overflow: hidden;_x000D_
_x000D_
}_x000D_
_x000D_
.center-cover img {_x000D_
width: 100%;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="container">_x000D_
<div class="center-cover d-flex align-items-center">_x000D_
<img src="http://placehold.it/1000x700">_x000D_
</div>_x000D_
</div>
_x000D_
Edit:
This method should no longer be needed with the arrival of MVC 3, as it will be handled automatically - http://weblogs.asp.net/scottgu/archive/2010/07/27/introducing-asp-net-mvc-3-preview-1.aspx
You can use this ObjectFilter:
public class ObjectFilter : ActionFilterAttribute {
public string Param { get; set; }
public Type RootType { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext) {
if ((filterContext.HttpContext.Request.ContentType ?? string.Empty).Contains("application/json")) {
object o =
new DataContractJsonSerializer(RootType).ReadObject(filterContext.HttpContext.Request.InputStream);
filterContext.ActionParameters[Param] = o;
}
}
}
You can then apply it to your controller methods like so:
[ObjectFilter(Param = "postdata", RootType = typeof(ObjectToSerializeTo))]
public JsonResult ControllerMethod(ObjectToSerializeTo postdata) { ... }
So basically, if the content type of the post is "application/json" this will spring into action and will map the values to the object of type you specify.
Ned Rockson basically answers this question. However there is a fatal flaw within his solution. When the targeted element is closer to the bottom of the page than the viewport-height, the function doesn't reach its exit statement and traps the user on the bottom of the page. This is simply solved by limiting the iteration count.
var smoothScroll = function(elementId) {
var MIN_PIXELS_PER_STEP = 16;
var MAX_SCROLL_STEPS = 30;
var target = document.getElementById(elementId);
var scrollContainer = target;
do {
scrollContainer = scrollContainer.parentNode;
if (!scrollContainer) return;
scrollContainer.scrollTop += 1;
} while (scrollContainer.scrollTop == 0);
var targetY = 0;
do {
if (target == scrollContainer) break;
targetY += target.offsetTop;
} while (target = target.offsetParent);
var pixelsPerStep = Math.max(MIN_PIXELS_PER_STEP,
(targetY - scrollContainer.scrollTop) / MAX_SCROLL_STEPS);
var iterations = 0;
var stepFunc = function() {
if(iterations > MAX_SCROLL_STEPS){
return;
}
scrollContainer.scrollTop =
Math.min(targetY, pixelsPerStep + scrollContainer.scrollTop);
if (scrollContainer.scrollTop >= targetY) {
return;
}
window.requestAnimationFrame(stepFunc);
};
window.requestAnimationFrame(stepFunc);
}
Download source code from here (https://deepshikhapuri.wordpress.com/2017/04/24/open-pdf-file-from-sdcard-in-android-programmatically/)
activity_main.xml:
<?xml version=”1.0" encoding=”utf-8"?>
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:tools=”http://schemas.android.com/tools”
android:id=”@+id/activity_main”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:background=”#efefef”>
<ListView
android:layout_width=”match_parent”
android:id=”@+id/lv_pdf”
android:divider=”#efefef”
android:layout_marginLeft=”10dp”
android:layout_marginRight=”10dp”
android:layout_marginTop=”10dp”
android:layout_marginBottom=”10dp”
android:dividerHeight=”5dp”
android:layout_height=”wrap_content”>
</ListView>
</RelativeLayout>
MainActivity.java:
package com.pdffilefromsdcard;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity {
ListView lv_pdf;
public static ArrayList<File> fileList = new ArrayList<File>();
PDFAdapter obj_adapter;
public static int REQUEST_PERMISSIONS = 1;
boolean boolean_permission;
File dir;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
lv_pdf = (ListView) findViewById(R.id.lv_pdf);
dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
fn_permission();
lv_pdf.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), PdfActivity.class);
intent.putExtra(“position”, i);
startActivity(intent);
Log.e(“Position”, i + “”);
}
});
}
public ArrayList<File> getfile(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null && listFile.length > 0) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
getfile(listFile[i]);
} else {
boolean booleanpdf = false;
if (listFile[i].getName().endsWith(“.pdf”)) {
for (int j = 0; j < fileList.size(); j++) {
if (fileList.get(j).getName().equals(listFile[i].getName())) {
booleanpdf = true;
} else {
}
}
if (booleanpdf) {
booleanpdf = false;
} else {
fileList.add(listFile[i]);
}
}
}
}
}
return fileList;
}
private void fn_permission() {
if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE))) {
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);
}
} else {
boolean_permission = true;
getfile(dir);
obj_adapter = new PDFAdapter(getApplicationContext(), fileList);
lv_pdf.setAdapter(obj_adapter);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSIONS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
boolean_permission = true;
getfile(dir);
obj_adapter = new PDFAdapter(getApplicationContext(), fileList);
lv_pdf.setAdapter(obj_adapter);
} else {
Toast.makeText(getApplicationContext(), “Please allow the permission”, Toast.LENGTH_LONG).show();
}
}
}
}
activity_pdf.xml:
<?xml version=”1.0" encoding=”utf-8"?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”match_parent”
android:background=”#ffffff”
android:layout_height=”match_parent”
android:orientation=”vertical”>
<com.github.barteksc.pdfviewer.PDFView
android:id=”@+id/pdfView”
android:layout_margin=”10dp”
android:layout_width=”match_parent”
android:layout_height=”match_parent” />
</LinearLayout>
PdfActivity.java:
package com.pdffilefromsdcard;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
import com.shockwave.pdfium.PdfDocument;
import java.io.File;
import java.util.List;
public class PdfActivity extends AppCompatActivity implements OnPageChangeListener,OnLoadCompleteListener {
PDFView pdfView;
Integer pageNumber = 0;
String pdfFileName;
String TAG=”PdfActivity”;
int position=-1;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf);
init();
}
private void init(){
pdfView= (PDFView)findViewById(R.id.pdfView);
position = getIntent().getIntExtra(“position”,-1);
displayFromSdcard();
}
private void displayFromSdcard() {
pdfFileName = MainActivity.fileList.get(position).getName();
pdfView.fromFile(MainActivity.fileList.get(position))
.defaultPage(pageNumber)
.enableSwipe(true)
.swipeHorizontal(false)
.onPageChange(this)
.enableAnnotationRendering(true)
.onLoad(this)
.scrollHandle(new DefaultScrollHandle(this))
.load();
}
@Override
public void onPageChanged(int page, int pageCount) {
pageNumber = page;
setTitle(String.format(“%s %s / %s”, pdfFileName, page + 1, pageCount));
}
@Override
public void loadComplete(int nbPages) {
PdfDocument.Meta meta = pdfView.getDocumentMeta();
printBookmarksTree(pdfView.getTableOfContents(), “-“);
}
public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
for (PdfDocument.Bookmark b : tree) {
Log.e(TAG, String.format(“%s %s, p %d”, sep, b.getTitle(), b.getPageIdx()));
if (b.hasChildren()) {
printBookmarksTree(b.getChildren(), sep + “-“);
}
}
}
}
Thanks!
I tested bits and pieces of the following, but not the complete rule set in its entirety, so if you run into trouble with it let me know and I'll dig around a bit more. However, assuming I got everything correct, you could try something like the following:
RewriteEngine On
# Check if this is the noredirect query string
RewriteCond %{QUERY_STRING} (^|&)noredirect=true(&|$)
# Set a cookie, and skip the next rule
RewriteRule ^ - [CO=mredir:0:%{HTTP_HOST},S]
# Check if this looks like a mobile device
# (You could add another [OR] to the second one and add in what you
# had to check, but I believe most mobile devices should send at
# least one of these headers)
RewriteCond %{HTTP:x-wap-profile} !^$ [OR]
RewriteCond %{HTTP:Profile} !^$
# Check if we're not already on the mobile site
RewriteCond %{HTTP_HOST} !^m\.
# Check to make sure we haven't set the cookie before
RewriteCond %{HTTP:Cookie} !\smredir=0(;|$)
# Now redirect to the mobile site
RewriteRule ^ http://m.example.org%{REQUEST_URI} [R,L]
Below is an implementation I use to intercept each HTTP request before it goes out and the response which comes back. With this implementation, I also have a single point where I can pass any header value with the request.
public class HttpInterceptor implements ClientHttpRequestInterceptor {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public ClientHttpResponse intercept(
HttpRequest request, byte[] body,
ClientHttpRequestExecution execution
) throws IOException {
HttpHeaders headers = request.getHeaders();
headers.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE);
headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
traceRequest(request, body);
ClientHttpResponse response = execution.execute(request, body);
traceResponse(response);
return response;
}
private void traceRequest(HttpRequest request, byte[] body) throws IOException {
logger.info("===========================Request begin======================================");
logger.info("URI : {}", request.getURI());
logger.info("Method : {}", request.getMethod());
logger.info("Headers : {}", request.getHeaders() );
logger.info("Request body: {}", new String(body, StandardCharsets.UTF_8));
logger.info("==========================Request end=========================================");
}
private void traceResponse(ClientHttpResponse response) throws IOException {
logger.info("============================Response begin====================================");
logger.info("Status code : {}", response.getStatusCode());
logger.info("Status text : {}", response.getStatusText());
logger.info("Headers : {}", response.getHeaders());
logger.info("=======================Response end===========================================");
}}
Below is the Rest Template Bean
@Bean
public RestTemplate restTemplate(HttpClient httpClient)
{
HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemplate= new RestTemplate(requestFactory);
List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
if (CollectionUtils.isEmpty(interceptors))
{
interceptors = new ArrayList<>();
}
interceptors.add(new HttpInterceptor());
restTemplate.setInterceptors(interceptors);
return restTemplate;
}
sudo apt-get install php5-mcrypt
ln -s /etc/php5/mods-available/mcrypt.ini /etc/php5/fpm/conf.d/mcrypt.ini
service php5-fpm restart
service nginx restart
The idea of retrying the query in case of Deadlock exception is good, but it can be terribly slow, since mysql query will keep waiting for locks to be released. And incase of deadlock mysql is trying to find if there is any deadlock, and even after finding out that there is a deadlock, it waits a while before kicking out a thread in order to get out from deadlock situation.
What I did when I faced this situation is to implement locking in your own code, since it is the locking mechanism of mysql is failing due to a bug. So I implemented my own row level locking in my java code:
private HashMap<String, Object> rowIdToRowLockMap = new HashMap<String, Object>();
private final Object hashmapLock = new Object();
public void handleShortCode(Integer rowId)
{
Object lock = null;
synchronized(hashmapLock)
{
lock = rowIdToRowLockMap.get(rowId);
if (lock == null)
{
rowIdToRowLockMap.put(rowId, lock = new Object());
}
}
synchronized (lock)
{
// Execute your queries on row by row id
}
}
I found that my version of Xcode was too outdated and installing command-line-tools wasn't helping. Here's what I did:
Destructors provide an implicit way of freeing unmanaged resources encapsulated in your class, they get called when the GC gets around to it and they implicitly call the Finalize method of the base class. If you're using a lot of unmanaged resources it is better to provide an explicit way of freeing those resources via the IDisposable interface. See the C# programming guide: http://msdn.microsoft.com/en-us/library/66x5fx1b.aspx
With using the inline-block it will behave as an inline object. so no floats needed to get them next to eachother on one line. And indeed as Rito said, floats need a "body", like they need dimensions.
I totally agree with Pekka about using tables. Everybody that build layouts using div's avoid tables like it's a desease. But use them for tablular data! That's what they're ment for. And in your case i think you need them :)
BUT if you really really want what you want. There is a css hack way. Same as the float hack.
.kundregister_grid_1:after { content: "."; }
Add that one and you're also set :D (Note: does not work in IE, but that is fixable)
Just call each section of the accordion as its own accordion. active: n will be 0 for the first one( so it will display) and 1, 2, 3, 4, etc for the rest. Since each one is it's own accordion, they will all have only 1 section, and the rest will be collapsed to start.
$('.accordian').each(function(n, el) {
$(el).accordion({
heightStyle: 'content',
collapsible: true,
active: n
});
});
Question content may have changed, so I'll try to answer thoroughly.
Destructuring allows you to pull values out of anything with properties. You can also define default values when null/undefined and name aliases.
const options = {
filters : {
firstName : "abc"
}
}
const {filters: {firstName = "John", lastName = "Smith"}} = options
// firstName = "abc"
// lastName = "Smith"
NOTE: Capitalization matters
If working with an array, here is how you do it.
In this case, name is extracted from each object in the array, and given its own alias. Since the object might not exist = {}
was also added.
const options = {
filters: [{
name: "abc",
value: "lots"
}]
}
const {filters:[{name : filter1 = "John"} = {}, {name : filter2 = "Smith"} = {}]} = options
// filter1 = "abc"
// filter2 = "Smith"
Browser Support 92% July 2020
just compiled your code and the only thing that is missing from it is that you have to Bind your ddl2 to an empty datasource before binding it again like this:
Protected Sub ddl1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) //ddl2.Items.Clear()
ddl2.DataSource=New List(Of String)() ddl2.DataSource = sql2 ddl2.DataBind() End Sub
and it worked just fine
From jacoco:prepare-agent that says:
One of the ways to do this in case of maven-surefire-plugin - is to use syntax for late property evaluation:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <argLine>@{argLine} -your -extra -arguments</argLine> </configuration> </plugin>
Note the @{argLine}
that's added to -your -extra -arguments
.
Thanks Slava Semushin for noticing the change and reporting in the comment.
Following jacoco:prepare-agent that says:
[org.jacoco:jacoco-maven-plugin:0.7.2-SNAPSHOT:prepare-agent] Prepares a property pointing to the JaCoCo runtime agent that can be passed as a VM argument to the application under test. Depending on the project packaging type by default a property with the following name is set:
- tycho.testArgLine for packaging type eclipse-test-plugin and
- argLine otherwise.
Note that these properties must not be overwritten by the test configuration, otherwise the JaCoCo agent cannot be attached. If you need custom parameters please append them. For example:
<argLine>${argLine} -your -extra -arguments</argLine>
Resulting coverage information is collected during execution and by default written to a file when the process terminates.
you should change the following line in maven-surefire-plugin
plugin configuration from (note the ${argLine}
inside <argLine>
):
<argLine>-Xmx2048m</argLine>
to
<argLine>${argLine} -Xmx2048m</argLine>
Make also the necessary changes to the other plugin maven-failsafe-plugin
and replace the following (again, notice the ${argLine}
):
<argLine>-Xmx4096m -XX:MaxPermSize=512M ${itCoverageAgent}</argLine>
to
<argLine>${argLine} -Xmx4096m -XX:MaxPermSize=512M ${itCoverageAgent}</argLine>
It might also be worth mentioning that inline will try to open Office Documents (xls, doc etc) directly from the server, which might lead to a User Credentials Prompt.
see this link:
http://forums.asp.net/t/1885657.aspx/1?Access+the+SSRS+Report+in+excel+format+on+server
somebody tried to deliver an Excel Report from SSRS via ASP.Net -> the user always got prompted to enter the credentials. After clicking cancel on the prompt it would be opened anyway...
If the Content Disposition is marked as Attachment it will automatically be saved to the temp folder after clicking open and then opened in Excel from the local copy.
You have to forgo the regex literal and use the object constructor, where you can pass the regex as a string.
var regex = new RegExp(pattern1+'|'+pattern2, 'gi');
str.match(regex);
display: block;
text-align: center;
DECIMAL TO BINARY NO ARRAYS USED *made by Oya:
I'm still a beginner, so this code will only use loops and variables xD...
Hope you like it. This can probably be made simpler than it is...
#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
int main()
{
int i;
int expoentes; //the sequence > pow(2,i) or 2^i
int decimal;
int extra; //this will be used to add some 0s between the 1s
int x = 1;
cout << "\nThis program converts natural numbers into binary code\nPlease enter a Natural number:";
cout << "\n\nWARNING: Only works until ~1.073 millions\n";
cout << " To exit, enter a negative number\n\n";
while(decimal >= 0){
cout << "\n----- // -----\n\n";
cin >> decimal;
cout << "\n";
if(decimal == 0){
cout << "0";
}
while(decimal >= 1){
i = 0;
expoentes = 1;
while(decimal >= expoentes){
i++;
expoentes = pow(2,i);
}
x = 1;
cout << "1";
decimal -= pow(2,i-x);
extra = pow(2,i-1-x);
while(decimal < extra){
cout << "0";
x++;
extra = pow(2,i-1-x);
}
}
}
return 0;
}
All other answers here depends on adding code the the notebook(!)
In my opinion is bad practice to hardcode a specific path into the notebook code, or otherwise depend on the location, since this makes it really hard to refactor you code later on. Instead I would recommend you to add the root project folder to PYTHONPATH when starting up your Jupyter notebook server, either directly from the project folder like so
env PYTHONPATH=`pwd` jupyter notebook
or if you are starting it up from somewhere else, use the absolute path like so
env PYTHONPATH=/Users/foo/bar/project/ jupyter notebook
You can save String and custom array list using Gson library.
=>First you need to create function to save array list to SharedPreferences.
public void saveListInLocal(ArrayList<String> list, String key) {
SharedPreferences prefs = getSharedPreferences("AppName", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
editor.putString(key, json);
editor.apply(); // This line is IMPORTANT !!!
}
=> You need to create function to get array list from SharedPreferences.
public ArrayList<String> getListFromLocal(String key)
{
SharedPreferences prefs = getSharedPreferences("AppName", Context.MODE_PRIVATE);
Gson gson = new Gson();
String json = prefs.getString(key, null);
Type type = new TypeToken<ArrayList<String>>() {}.getType();
return gson.fromJson(json, type);
}
=> How to call save and retrieve array list function.
ArrayList<String> listSave=new ArrayList<>();
listSave.add("test1"));
listSave.add("test2"));
saveListInLocal(listSave,"key");
Log.e("saveArrayList:","Save ArrayList success");
ArrayList<String> listGet=new ArrayList<>();
listGet=getListFromLocal("key");
Log.e("getArrayList:","Get ArrayList size"+listGet.size());
=> Don't forgot to add gson library in you app level build.gradle.
implementation 'com.google.code.gson:gson:2.8.2'
As the other responses pointed out, one solution is to install Visual Studio 2015. However, it takes a few GBs of disk space. One way around is to install precompiled binaries. The webpage http://www.lfd.uci.edu/~gohlke/pythonlibs (mirror) contains precompiled binaries for many Python packages. After downloading the package of interest to you, you can install it using pip install
, e.g. pip install mysqlclient-1.3.10-cp35-cp35m-win_amd64.whl
.
If you have problems with numbers (say 1, 2, 10, 12 which will be sorted 1, 10, 12, 2) you can use LINQ:
var arr = arr.OrderBy(x=>x).ToArray();
solution is easy:
replace
mask = (50 < df['heart rate'] < 101 &
140 < df['systolic blood pressure'] < 160 &
90 < df['dyastolic blood pressure'] < 100 &
35 < df['temperature'] < 39 &
11 < df['respiratory rate'] < 19 &
95 < df['pulse oximetry'] < 100
, "excellent", "critical")
by
mask = ((50 < df['heart rate'] < 101) &
(140 < df['systolic blood pressure'] < 160) &
(90 < df['dyastolic blood pressure'] < 100) &
(35 < df['temperature'] < 39) &
(11 < df['respiratory rate'] < 19) &
(95 < df['pulse oximetry'] < 100)
, "excellent", "critical")
Conversion from signed to unsigned does not necessarily just copy or reinterpret the representation of the signed value. Quoting the C standard (C99 6.3.1.3):
When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.
Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.
Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.
For the two's complement representation that's nearly universal these days, the rules do correspond to reinterpreting the bits. But for other representations (sign-and-magnitude or ones' complement), the C implementation must still arrange for the same result, which means that the conversion can't just copy the bits. For example, (unsigned)-1 == UINT_MAX, regardless of the representation.
In general, conversions in C are defined to operate on values, not on representations.
To answer the original question:
unsigned int u = 1234;
int i = -5678;
unsigned int result = u + i;
The value of i is converted to unsigned int, yielding UINT_MAX + 1 - 5678
. This value is then added to the unsigned value 1234, yielding UINT_MAX + 1 - 4444
.
(Unlike unsigned overflow, signed overflow invokes undefined behavior. Wraparound is common, but is not guaranteed by the C standard -- and compiler optimizations can wreak havoc on code that makes unwarranted assumptions.)
The desired result can be obtained using IGrouping, which represents a collection of objects that have a common key in this case a GroupID
var newCustomerList = CustomerList.GroupBy(u => u.GroupID)
.Select(group => new { GroupID = group.Key, Customers = group.ToList() })
.ToList();
have a look at http://au.php.net/reserved.variables
I think the variable you are looking for is: $_SERVER["DOCUMENT_ROOT"]
Well, Apache is HTTP webserver, where as Tomcat is also webserver for Servlets and JSP. Moreover Apache is preferred over Apache Tomcat in real time
http://download.eclipse.org/webtools/updates/ - This is an old URL and doesn't work any more. If you want to install WTP (i.e. J2EE plugins) use the following URLs depending upon the version of the eclipse you are using:
More information can be found here.
This error occur because of path of project. Change your project path wiht way which dont contain nonAscii character.
An example.
$query_new = "INSERT INTO students(courseid, coursename) VALUES ('', ?)";
$query_new = $databaseConnection->prepare($query_new);
$query_new->bind_param('s', $_POST['coursename']);
$query_new->execute();
$course_id = $query_new->insert_id;
$query_new->close();
The code line $course_id = $query_new->insert_id;
will display the ID of the last inserted row.
Hope this helps.
git config [--global] user.name "Full Name"
git config [--global] user.email "[email protected]"
Per repo basis you could also edit .git/config
manually instead.
When performing step 2 if you see credential.helper=manager
you need to open the credential manager of your computer (Win or Mac) and update the credentials there
This problem occurs because of UAC and only when you are running IE on the same computer SSRS is on.
To fix it, you have to add an AD group of the users with read priviledges to the actual SSRS website directories and push the security down. UAC is dumb in how if you are an admin on the box. It won't let you access the data unless you also have access to the data through other means such as a non-administrator AD group that is applied to the files.
Something may have change your proxy setting, like Fiddler. Close Fiddler, then close Visual Studio and open it again.
Why noy just use the theme styles in the table? i.e.
<table>
<thead class="ui-widget-header">
<tr>
<th>Id</th>
<th>Description</th>
</td>
</thead>
<tbody class="ui-widget-content">
<tr>
<td>...</td>
<td>...</td>
</tr>
.
.
.
</tbody>
</table>
And you don't need to use any code...
I was facing the same problem, not it works fine.
just open cmd
cd to the directory where your netbeans setup file is located.
in cmd, write the name of the entire setup file and write --javahome "address of jdk"
hit enter, it will surely solve your problem
for example, if the setup file is: netbeans8.02.exe
and path of JDK is C:/program files/java/jdk9.01
then run the command,
netbeans8.02.exe --javahome "C:/program files/java/jdk9.01"
and hit enter! :-)
In my case, I found that I set the post method as private mistakenly. after changing private to public.
[HttpPost]
private async Task<ActionResult> OnPostRemoveForecasting(){}
change to
[HttpPost]
public async Task<ActionResult> OnPostRemoveForecasting(){}
Now works fine.
Script based on Joe answer (detach, copy files, attach both).
It's not necessary, but maybe access denied error on executing.
EXEC sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
EXEC sp_configure 'xp_cmdshell', 1
GO
RECONFIGURE
GO
@dbName
and @copyDBName
variables before.USE master;
GO
DECLARE @dbName NVARCHAR(255) = 'Products'
DECLARE @copyDBName NVARCHAR(255) = 'Products_branch'
-- get DB files
CREATE TABLE ##DBFileNames([FileName] NVARCHAR(255))
EXEC('
INSERT INTO ##DBFileNames([FileName])
SELECT [filename] FROM ' + @dbName + '.sys.sysfiles')
-- drop connections
EXEC('ALTER DATABASE ' + @dbName + ' SET OFFLINE WITH ROLLBACK IMMEDIATE')
EXEC('ALTER DATABASE ' + @dbName + ' SET SINGLE_USER')
-- detach
EXEC('EXEC sp_detach_db @dbname = ''' + @dbName + '''')
-- copy files
DECLARE @filename NVARCHAR(255), @path NVARCHAR(255), @ext NVARCHAR(255), @copyFileName NVARCHAR(255), @command NVARCHAR(MAX) = ''
DECLARE
@oldAttachCommand NVARCHAR(MAX) =
'CREATE DATABASE ' + @dbName + ' ON ',
@newAttachCommand NVARCHAR(MAX) =
'CREATE DATABASE ' + @copyDBName + ' ON '
DECLARE curs CURSOR FOR
SELECT [filename] FROM ##DBFileNames
OPEN curs
FETCH NEXT FROM curs INTO @filename
WHILE @@FETCH_STATUS = 0
BEGIN
SET @path = REVERSE(RIGHT(REVERSE(@filename),(LEN(@filename)-CHARINDEX('\', REVERSE(@filename),1))+1))
SET @ext = RIGHT(@filename,4)
SET @copyFileName = @path + @copyDBName + @ext
SET @command = 'EXEC master..xp_cmdshell ''COPY "' + @filename + '" "' + @copyFileName + '"'''
PRINT @command
EXEC(@command);
SET @oldAttachCommand = @oldAttachCommand + '(FILENAME = "' + @filename + '"),'
SET @newAttachCommand = @newAttachCommand + '(FILENAME = "' + @copyFileName + '"),'
FETCH NEXT FROM curs INTO @filename
END
CLOSE curs
DEALLOCATE curs
-- attach
SET @oldAttachCommand = LEFT(@oldAttachCommand, LEN(@oldAttachCommand) - 1) + ' FOR ATTACH'
SET @newAttachCommand = LEFT(@newAttachCommand, LEN(@newAttachCommand) - 1) + ' FOR ATTACH'
-- attach old db
PRINT @oldAttachCommand
EXEC(@oldAttachCommand)
-- attach copy db
PRINT @newAttachCommand
EXEC(@newAttachCommand)
DROP TABLE ##DBFileNames