With ES2017 async/await
support, this is how to POST
a JSON payload:
(async () => {_x000D_
const rawResponse = await fetch('https://httpbin.org/post', {_x000D_
method: 'POST',_x000D_
headers: {_x000D_
'Accept': 'application/json',_x000D_
'Content-Type': 'application/json'_x000D_
},_x000D_
body: JSON.stringify({a: 1, b: 'Textual content'})_x000D_
});_x000D_
const content = await rawResponse.json();_x000D_
_x000D_
console.log(content);_x000D_
})();
_x000D_
Can't use ES2017? See @vp_art's answer using promises
The question however is asking for an issue caused by a long since fixed chrome bug.
Original answer follows.
chrome devtools doesn't even show the JSON as part of the request
This is the real issue here, and it's a bug with chrome devtools, fixed in Chrome 46.
That code works fine - it is POSTing the JSON correctly, it just cannot be seen.
I'd expect to see the object I've sent back
that's not working because that is not the correct format for JSfiddle's echo.
The correct code is:
var payload = {
a: 1,
b: 2
};
var data = new FormData();
data.append( "json", JSON.stringify( payload ) );
fetch("/echo/json/",
{
method: "POST",
body: data
})
.then(function(res){ return res.json(); })
.then(function(data){ alert( JSON.stringify( data ) ) })
For endpoints accepting JSON payloads, the original code is correct
In linux terminal you can just type:
$ code run
data
names = ['Prashobh','Abraham','Anil','Sam','Natasha','Marry','Zian','karan']
You can achieve this by creating a simple pipe
<input type="text" [(ngModel)]="queryString" id="search" placeholder="Search to type">
Pipe
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'FilterPipe',
})
export class FilterPipe implements PipeTransform {
transform(value: any, input: string) {
if (input) {
input = input.toLowerCase();
return value.filter(function (el: any) {
return el.toLowerCase().indexOf(input) > -1;
})
}
return value;
}
}
This will filter the result based on the search term
On Centos, RedHat, Fedora and other yum-my systems it is much simpler than the PHP manual suggests:
yum install php-mbstring
service httpd restart
5 Amazing Ways To Underline A TextView In Android - Kotlin/Java & XML
String html = "<u>Underline using Html.fromHtml()</u>";
textview.setText(Html.fromHtml(html));
But Html.fromHtml(String resource) was deprecated in API 24.
So you can use the latest android support library androidx.core.text.HtmlCompat. Before that, you need to include the dependency in your project.
`implementation 'androidx.core:core:1.0.1'`
String html = "<u> 1.1 Underline using HtmlCompat.fromHtml()</u>";
//underline textview using HtmlCompat.fromHtml() method
textview11.setText(HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY));
Using strings.xml,
<string name="underline_text">1.3 <u>Underline using HtmlCompat.fromHtml() and string resource</u></string>
textview13.setText(HtmlCompat.fromHtml(getString(R.string.underline_text), HtmlCompat.FROM_HTML_MODE_LEGACY));
using PaintFlags
textview2.setPaintFlags(textview2.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
textview2.setText("2. Underline using setPaintFlags()");
using SpannableString
`String content1 = "3.1 Underline using SpannableString";
SpannableString spannableString1 = new SpannableString(content1);
spannableString1.setSpan(new UnderlineSpan(), 0, content1.length(), 0);
textview31.setText(spannableString1);`
Another simple solution is to use map()
as follows:
tensor_shape = map(int, my_tensor.shape)
This converts all the Dimension
objects to int
Probably the simplest way is to use curl
for this, there is no need to install any additional packages and it can be configured directly in a request.
Here is an example using gmail smtp server:
curl --url 'smtps://smtp.gmail.com:465' --ssl-reqd \
--mail-from '[email protected]' \
--mail-rcpt '[email protected]' \
--user '[email protected]:YourPassword' \
-T <(echo -e 'From: [email protected]\nTo: [email protected]\nSubject: Curl Test\n\nHello')
Thought I knew I had read about that in the standard; but can't find it. Keeps looking. Old; answering heading; not Q-tex ;P:
The following program would determine that:
#include <stdio.h>
#include <stdint.h>
int is_big_endian(void)
{
union {
uint32_t i;
char c[4];
} e = { 0x01000000 };
return e.c[0];
}
int main(void)
{
printf("System is %s-endian.\n",
is_big_endian() ? "big" : "little");
return 0;
}
You also have this approach; from Quake II:
byte swaptest[2] = {1,0};
if ( *(short *)swaptest == 1) {
bigendien = false;
And !is_big_endian()
is not 100% to be little as it can be mixed/middle.
Believe this can be checked using same approach only change value from 0x01000000
to i.e. 0x01020304
giving:
switch(e.c[0]) {
case 0x01: BIG
case 0x02: MIX
default: LITTLE
But not entirely sure about that one ...
Try this
UPDATE `table` SET `uid` = CASE
WHEN id = 1 THEN 2952
WHEN id = 2 THEN 4925
WHEN id = 3 THEN 1592
ELSE `uid`
END
WHERE id in (1,2,3)
Remember that a single =
is always an assignment in C or C++.
Your test should be if ( match == 0 && k == M )
you made a typo on the k == M
test.
If you really mean k=M
(i.e. a side-effecting assignment inside a test) you should for readability reasons code if (match == 0 && (k=m) != 0)
but most coding rules advise not writing that.
BTW, your mistake suggests to ask for all warnings (e.g. -Wall
option to g++
), and to upgrade to recent compilers. The next GCC 4.8 will give you:
% g++-trunk -Wall -c ederman.cc
ederman.cc: In function ‘void foo()’:
ederman.cc:9:30: error: lvalue required as left operand of assignment
if ( match == 0 && k = M )
^
and Clang 3.1 also tells you ederman.cc:9:30: error: expression is not assignable
So use recent versions of free compilers and enable all the warnings when using them.
Linux (and indeed Unix) gives you a third option.
Create a standalone executable which handles some part (or all parts) of your application, and invoke it separately for each process, e.g. the program runs copies of itself to delegate tasks to.
Create a standalone executable which starts up with a single thread and create additional threads to do some tasks
Only available under Linux/Unix, this is a bit different. A forked process really is its own process with its own address space - there is nothing that the child can do (normally) to affect its parent's or siblings address space (unlike a thread) - so you get added robustness.
However, the memory pages are not copied, they are copy-on-write, so less memory is usually used than you might imagine.
Consider a web server program which consists of two steps:
If you used threads, step 1 would be done once, and step 2 done in multiple threads. If you used "traditional" processes, steps 1 and 2 would need to be repeated for each process, and the memory to store the configuration and runtime data duplicated. If you used fork(), then you can do step 1 once, and then fork(), leaving the runtime data and configuration in memory, untouched, not copied.
So there are really three choices.
Creating colnames with iterating
df = pd.DataFrame(columns=['colname_' + str(i) for i in range(5)])
print(df)
# Empty DataFrame
# Columns: [colname_0, colname_1, colname_2, colname_3, colname_4]
# Index: []
to_html()
operations
print(df.to_html())
# <table border="1" class="dataframe">
# <thead>
# <tr style="text-align: right;">
# <th></th>
# <th>colname_0</th>
# <th>colname_1</th>
# <th>colname_2</th>
# <th>colname_3</th>
# <th>colname_4</th>
# </tr>
# </thead>
# <tbody>
# </tbody>
# </table>
this seems working
print(type(df.to_html()))
# <class 'str'>
when you create df like this
df = pd.DataFrame(columns=COLUMN_NAMES)
it has 0 rows × n columns
, you need to create at least one row index by
df = pd.DataFrame(columns=COLUMN_NAMES, index=[0])
now it has 1 rows × n columns
. You are be able to add data. Otherwise its df that only consist colnames object(like a string list).
i have same issue this work fine for me
<style>
td{
word-break: break-word;
}
</style>
<table style="width: 100%;">
<tr>
<td>Loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong word</td>
<td><span style="display: inline;">Short word</span></td>
</tr>
</table>
from item in db.vw_Dropship_OrderItems
where (listStatus != null ? listStatus.Contains(item.StatusCode) : true) &&
(listMerchants != null ? listMerchants.Contains(item.MerchantId) : true)
select item;
Might give strange behavior if both listMerchants and listStatus are both null.
request.getContextPath()-
returns root path of your application, while
../
- returns parent directory of a file.
You use request.getContextPath(), as it will always points to root of your application. If you were to move your jsp file from one directory to another, nothing needs to be changed. Now, consider the second approach. If you were to move your jsp files from one folder to another, you'd have to make changes at every location where you are referring your files.
Also, better approach of using request.getContextPath() will be to set 'request.getContextPath()' in a variable and use that variable for referring your path.
<c:set var="context" value="${pageContext.request.contextPath}" />
<script src="${context}/themes/js/jquery.js"></script>
PS- This is the one reason I can figure out. Don't know if there is any more significance to it.
I don't think you can do this in XML (at least not in Android), but I've found a good solution posted here that looks like it'd be a great help!
ShapeDrawable.ShaderFactory sf = new ShapeDrawable.ShaderFactory() {
@Override
public Shader resize(int width, int height) {
LinearGradient lg = new LinearGradient(0, 0, width, height,
new int[]{Color.GREEN, Color.GREEN, Color.WHITE, Color.WHITE},
new float[]{0,0.5f,.55f,1}, Shader.TileMode.REPEAT);
return lg;
}
};
PaintDrawable p=new PaintDrawable();
p.setShape(new RectShape());
p.setShaderFactory(sf);
Basically, the int array allows you to select multiple color stops, and the following float array defines where those stops are positioned (from 0 to 1). You can then, as stated, just use this as a standard Drawable.
Edit: Here's how you could use this in your scenario. Let's say you have a Button defined in XML like so:
<Button
android:id="@+id/thebutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Press Me!"
/>
You'd then put something like this in your onCreate() method:
Button theButton = (Button)findViewById(R.id.thebutton);
ShapeDrawable.ShaderFactory sf = new ShapeDrawable.ShaderFactory() {
@Override
public Shader resize(int width, int height) {
LinearGradient lg = new LinearGradient(0, 0, 0, theButton.getHeight(),
new int[] {
Color.LIGHT_GREEN,
Color.WHITE,
Color.MID_GREEN,
Color.DARK_GREEN }, //substitute the correct colors for these
new float[] {
0, 0.45f, 0.55f, 1 },
Shader.TileMode.REPEAT);
return lg;
}
};
PaintDrawable p = new PaintDrawable();
p.setShape(new RectShape());
p.setShaderFactory(sf);
theButton.setBackground((Drawable)p);
I cannot test this at the moment, this is code from my head, but basically just replace, or add stops for the colors that you need. Basically, in my example, you would start with a light green, fade to white slightly before the center (to give a fade, rather than a harsh transition), fade from white to mid green between 45% and 55%, then fade from mid green to dark green from 55% to the end. This may not look exactly like your shape (Right now, I have no way of testing these colors), but you can modify this to replicate your example.
Edit: Also, the 0, 0, 0, theButton.getHeight()
refers to the x0, y0, x1, y1 coordinates of the gradient. So basically, it starts at x = 0 (left side), y = 0 (top), and stretches to x = 0 (we're wanting a vertical gradient, so no left to right angle is necessary), y = the height of the button. So the gradient goes at a 90 degree angle from the top of the button to the bottom of the button.
Edit: Okay, so I have one more idea that works, haha. Right now it works in XML, but should be doable for shapes in Java as well. It's kind of complex, and I imagine there's a way to simplify it into a single shape, but this is what I've got for now:
green_horizontal_gradient.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
>
<corners
android:radius="3dp"
/>
<gradient
android:angle="0"
android:startColor="#FF63a34a"
android:endColor="#FF477b36"
android:type="linear"
/>
</shape>
half_overlay.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
>
<solid
android:color="#40000000"
/>
</shape>
layer_list.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list
xmlns:android="http://schemas.android.com/apk/res/android"
>
<item
android:drawable="@drawable/green_horizontal_gradient"
android:id="@+id/green_gradient"
/>
<item
android:drawable="@drawable/half_overlay"
android:id="@+id/half_overlay"
android:top="50dp"
/>
</layer-list>
test.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
>
<TextView
android:id="@+id/image_test"
android:background="@drawable/layer_list"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:gravity="center"
android:text="Layer List Drawable!"
android:textColor="@android:color/white"
android:textStyle="bold"
android:textSize="26sp"
/>
</RelativeLayout>
Okay, so basically I've created a shape gradient in XML for the horizontal green gradient, set at a 0 degree angle, going from the top area's left green color, to the right green color. Next, I made a shape rectangle with a half transparent gray. I'm pretty sure that could be inlined into the layer-list XML, obviating this extra file, but I'm not sure how. But okay, then the kind of hacky part comes in on the layer_list XML file. I put the green gradient as the bottom layer, then put the half overlay as the second layer, offset from the top by 50dp. Obviously you'd want this number to always be half of whatever your view size is, though, and not a fixed 50dp. I don't think you can use percentages, though. From there, I just inserted a TextView into my test.xml layout, using the layer_list.xml file as my background. I set the height to 100dp (twice the size of the offset of the overlay), resulting in the following:
Tada!
One more edit: I've realized you can just embed the shapes into the layer list drawable as items, meaning you don't need 3 separate XML files any more! You can achieve the same result combining them like so:
layer_list.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list
xmlns:android="http://schemas.android.com/apk/res/android"
>
<item>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
>
<corners
android:radius="3dp"
/>
<gradient
android:angle="0"
android:startColor="#FF63a34a"
android:endColor="#FF477b36"
android:type="linear"
/>
</shape>
</item>
<item
android:top="50dp"
>
<shape
android:shape="rectangle"
>
<solid
android:color="#40000000"
/>
</shape>
</item>
</layer-list>
You can layer as many items as you like this way! I may try to play around and see if I can get a more versatile result through Java.
I think this is the last edit...: Okay, so you can definitely fix the positioning through Java, like the following:
TextView tv = (TextView)findViewById(R.id.image_test);
LayerDrawable ld = (LayerDrawable)tv.getBackground();
int topInset = tv.getHeight() / 2 ; //does not work!
ld.setLayerInset(1, 0, topInset, 0, 0);
tv.setBackgroundDrawable(ld);
However! This leads to yet another annoying problem in that you cannot measure the TextView until after it has been drawn. I'm not quite sure yet how you can accomplish this...but manually inserting a number for topInset does work.
I lied, one more edit
Okay, found out how to manually update this layer drawable to match the height of the container, full description can be found here. This code should go in your onCreate() method:
final TextView tv = (TextView)findViewById(R.id.image_test);
ViewTreeObserver vto = tv.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
LayerDrawable ld = (LayerDrawable)tv.getBackground();
ld.setLayerInset(1, 0, tv.getHeight() / 2, 0, 0);
}
});
And I'm done! Whew! :)
here is a test script to run on your server to see what is reliabel.
<?php
$host = gethostname();
$ip = gethostbyname($host);
echo "gethostname and gethostbyname: $host at $ip<br>";
$server = $_SERVER['SERVER_ADDR'];
echo "_SERVER[SERVER_ADDR]: $server<br>";
$my_current_ip=exec("ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'");
echo "exec ifconfig ... : $my_current_ip<br>";
$external_ip = file_get_contents("http://ipecho.net/plain");
echo "get contents ipecho.net: $external_ip<br>";
?>
The only different option in there is using fiel_get_contents rather than curl for the extrernal website lookup.
This is the result of hitting the web page on a shared hosting, free account. (actual server name and IP changed)
gethostname and gethostbyname: freesites.servercluster.com at 345.27.413.51
_SERVER[SERVER_ADDR]: 127.0.0.7
exec ifconfig ... :
get contents ipecho.net: 345.27.413.51
Why needed this? Decided to point A record at server to see if it opens the web page. Later ran script to save ip and update on ghost site on same server to lookup IP and alert if changed.
In this case, good results optained by:
gethostname() &
gethostbyname($host)
or
file_get_contents("http://ipecho.net/plain")
Or even shorter, with only standard modern Javascript:
var first_link = document.getElementsByTagName('a')[0];
first_link.dispatchEvent(new MouseEvent('click'));
The new MouseEvent
constructor takes a required event type name, then an optional object (at least in Chrome). So you could, for example, set some properties of the event:
first_link.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true}));
I just want to point out that monetarily you want to round, and not trunc. Being off by a penny is much less likely, since 4.999452 * 100 rounded will give you 5, a more representative answer.
And on top of that, don't forget about banker's rounding, which is a way to counter the slightly positive bias that straight rounding gives -- your financial application may require it.
Avoid nullable unique constraints. You can always put the column in a new table, make it non-null and unique and then populate that table only when you have a value for it. This ensures that any key dependency on the column can be correctly enforced and avoids any problems that could be caused by nulls.
Have a look at: Greybox
It's an awesome version of lightbox that supports forms, external web pages as well as the traditional images and slideshows. It works perfectly from a link on a webpage.
You will find many information on how to use Greybox and also some great examples. Cheers Kara
Without jQuery updated
document.querySelectorAll('.testimonial').forEach(function (element, index) {_x000D_
element.innerHTML = 'Testimonial ' + (index + 1);_x000D_
});
_x000D_
<div class="testimonial"></div>_x000D_
<div class="testimonial"></div>
_x000D_
No Problem You can use onClick()
function easily without using any other interference of language,
<?php
echo '<br><Button onclick="document.getElementById(';?>'modal-wrapper2'<?php echo ').style.display=';?>'block'<?php echo '" name="comment" style="width:100px; color: white;background-color: black;border-radius: 10px; padding: 4px;">Show</button>';
?>
Just to sum up:
I understand much better the output of:
git diff <remote-tracking branch> <local branch>
that shows me what is going to be dropped and what is going to be added if I push the local branch. Of course it is the same, just the inverse, but for me is more readable and I'm more confortable looking at what is going to happen.
@mywolfe02 gives a static range code so his inRange works fine but if you want to add dynamic range then use this one with inRange function of him.this works better with when you want to populate data to fix starting cell and last column is also fixed.
Sub DynamicRange()
Dim sht As Worksheet
Dim LastRow As Long
Dim StartCell As Range
Dim rng As Range
Set sht = Worksheets("xyz")
LastRow = sht.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).row
Set rng = Workbooks("Record.xlsm").Worksheets("xyz").Range(Cells(12, 2), Cells(LastRow, 12))
Debug.Print LastRow
If InRange(ActiveCell, rng) Then
' MsgBox "Active Cell In Range!"
Else
MsgBox "Please select the cell within the range!"
End If
End Sub
This one works for me (Swift UI)
struct DetailView: View {
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var body: some View {
VStack {
Text("This is the detail view")
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
Text("Back")
}
}
}
}
Simply put, an endpoint is one end of a communication channel. When an API interacts with another system, the touch-points of this communication are considered endpoints. For APIs, an endpoint can include a URL of a server or service. Each endpoint is the location from which APIs can access the resources they need to carry out their function.
APIs work using ‘requests’ and ‘responses.’ When an API requests information from a web application or web server, it will receive a response. The place that APIs send requests and where the resource lives, is called an endpoint.
Reference: https://smartbear.com/learn/performance-monitoring/api-endpoints/
Some people like to use the Paint
, CellPainting
or CellFormatting
events, but note that changing a style in these events causes recursive calls. If you use DataBindingComplete
it will execute only once. The argument for CellFormatting
is that it is called only on visible cells, so you don't have to format non-visible cells, but you format them multiple times.
Include input type="file"
element on your HTML page and on the click event of your button trigger the click event of input type file element using trigger function of jQuery
The code will look like:
<input type="file" id="imgupload" style="display:none"/>
<button id="OpenImgUpload">Image Upload</button>
And on the button's click event write the jQuery code like :
$('#OpenImgUpload').click(function(){ $('#imgupload').trigger('click'); });
This will open File Upload Dialog box on your button click event..
You can use pandas it has some built in functions for comparison. So if you want to select values of "A" that are met by the conditions of "B" and "C" (assuming you want back a DataFrame pandas object)
df[['A']][df.B.gt(50) & df.C.ne(900)]
df[['A']]
will give you back column A in DataFrame format.
pandas 'gt' function will return the positions of column B that are greater than 50 and 'ne' will return the positions not equal to 900.
You can also use OrderedDict:
In [183]: from collections import OrderedDict
In [184]: data = OrderedDict()
In [185]: data['one thing'] = [1,2,3,4]
In [186]: data['second thing'] = [0.1,0.2,1,2]
In [187]: data['other thing'] = ['a','e','i','o']
In [188]: frame = pd.DataFrame(data)
In [189]: frame
Out[189]:
one thing second thing other thing
0 1 0.1 a
1 2 0.2 e
2 3 1.0 i
3 4 2.0 o
Faced the same problem running on Windows 10 and using the Windows cmd.
Solved it by running the following command in the Anaconda Prompt which comes with Anaconda3 (as administrator):
conda install -c menpo opencv3=3.1.0
Command found on the official website: https://anaconda.org/menpo/opencv3
You can use setTimeout
to do this
function myFunction() {
// your code to run after the timeout
}
// stop for sometime if needed
setTimeout(myFunction, 5000);
Using toJSON()
date function as below:
var sqlDatetime = new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60 * 1000).toJSON().slice(0, 19).replace('T', ' ');
console.log(sqlDatetime);
_x000D_
You mention "the first one", so I assume that you have some kind of ordering on your data. Let's assume that your data is ordered by some field ID
.
This SQL should get you the duplicate entries except for the first one. It basically selects all rows for which another row with (a) the same fields and (b) a lower ID exists. Performance won't be great, but it might solve your problem.
SELECT A.ID, A.field1, A.field2, A.field3
FROM myTable A
WHERE EXISTS (SELECT B.ID
FROM myTable B
WHERE B.field1 = A.field1
AND B.field2 = A.field2
AND B.field3 = A.field3
AND B.ID < A.ID)
Use this code in your php script (first lines)
ini_set('allow_url_fopen',1);
You cannot set height
and width
for elements with display:inline;
. Use display:inline-block;
instead.
From the CSS2 spec:
10.6.1 Inline, non-replaced elements
The
height
property does not apply. The height of the content area should be based on the font, but this specification does not specify how. A UA may, e.g., use the em-box or the maximum ascender and descender of the font. (The latter would ensure that glyphs with parts above or below the em-box still fall within the content area, but leads to differently sized boxes for different fonts; the former would ensure authors can control background styling relative to the 'line-height', but leads to glyphs painting outside their content area.)
EDIT — You're also missing a ;
terminator for the height
property:
<div style="display:inline; height:20px width: 70px">My Text Here</div>
<!-- ^^ here -->
Working example: http://jsfiddle.net/FpqtJ/
When submitting the data to ASP.NET Web server the controls mentioned as Runat = “server” will be represented as Dot Net objects in Server Application. You can manually type the code in HTML controls or else can use Run As Server option by right clicking in design view. ASP.NET controls will automatically get this attribute once you drag it from toolbox where usually HTML controls don't.
before start make sure of installation:
yum install -y xorg-x11-server-Xorg xorg-x11-xauth xorg-x11-apps
xming
or cygwin
cat /etc/ssh/sshd_config | grep X
X11Forwarding yes
X11DisplayOffset 10
AddressFamily inet
blablaco@blablaco01 ~
$ xhost 192.168.2.223
192.168.2.223 being added to access control list
blablaco@blablaco01 ~
$ ssh -l root 192.168.2.223
[email protected] password:
Last login: Sat May 22 18:59:04 2010 from etcetc
[root@oel5u5 ~]# export DISPLAY=192.168.2.2:0.0
[root@oel5u5 ~]# echo $DISPLAY
192.168.2.2:0.0
[root@oel5u5 ~]# xclock&
Then the xclock application must launch.
Check it on putty or mobaxterm and don't check in remote desktop Manager software. Be careful for user that sudo in.
This helped me: The Owner method basically ties the window to another window in case you want extra windows with the same ones.
LoadingScreen lc = new LoadingScreen();
lc.Owner = this;
lc.Show();
Consider this as well.
this.WindowState = WindowState.Normal;
this.Activate();
For users that are using VB.Net
Imports System.IO
Imports System.Reflection
Dim reader As StreamReader
Dim ass As Assembly = Assembly.GetExecutingAssembly()
Dim sFileName = "MyApplicationName.JavaScript.js"
Dim reader = New StreamReader(ass.GetManifestResourceStream(sFileName))
Dim sScriptText = reader.ReadToEnd()
reader.Close()
where MyApplicationName
is namespace of my application.
It is not the assembly name.
This name is define in project's properties (Application tab).
If you don't find correct resource name, you can use GetManifestResourceNames()
function
Dim resourceName() As String = ass.GetManifestResourceNames()
or
Dim sName As String
= ass.GetManifestResourceNames()
.Single(Function(x) x.EndsWith("JavaScript.js"))
or
Dim sNameList
= ass.GetManifestResourceNames()
.Where(Function(x As String) x.EndsWith(".js"))
Lodash has a "map" function that works just like jQuerys:
var myArr = [{ name: "john", age:23 },_x000D_
{ name: "john", age:43 },_x000D_
{ name: "jimi", age:10 },_x000D_
{ name: "bobi", age:67 }];_x000D_
_x000D_
var johns = _.map(myArr, function(o) {_x000D_
if (o.name == "john") return o;_x000D_
});_x000D_
_x000D_
// Remove undefines from the array_x000D_
johns = _.without(johns, undefined)
_x000D_
The (un)safe way to do this - if you are ok with not using option explicit - is...
Not TypeName(myObj) = "Empty"
This also handles the case if the object has not been declared. This is useful if you want to just comment out a declaration to switch off some behaviour...
Dim myObj as Object
Not TypeName(myObj) = "Empty" '/ true, the object exists - TypeName is Object
'Dim myObj as Object
Not TypeName(myObj) = "Empty" '/ false, the object has not been declared
This works because VBA will auto-instantiate an undeclared variable as an Empty Variant type. It eliminates the need for an auxiliary Boolean to manage the behaviour.
As you are not trying to move the files around in the tree, you should be able to just checkout the directory:
git checkout master -- dirname
action=""
will resolve to the page's address. action="#"
will resolve to the page's address + #
, which will mean an empty fragment identifier.
Doing the latter might prevent a navigation (new load) to the same page and instead try to jump to the element with the id in the fragment identifier. But, since it's empty, it won't jump anywhere.
Usually, authors just put #
in href-like attributes when they're not going to use the attribute where they're using scripting instead. In these cases, they could just use action=""
(or omit it if validation allows).
You can create an alias at your ~/.bash_profile
file:
alias rn-ios="react-native run-ios --simulator \"iPhone 5s (10.0)\""
And then run react-native using the created alias:
$ rn-ios
At the beginning of stored procedure one should put SET XACT_ABORT ON to instruct Sql Server to automatically rollback transaction in case of error. If ommited or set to OFF one needs to test @@ERROR after each statement or use TRY ... CATCH rollback block.
clang has advantages in error reporting & recovery.
$ clang errors.c
errors.c:36:21: warning: result of comparison against a string literal is unspecified (use strcmp instead)
if (args[i] == "&") //WARNING HERE
^~ ~~~
strcmp( , ) == 0
errors.c:38:26: warning: result of comparison against a string literal is unspecified (use strcmp instead)
else if (args[i] == "<") //WARNING HERE
^~ ~~~
strcmp( , ) == 0
errors.c:44:26: warning: result of comparison against a string literal is unspecified (use strcmp instead)
else if (args[i] == ">") //WARNING HERE
^~ ~~~
strcmp( , ) == 0
It suggests to replace x == y
by strcmp(x,y) == 0
.
gengetopt writes command-line option parser for you.
Is the $_SESSION['name'] variable an array? If you want to delete a specific key from within an array, you have to refer to that exact key in the unset() call, otherwise you delete the entire array, e.g.
$name = array(0 => 'a', 1 => 'b', 2 => 'c');
unset($name); // deletes the entire array
unset($name[1]); // deletes only the 'b' entry
Another minor problem with your snippet: You're mixing GET query parameters in with a POST form. Is there any reason why you can't do the forms with 'name' being passed in a hidden field? It's best to not mix get and post variables, especially if you use $_REQUEST elsewhere. You can run into all kinds of fun trying to figure out why $_GET['name'] isn't showing up the same as $_POST['name'], because the server's got a differnt EGPCS order set in the 'variables_order' .ini setting.
<form blah blah blah method="post">
<input type="hidden" name="name" value="<?= htmlspecialchars($list1) ?>" />
<input type="submit" name="add" value="Add />
</form>
And note the htmlspecialchars() call. If either $list1 or $list2 contain a double quote ("), it'll break your HTML
Finally I Try with this. Its worked for me..
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ebook);
//webview use to call own site
webview =(WebView)findViewById(R.id.webView1);
webview.setWebViewClient(new WebViewClient());
webview .getSettings().setJavaScriptEnabled(true);
webview .getSettings().setDomStorageEnabled(true);
webview.loadUrl("http://www.google.com");
}
and your entire main.xml(res/layout) look should like this:
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
don't go to add layouts.
Quite an intuitive error message - just need to give the columns in d names
Change to either this
d as
(
select
[duration] = month(clothdeliverydate),
[bkdqty] = SUM(CONVERT(INT, deliveredqty))
FROM
barcodetable
where
month(clothdeliverydate) is not null
group by month(clothdeliverydate)
)
Or you can explicitly declare the fields in the definition of the cte:
d ([duration], [bkdqty]) as
(
select
month(clothdeliverydate),
SUM(CONVERT(INT, deliveredqty))
FROM
barcodetable
where
month(clothdeliverydate) is not null
group by month(clothdeliverydate)
)
Improve RouMao's solution by temporarily disabling GIT/curl ssl verification in Windows cmd:
set GIT_SSL_NO_VERIFY=true
git config --global http.proxy http://<your-proxy>:443
The good thing about this solution is that it only takes effect in the current cmd window.
In fact I would not use any REDIM, nor a loop for transferring data from sheet to array:
dim arOne()
arOne = range("A2:F1000")
or even
arOne = range("A2").CurrentRegion
and that's it, your array is filled much faster then with a loop, no redim.
I recommend you try to suppress specific warnings by using @SuppressWarnings("squid:S2078")
.
For suppressing multiple warnings you can do it like this @SuppressWarnings({"squid:S2078", "squid:S2076"})
There is also the //NOSONAR
comment that tells SonarQube to ignore all errors for a specific line.
Finally if you have the proper rights for the user interface you can issue a flag as a false positive directly from the interface.
The reason why I recommend suppression of specific warnings is that it's a better practice to block a specific issue instead of using //NOSONAR
and risk a Sonar issue creeping in your code by accident.
You can read more about this in the FAQ
Edit: 6/30/16 SonarQube is now called SonarLint
In case you are wondering how to find the squid number. Just click on the Sonar message (ex. Remove this method to simply inherit it.
) and the Sonar issue will expand.
On the bottom left it will have the squid number (ex. squid:S1185
Maintainability > Understandability)
So then you can suppress it by @SuppressWarnings("squid:S1185")
This worked for me:
location / {
# redirect all HTTP traffic to localhost:8080
proxy_pass http://localhost:8080;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# WebSocket support
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
-- borrowed from: https://github.com/nicokaiser/nginx-websocket-proxy/blob/df67cd92f71bfcb513b343beaa89cb33ab09fb05/simple-wss.conf
A callback is some code that you pass to a given method, so that it can be called at a later time.
In Java one obvious example is java.util.Comparator
. You do not usually use a Comparator
directly; rather, you pass it to some code that calls the Comparator
at a later time:
Example:
class CodedString implements Comparable<CodedString> {
private int code;
private String text;
...
@Override
public boolean equals() {
// member-wise equality
}
@Override
public int hashCode() {
// member-wise equality
}
@Override
public boolean compareTo(CodedString cs) {
// Compare using "code" first, then
// "text" if both codes are equal.
}
}
...
public void sortCodedStringsByText(List<CodedString> codedStrings) {
Comparator<CodedString> comparatorByText = new Comparator<CodedString>() {
@Override
public int compare(CodedString cs1, CodedString cs2) {
// Compare cs1 and cs2 using just the "text" field
}
}
// Here we pass the comparatorByText callback to Collections.sort(...)
// Collections.sort(...) will then call this callback whenever it
// needs to compare two items from the list being sorted.
// As a result, we will get the list sorted by just the "text" field.
// If we do not pass a callback, Collections.sort will use the default
// comparison for the class (first by "code", then by "text").
Collections.sort(codedStrings, comparatorByText);
}
I also had this question, but in my case I didn't want to use a regex, because my JSON value may contain quotation marks. Hopefully my answer will help others in the future.
I solved this issue by using a standard string slice to remove the first and last characters. This works for me, because I used JSON.stringify()
on the textarea
that produced it and as a result, I know that I'm always going to have the "
s at each end of the string.
In this generalized example, response
is the JSON object my AJAX returns, and key
is the name of my JSON key.
response.key.slice(1, response.key.length-1)
I used it like this with a regex replace
to preserve the line breaks and write the content of that key to a paragraph block in my HTML:
$('#description').html(studyData.description.slice(1, studyData.description.length-1).replace(/\\n/g, '<br/>'));
In this case, $('#description')
is the paragraph tag I'm writing to. studyData
is my JSON object, and description
is my key with a multi-line value.
In Node.js, you could use:
console.log('Current directory: ' + process.cwd());
Oracle 10g has functions that allow the use of POSIX-compliant regular expressions in SQL:
See the Oracle Database SQL Reference for syntax details on this functions.
Take a look at Regular expressions in Perl with examples.
Code :
select * from tbl where regexp_like(col, '^(ABC|XYZ|PQR)');
tchester said :
(2) Create a login for the non-sysadmin user that has public access to the master database
I went to my user's database list (server/security/connections/my user name/properties/user mapping, and wanted to check the box for master database. I got an error message telling that the user already exists in the master database. Went to master database, dropped the user, went back to "user mapping" and checked the box for master. Check the "public" box below.
After that, you need to re-issue the grant execute on xp_cmdshell to "my user name"
Yves
With Javascript you can use:
yourtext.substr(0,1).toUpperCase()+yourtext.substr(1);
If by chance you're generating your web page with PHP you can also use:
<?=ucfirst($your_text)?>
This is the cleanest solution there is:
mvn org.apache.maven.plugins:maven-help-plugin:3.2.0:evaluate \
-Dexpression=project.version -q -DforceStdout
Advantages:
pom.xml
Note:
maven-help-plugin
version 3.2.0
(and above) has forceStdout
option. You may replace 3.2.0
in above command with a newer version from the list of available versions of mvn-help-plugin from artifactory, if available.-q
suppresses verbose messages ([INFO]
, [WARN]
etc.)Alternatively, you can add this entry in your pom.xml
, under plugins
section:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-help-plugin</artifactId>
<version>3.2.0</version>
</plugin>
and then run above command compactly as follows:
mvn help:evaluate -Dexpression=project.groupId -q -DforceStdout
If you want to fetch groupId
and artifactId
as well, check this answer.
If you'd prefer a more direct approach, one that does NOT mess with symlinking between /etc/nginx/sites-available
and /etc/nginx/sites-enabled
, do the following:
/etc/nginx/nginx.conf
include /etc/nginx/conf.d/*.conf;
This tells nginx to pull in any files in the conf.d
directory that end in .conf
. (I know: it's weird that a directory can have a .
in it.)conf.d
directory if it doesn't already exist (per the path in step 3). Be sure to give it the right permissions/ownership. Likely root or www-data. /etc/nginx/sites-available
) into the directory conf.d
.Any .conf
files that you put into the conf.d
directory from here on out will become active as long as you reload/restart nginx after.
Note: You can use the conf.d
and sites-enabled
+ sites-available
method concurrently if you wish. I like to test on my dev box using conf.d
. Feels faster than symlinking and unsymlinking.
Some time ago I wrote a format_date
function as this gives many options on how you want your date:
function format_date($date, $type, $seperator="-")
{
if($date)
{
$day = date("j", strtotime($date));
$month = date("n", strtotime($date));
$year = date("Y", strtotime($date));
$hour = date("H", strtotime($date));
$min = date("i", strtotime($date));
$sec = date("s", strtotime($date));
switch($type)
{
case 0: $date = date("Y".$seperator."m".$seperator."d",mktime($hour, $min, $sec, $month, $day, $year)); break;
case 1: $date = date("D, F j, Y",mktime($hour, $min, $sec, $month, $day, $year)); break;
case 2: $date = date("d".$seperator."m".$seperator."Y",mktime($hour, $min, $sec, $month, $day, $year)); break;
case 3: $date = date("d".$seperator."M".$seperator."Y",mktime($hour, $min, $sec, $month, $day, $year)); break;
case 4: $date = date("d".$seperator."M".$seperator."Y h:i A",mktime($hour, $min, $sec, $month, $day, $year)); break;
case 5: $date = date("m".$seperator."d".$seperator."Y",mktime($hour, $min, $sec, $month, $day, $year)); break;
case 6: $date = date("M",mktime($hour, $min, $sec, $month, $day, $year)); break;
case 7: $date = date("Y",mktime($hour, $min, $sec, $month, $day, $year)); break;
case 8: $date = date("j",mktime($hour, $min, $sec, $month, $day, $year)); break;
case 9: $date = date("n",mktime($hour, $min, $sec, $month, $day, $year)); break;
case 10:
$diff = abs(strtotime($date) - strtotime(date("Y-m-d h:i:s")));
$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
$date = $years . " years, " . $months . " months, " . $days . "days";
}
}
return($date);
}
String Integer
without space as String
arr = "12345"
arr.split('')
output: ["1","2","3","4","5"]
String Integer
with space as String
arr = "1 2 3 4 5"
arr.split(' ')
output: ["1","2","3","4","5"]
String Integer
without space as Integer
arr = "12345"
arr.split('').map(&:to_i)
output: [1,2,3,4,5]
arr = "abc"
arr.split('')
output: ["a","b","c"]
Explanation:
arr
-> string which you're going to perform any action.split()
-> is an method, which split the input and store it as array.''
or ' '
or ','
-> is an value, which is needed to be removed from given string.I will choose a simple approach using the dplyr package.
If the dataframe is data.
library(dplyr)
result <- filter(data, three == 11)
I would suggest the method presented on the Gradle forum:
def createMinifyCssTask(def brand, def sourceFile, def destFile) {
return tasks.create("minify${brand}Css", com.eriwen.gradle.css.tasks.MinifyCssTask) {
source = sourceFile
dest = destFile
}
}
I have used this method myself to create custom tasks, and it works very well.
seconds_in_day = 86400
seconds_in_hour = 3600
seconds_in_minute = 60
seconds = int(input("Enter a number of seconds: "))
days = seconds // seconds_in_day
seconds = seconds - (days * seconds_in_day)
hours = seconds // seconds_in_hour
seconds = seconds - (hours * seconds_in_hour)
minutes = seconds // seconds_in_minute
seconds = seconds - (minutes * seconds_in_minute)
print("{0:.0f} days, {1:.0f} hours, {2:.0f} minutes, {3:.0f} seconds.".format(
days, hours, minutes, seconds))
Rebuild All worked for me. VS2013, IIS Express.
If you want to have a one liner without requiring a huge library like lodash, I suggest you to use deepmerge. (npm install deepmerge
)
Then, you can do
deepmerge({ a: 1, b: 2, c: 3 }, { a: 2, d: 3 });
to get
{ a: 2, b: 2, c: 3, d: 3 }
This works nicely with complex objects and arrays. The nice thing is it comes with typings for TypeScript right away. A real all-rounder solution this is.
Try
ALLOWED_HOSTS = ['*']
Less secure if you're not firewalled off or on a public LAN, but it's what I use and it works.
EDIT: Interestingly enough I've been needing to add this to a few of my 1.8 projects even when DEBUG = True
. Very unsure why.
EDIT: This is due to a Django security update as mentioned in my comment.
In workbench 6.0 Connect to any of the database. You will see two tabs.
1.Management
2. Schemas
By default Schemas
tab is selected.
Select Management
tab
then select Data Export
.
You will get list of all databases.
select the desired database and and the file name and ther options you wish and start export.
You are done with backup.
Banging my usual drum solo of JUST TRY IT, here's how you can answer questions like that in the future:
$ cat junk.c
#include <stdio.h>
char* string = "Hello\0";
int main(int argv, char** argc)
{
printf("-->%s<--\n", string);
}
$ gcc -S junk.c
$ cat junk.s
... eliding the unnecessary parts ...
.LC0:
.string "Hello"
.string ""
...
.LC1:
.string "-->%s<--\n"
...
Note here how the string I used for printf is just "-->%s<---\n"
while the global string is in two parts: "Hello"
and ""
. The GNU assembler also terminates strings with an implicit NUL
character, so the fact that the first string (.LC0) is in those two parts indicates that there are two NUL
s. The string is thus 7 bytes long. Generally if you really want to know what your compiler is doing with a certain hunk of code, isolate it in a dummy example like this and see what it's doing using -S
(for GNU -- MSVC has a flag too for assembler output but I don't know it off-hand). You'll learn a lot about how your code works (or fails to work as the case may be) and you'll get an answer quickly that is 100% guaranteed to match the tools and environment you're working in.
With zsh you can do this:
% cat infile
tar
more than one word
gz
java
gz
java
tar
class
class
zsh-5.0.0[t]% print -l "${(fu)$(<infile)}"
tar
more than one word
gz
java
class
Or you can use AWK:
% awk '!_[$0]++' infile
tar
more than one word
gz
java
class
Put the table in a container element that has
overflow:scroll; max-width:95vw;
or make the table fit to the screen and overflow:scroll all table cells.
I won't write your code but what you looking for is something like a jquery dialog
take a look here
$(function() {
$( "#dialog-confirm" ).dialog({
resizable: false,
height:140,
modal: true,
buttons: {
"Delete all items": function() {
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
<div id="dialog-confirm" title="Empty the recycle bin?">
<p>
<span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>
These items will be permanently deleted and cannot be recovered. Are you sure?
</p>
</div>
If you need a counter in an for-each loop you have to count yourself. There is no built in counter as far as I know.
First give your form an id
attribute, then use code like this:
$(document).ready( function() {
var form = $('#my_awesome_form');
form.find('select:first').change( function() {
$.ajax( {
type: "POST",
url: form.attr( 'action' ),
data: form.serialize(),
success: function( response ) {
console.log( response );
}
} );
} );
} );
So this code uses .serialize()
to pull out the relevant data from the form. It also assumes the select you care about is the first one in the form.
For future reference, the jQuery docs are very, very good.
Future.delayed(Duration(seconds: 3) , your_function)
You can use lamba function:
index = df.index[lambda x : for x in df.index() ]
print(index)
For me, I usually use DataContext
together in order to bind two-depth property such as this question.
<TextBlock DataContext="{Binding SelectedRule}" Text="{Binding Name}" />
Or, I prefer to use ElementName
because it achieves bindings only with view controls.
<TextBlock DataContext="{Binding ElementName=lbRules, Path=SelectedItem}" Text="{Binding Name}" />
Something is wrong with your Python/Computer.
a = iter(list(range(10)))
for i in a:
print(i)
next(a)
>>>
0
2
4
6
8
Works like expected.
Tested in Python 2.7 and in Python 3+ . Works properly in both
I used another solution using CSS attribute selectors to get what you need.
Indicate the HTML attribute you know and put in the relative style you want.
Like below:
input[type="date"]
{
width: 150px;
}
But still I am not sure how it works?
Let's say an entity MyEntity
has an annotated version
property:
@Entity
public class MyEntity implements Serializable {
@Id
@GeneratedValue
private Long id;
private String name;
@Version
private Long version;
//...
}
On update, the field annotated with @Version
will be incremented and added to the WHERE
clause, something like this:
UPDATE MYENTITY SET ..., VERSION = VERSION + 1 WHERE ((ID = ?) AND (VERSION = ?))
If the WHERE
clause fails to match a record (because the same entity has already been updated by another thread), then the persistence provider will throw an OptimisticLockException
.
Does it mean that we should declare our version field as final
No but you could consider making the setter protected as you're not supposed to call it.
Try using rextract. It will let you extract text using a regular expression and reformat it.
Example:
$ echo "This is 02G05 a test string 20-Jul-2012" | ./rextract '([\d]+G[\d]+)' '${1}'
2G05
Focus can only be given by keyboard input, but an Element can be activated by both, a mouse or a keyboard.
If one would use :focus on a link, the style rule would only apply with pressing a botton on the keyboard.
docker build -t name1:tag1 -t name2:tag2 -f Dockerfile.ui .
mongod --port portnumber --dbpath /path_to_your_folder
By default portnumber is 27017 and path is /var/lib/mongodb
You can set your own port number and path where you want to keep all your database.
I adapted and modified the code from this tutorial to write a function that does a deep comparison of two JS objects.
const isEqual = function(obj1, obj2) {
const obj1Keys = Object.keys(obj1);
const obj2Keys = Object.keys(obj2);
if(obj1Keys.length !== obj2Keys.length) {
return false;
}
for (let objKey of obj1Keys) {
if (obj1[objKey] !== obj2[objKey]) {
if(typeof obj1[objKey] == "object" && typeof obj2[objKey] == "object") {
if(!isEqual(obj1[objKey], obj2[objKey])) {
return false;
}
}
else {
return false;
}
}
}
return true;
};
The function compares the respective values of the same keys for the two objects. Further, if the two values are objects, it uses recursion to execute deep comparison on them as well.
Hope this helps.
With the introduction of (i|android|windows)phones, things have changed, and to get a correct and complete solution that works on any device is really time-consuming.
You can have a peek at https://realfavicongenerator.net/favicon_compatibility or http://caniuse.com/#search=favicon to get an idea on the best way to get something that works on any device.
You should have a look at http://realfavicongenerator.net/ to automate a large part of this work, and probably at https://github.com/audreyr/favicon-cheat-sheet to understand how it works (even if this latter resource hasn't been updated in a loooong time).
One complete solution requires to add to you header the following (with the corresponding pictures and files, of course) :
<link rel="shortcut icon" href="favicon.ico">
<link rel="apple-touch-icon" sizes="57x57" href="apple-touch-icon-57x57.png">
<link rel="apple-touch-icon" sizes="114x114" href="apple-touch-icon-114x114.png">
<link rel="apple-touch-icon" sizes="72x72" href="apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="144x144" href="apple-touch-icon-144x144.png">
<link rel="apple-touch-icon" sizes="60x60" href="apple-touch-icon-60x60.png">
<link rel="apple-touch-icon" sizes="120x120" href="apple-touch-icon-120x120.png">
<link rel="apple-touch-icon" sizes="76x76" href="apple-touch-icon-76x76.png">
<link rel="apple-touch-icon" sizes="152x152" href="apple-touch-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon-180x180.png">
<link rel="icon" type="image/png" href="favicon-192x192.png" sizes="192x192">
<link rel="icon" type="image/png" href="favicon-160x160.png" sizes="160x160">
<link rel="icon" type="image/png" href="favicon-96x96.png" sizes="96x96">
<link rel="icon" type="image/png" href="favicon-16x16.png" sizes="16x16">
<link rel="icon" type="image/png" href="favicon-32x32.png" sizes="32x32">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="mstile-144x144.png">
<meta name="msapplication-config" content="browserconfig.xml">
In June 2016, RealFaviconGenerator claimed that the following 5 lines of code were supporting as many devices as the previous 18 lines:
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32">
<link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16">
<link rel="manifest" href="/manifest.json">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">
<meta name="theme-color" content="#ffffff">
Moving any column to any position:
import pandas as pd
df = pd.DataFrame({"A": [1,2,3],
"B": [2,4,8],
"C": [5,5,5]})
cols = df.columns.tolist()
column_to_move = "C"
new_position = 1
cols.insert(new_position, cols.pop(cols.index(column_to_move)))
df = df[cols]
(this answer was added to provide shorter and more generic examples to the question - without including all the case-specific details in the original question).
There are two distinct "problems" here, the first is if a table or subquery has no rows, the second is if there are NULL values in the query.
For all versions I've tested, postgres and mysql will ignore all NULL values when averaging, and it will return NULL if there is nothing to average over. This generally makes sense, as NULL is to be considered "unknown". If you want to override this you can use coalesce (as suggested by Luc M).
$ create table foo (bar int);
CREATE TABLE
$ select avg(bar) from foo;
avg
-----
(1 row)
$ select coalesce(avg(bar), 0) from foo;
coalesce
----------
0
(1 row)
$ insert into foo values (3);
INSERT 0 1
$ insert into foo values (9);
INSERT 0 1
$ insert into foo values (NULL);
INSERT 0 1
$ select coalesce(avg(bar), 0) from foo;
coalesce
--------------------
6.0000000000000000
(1 row)
of course, "from foo" can be replaced by "from (... any complicated logic here ...) as foo"
Now, should the NULL row in the table be counted as 0? Then coalesce has to be used inside the avg call.
$ select coalesce(avg(coalesce(bar, 0)), 0) from foo;
coalesce
--------------------
4.0000000000000000
(1 row)
If you facing this issue after rebooting the system, Then below steps will work fine
For workaround.
1) format the namenode: bin/hadoop namenode -format
2) start all processes again:bin/start-all.sh
For Perm fix: -
1) go to /conf/core-site.xml change fs.default.name to your custom one.
2) format the namenode: bin/hadoop namenode -format
3) start all processes again:bin/start-all.sh
Add the following JARs to the build path or lib folder of the project:
Pattern satisfy, these below criteria
^(?!.*([A-Za-z0-9]))(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,15}$
Using plain JavaScript in IE 9+ compatible syntax in just a few lines:
let children = document.querySelector('#listItem').childNodes;
if (children.length > 0) {
childrenLoop:
for (var i = 0; i < children.length; i++) {
//only target text nodes (nodeType of 3)
if (children[i].nodeType === 3) {
//do not target any whitespace in the HTML
if (children[i].nodeValue.trim().length > 0) {
children[i].nodeValue = 'Replacement text';
//optimized to break out of the loop once primary text node found
break childrenLoop;
}
}
}
}
You can detect mobile clients simply through navigator.userAgent
, and load alternate scripts based on the detected client type as:
$(document).ready(function(e) {
if(navigator.userAgent.match(/Android/i)
|| navigator.userAgent.match(/webOS/i)
|| navigator.userAgent.match(/iPhone/i)
|| navigator.userAgent.match(/iPad/i)
|| navigator.userAgent.match(/iPod/i)
|| navigator.userAgent.match(/BlackBerry/i)
|| navigator.userAgent.match(/Windows Phone/i)) {
//write code for your mobile clients here.
var jsScript = document.createElement("script");
jsScript.setAttribute("type", "text/javascript");
jsScript.setAttribute("src", "js/alternate_js_file.js");
document.getElementsByTagName("head")[0].appendChild(jsScript );
var cssScript = document.createElement("link");
cssScript.setAttribute("rel", "stylesheet");
cssScript.setAttribute("type", "text/css");
cssScript.setAttribute("href", "css/alternate_css_file.css");
document.getElementsByTagName("head")[0].appendChild(cssScript);
}
else{
// write code for your desktop clients here
}
});
You might want to try this example for version 2.6 of Python.
def my_print(text, begin, end):
"Print text in UPPER between 'begin' and 'end' in lower."
for obj in (text, begin, end):
assert isinstance(obj, str), 'Argument of wrong type!'
print begin.lower() + text.upper() + end.lower()
However, have you considered letting the function fail naturally instead?
Here ya go.
Public Function ReDimPreserve(ByRef Arr, ByVal idx1 As Integer, ByVal idx2 As Integer)
Dim newArr()
Dim x As Integer
Dim y As Integer
ReDim newArr(idx1, idx2)
For x = 0 To UBound(Arr, 1)
For y = 0 To UBound(Arr, 2)
newArr(x, y) = Arr(x, y)
Next
Next
Arr = newArr
End Function
You may get more success if you do a "search" for the runtime env from the preferences screen instead of hitting "add" - see this demo on youtube. http://www.youtube.com/watch?v=EOkN5IPoJVs&playnext_from=TL&videos=rVnITzSU2Z8 - When you hit search, you are prompted to point to the tomcat directory and then it SHOULD add it as a server runtime environment. Unfortunately for me, that is not the case (I get "no new server runtime environments were found") But you might have more success.
Only this is necessary
session_start();
unset($_SESSION["nome"]); // where $_SESSION["nome"] is your own variable. if you do not have one use only this as follow **session_unset();**
header("Location: home.php");
Serge is right - my workaround:
function mySleep (sec)
{
SpreadsheetApp.flush();
Utilities.sleep(sec*1000);
SpreadsheetApp.flush();
}
The Problem is the Container that gets the smallest possible size.
Just give a width:
to the Container (in red) and you are done.
width: MediaQuery.of(context).size.width
new Positioned(
bottom: 0.0,
child: new Container(
width: MediaQuery.of(context).size.width,
color: Colors.red,
margin: const EdgeInsets.all(0.0),
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Align(
alignment: Alignment.bottomCenter,
child: new ButtonBar(
alignment: MainAxisAlignment.center,
children: <Widget>[
new OutlineButton(
onPressed: null,
child: new Text(
"Login",
style: new TextStyle(color: Colors.white),
),
),
new RaisedButton(
color: Colors.white,
onPressed: null,
child: new Text(
"Register",
style: new TextStyle(color: Colors.black),
),
)
],
),
)
],
),
),
),
These may not solve exactly your "real-world problems", but perhaps something useful ...
Our web site includes PhoneGap and jQuery Mobile tutorials for a media player, barcode scanner, google maps, and OAuth.
Also, my github page has code, but no tutorial, for two apps:
In an lsf environment (interactive or otherwise) if the application exceeds memory utilization beyond some preset threshold by the admins on the queue or the resource request in submit to the queue the processes will be killed so other users don't fall victim to a potential run away. It doesn't always send an email when it does so, depending on how its set up.
One solution in this case is to find a queue with larger resources or define larger resource requirements in the submission.
You may also want to review man ulimit
Although I don't remember ulimit
resulting in Killed
its been a while since I needed that.
The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).
WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.
For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:
ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.
Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.
In the scenarios listed below you should go for WCF:
WEB API is a framework for developing RESTful/HTTP services.
There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.
HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.
I like this way:
set list=a;^
b;^
c;^
d;
for %%a in (%list%) do (
echo %%a
echo/
)
Difficult to give code examples in the comments.
To read the words in the file, you can read the contents of the file, which gets you a string - this is what you were doing before, with the read() method - and then use split() to get the individual words. Split breaks up a String on the delimiter provided, or on whitespace by default. For example,
"the quick brown fox".split()
produces
['the', 'quick', 'brown', 'fox']
Similarly,
fileScan.read().split()
will give you an array of Strings. Hope that helps!
I would suggest to remove the Mysql connection -
UPDATE-This is for Mysql version 5.5,if your version is different ,please change the first line accordingly
sudo apt-get purge mysql-server mysql-client mysql-common mysql-server-core-5.5 mysql-client-core-5.5
sudo rm -rf /etc/mysql /var/lib/mysql
sudo apt-get autoremove
sudo apt-get autoclean
And Install Again But this time set a root password yourself. This will save a lot of effort.
sudo apt-get update
sudo apt-get install mysql-server
SQL tables are not ordered by default, and asking for the n-th row from a non ordered set of rows has no meaning as it could potentially return a different row each time unless you specify an ORDER BY:
select * from customer order by id where row_number() = 3
(sometimes MySQL tables are shown with an internal order but you cannot rely on this behaviour). Then you can use LIMIT offset, row_count
, with a 0-based offset so row number 3 becomes offset 2:
select * from customer order by id
limit 2, 1
or you can use LIMIT row_count OFFSET offset
:
select * from customer order by id
limit 1 offset 2
You can give a try to django-import-export. It has nice admin integration, changes preview, can create, update, delete objects.
Extending @oopbase's answer with return;
statement.
Let's consider a use case of traditional authentication system where we store login information into the session. On each page we check for active session like,
/* Some Import Statements here. */
if(null == session || !session.getAttribute("is_login").equals("1")) {
response.sendRedirect("http://domain.com/login");
}
// ....
session.getAttribute("user_id");
// ....
/* Some More JSP+Java+HTML code here */
It looks fine at first glance however; It has one issue. If your server has expired session due to time limit and user is trying to access the page he might get error if you have not written your code in try..catch
block or handled if(null != session.getAttribute("attr_name"))
everytime.
So by putting a return;
statement I stopped further execution and forced to redirect page to certain location.
if(null == session || !session.getAttribute("is_login").equals("1")) {
response.sendRedirect("http://domain.com/login");
return;
}
Note that Use of redirection may vary based on the requirements. Nowadays people don't use such authentication system. (Modern approach - Token Based Authentication) It's just an simple example to understand where and how to place redirection(s).
Use execfile for Python 2:
>>> execfile('C:\\test.py')
Use exec for Python 3
>>> exec(open("C:\\test.py").read())
SJF are two type - i) non preemptive SJF ii)pre-emptive SJF
I have re-arranged the processes according to Arrival time. here is the non preemptive SJF
A.T= Arrival Time
B.T= Burst Time
C.T= Completion Time
T.T = Turn around Time = C.T - A.T
W.T = Waiting Time = T.T - B.T
Here is the preemptive SJF Note: each process will preempt at time a new process arrives.Then it will compare the burst times and will allocate the process which have shortest burst time. But if two process have same burst time then the process which came first that will be allocated first just like FCFS.
If you're using RHEL, CentOS, Oracle Linux, etc. You can use yum to install tkinter module
yum install tkinter
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
editString = ed.getText().toString();
if(editString.equals("1")){
toggle.setTextOff("TOGGLE ON");
toggle.setChecked(true);
}
else if(editString.equals("0")){
toggle.setTextOn("TOGGLE OFF");
toggle.setChecked(false);
}
}
URL url=new URL("http://[any domain]");
URLConnection con=url.openConnection();
/*now errors WILL arise here, i hav tried myself and it always shows "connected" so we'll open an InputStream on the connection, this way we know for sure that we're connected to d internet */
/* Get input stream */
con.getInputStream();
Put the above statements in try catch blocks and if an exception in caught means that there's no internet connection established. :-)
By using absolute positioning, you can make <body>
or <form>
or <div>
, fit to your browser page. For example:
<body style="position: absolute; bottom: 0px; top: 0px; left: 0px; right: 0px;">
and then simply put a <div>
inside it and use whatever percentage of either height
or width
you wish
<div id="divContainer" style="height: 100%;">
class App():
def __init__(self):
self.root = Tkinter.Tk()
button = Tkinter.Button(self.root, text = 'root quit', command=self.quit)
button.pack()
self.root.mainloop()
def quit(self):
self.root.destroy()
app = App()
I came here trying to solve a slightly different problem. Maybe this will be useful to someone else:
I create a new branch feature-a
. as part of this branch I create new directories and need to modify .gitignore to suppress some of them. This happens a lot when adding new tools to a project that create various cache folders. .serverless
, .terraform
, etc.
Before I'm ready to merge that back to master I have something else come up, so I checkout master
again, but now git status
picks up those suppressed folders again, since the .gitignore hasn't been merged yet.
The answer here is actually simple, though I had to find this blog to figure it out:
Just checkout the .gitignore file from feature-a
branch
git checkout feature-a -- feature-a/.gitignore
git add .
git commit -m "update .gitignore from feature-a branch"
That URL works fine. The message you report is normal when you look at it in a browser. My copy of Eclipse has no problems talking to it. If yours does, I suspect a proxy configuration error in your copy of eclipse.
A solution that I have found from here is pretty simple if you have python 3.x available in your command line. First, save a file (ctrl_c.py) with the contents:
import ctypes
import sys
kernel = ctypes.windll.kernel32
pid = int(sys.argv[1])
kernel.FreeConsole()
kernel.AttachConsole(pid)
kernel.SetConsoleCtrlHandler(None, 1)
kernel.GenerateConsoleCtrlEvent(0, 0)
sys.exit(0)
Then call:
python ctrl_c.py 12345
If that doesn't work, I recommend trying out the windows-kill project: https://github.com/alirdn/windows-kill
Ok uninstall the app, but we admit that the data not must be lost? This can be resolve, upgrading versionCode and versionName and try the application in "Release" mode.
For example, this is important when we want to try the migration of our Database. We can compare the our application on play store with actual application not release yet.
If your project is not a Maven project, right-click on your project and choose Properties to open the Project Properties dialog.
There is a Project Facets item on the left, select it, look for the Java facet on the list, choose which version you want to use for the project and apply.
One more solution:
function firstOrNull(array, expr) {
for (var i = 0; i < array.length; i++) {
if (expr(array[i]))
return array[i];
}
return null;
}
Using: firstOrNull([{ a: 1, b: 2 }, { a: 3, b: 3 }], function(item) { return item.a === 3; });
This function don't executes for each element from the array (it's valuable for large arrays)
Set priority for default python in Linux terminal by adding this:
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 10
sudo update-alternatives --install /usr/bin/python python /usr/bin/python2 1
Here, we set python3
to have priority 10 and python2
to priority 1. This will make python3
the default python. If you want Python2 as default then make a priority of python2 higher then python3
The easiest way to do so is using jQuery and animate.css animation library.
Javascript
/* --- Show DIV --- */
$( '.example' ).removeClass( 'fadeOutRight' ).show().addClass( 'fadeInRight' );
/* --- Hide DIV --- */
$( '.example' ).removeClass( 'fadeInRight' ).addClass( 'fadeOutRight' );
HTML
<div class="example">Some text over here.</div>
Easy enough to implement. Just don't forget to include the animate.css file in the header :)
PYTHONPATH
only affects import
statements, not the top-level Python interpreter's lookup of python files given as arguments.
Needing PYTHONPATH
to be set is not a great idea - as with anything dependent on environment variables, replicating things consistently across different machines gets tricky. Better is to use Python 'packages' which can be installed (using 'pip', or distutils) in system-dependent paths which Python already knows about.
Have a read of https://the-hitchhikers-guide-to-packaging.readthedocs.org/en/latest/ - 'The Hitchhiker's Guide to Packaging', and also http://docs.python.org/3/tutorial/modules.html - which explains PYTHONPATH and packages at a lower level.
android:layout_gravity
is used to align the text view with respect to the parent layout.
android:gravity
is used to align the text inside the text view.
Are you sure you are trying to align the text inside the text view to the right or do you want to move the text view itself to the right with respect to the parent layout or are you trying to acheive both
Just add UILongPressGestureRecognizer to the given prototype cell in storyboard, then pull the gesture to the viewController's .m file to create an action method. I made it as I said.
My needs were different, I needed to merge incomplete nested data sets without clobbering.
merging:
["b": [1, 2], "s": Set([5, 6]), "a": 1, "d": ["x": 2]]
with
["b": [3, 4], "s": Set([6, 7]), "a": 2, "d": ["y": 4]]
yields:
["b": [1, 2, 3, 4], "s": Set([5, 6, 7]), "a": 2, "d": ["y": 4, "x": 2]]
This was harder than I wanted it to be. The challenge was in mapping from dynamic typing to static typing, and I used protocols to solve this.
Also worthy of note is that when you use the dictionary literal syntax, you actually get the foundation types, which do not pick up the protocol extensions. I aborted my efforts to support those as I couldn't find an easy to to validate the uniformity of the collection elements.
import UIKit
private protocol Mergable {
func mergeWithSame<T>(right: T) -> T?
}
public extension Dictionary {
/**
Merge Dictionaries
- Parameter left: Dictionary to update
- Parameter right: Source dictionary with values to be merged
- Returns: Merged dictionay
*/
func merge(right:Dictionary) -> Dictionary {
var merged = self
for (k, rv) in right {
// case of existing left value
if let lv = self[k] {
if let lv = lv as? Mergable where lv.dynamicType == rv.dynamicType {
let m = lv.mergeWithSame(rv)
merged[k] = m
}
else if lv is Mergable {
assert(false, "Expected common type for matching keys!")
}
else if !(lv is Mergable), let _ = lv as? NSArray {
assert(false, "Dictionary literals use incompatible Foundation Types")
}
else if !(lv is Mergable), let _ = lv as? NSDictionary {
assert(false, "Dictionary literals use incompatible Foundation Types")
}
else {
merged[k] = rv
}
}
// case of no existing value
else {
merged[k] = rv
}
}
return merged
}
}
extension Array: Mergable {
func mergeWithSame<T>(right: T) -> T? {
if let right = right as? Array {
return (self + right) as? T
}
assert(false)
return nil
}
}
extension Dictionary: Mergable {
func mergeWithSame<T>(right: T) -> T? {
if let right = right as? Dictionary {
return self.merge(right) as? T
}
assert(false)
return nil
}
}
extension Set: Mergable {
func mergeWithSame<T>(right: T) -> T? {
if let right = right as? Set {
return self.union(right) as? T
}
assert(false)
return nil
}
}
var dsa12 = Dictionary<String, Any>()
dsa12["a"] = 1
dsa12["b"] = [1, 2]
dsa12["s"] = Set([5, 6])
dsa12["d"] = ["c":5, "x": 2]
var dsa34 = Dictionary<String, Any>()
dsa34["a"] = 2
dsa34["b"] = [3, 4]
dsa34["s"] = Set([6, 7])
dsa34["d"] = ["c":-5, "y": 4]
//let dsa2 = ["a": 1, "b":a34]
let mdsa3 = dsa12.merge(dsa34)
print("merging:\n\t\(dsa12)\nwith\n\t\(dsa34) \nyields: \n\t\(mdsa3)")
The key of this problem is to detect the load-more event, start an async request for data and then update the list. Also an adapter with loading indicator and other decorators is needed. In fact, the problem is very complicated in some corner cases. Just a OnScrollListener
implementation is not enough, because sometimes the items do not fill the screen.
I have written a personal package which support endless list for RecyclerView
, and also provide a async loader implementation AutoPagerFragment
which makes it very easy to get data from a multi-page source. It can load any page you want into a RecyclerView
on a custom event, not only the next page.
Here is the address: https://github.com/SphiaTower/AutoPagerRecyclerManager
Please Run Visual Studio with Administrator privilege..This Issue is solved for me..
Access to the path is denied C:\inetpub\wwwroot is denied indicates that the Self Service web site can’t access a specific folder on the server where it is installed. This could be either because the location doesn’t exist, or because the Authenticating User does not have any permissions applied to Write to this location.
A self-contained, executable Java archive. In the case of WildFly Swarm uberjars, it is a single .jar file containing your application, the portions of WildFly required to support it, an internal Maven repository of dependencies, plus a shim to bootstrap it all. see this
You can format currency writing your own code but it is just solution for the moment - when your app will grow you can need other currencies.
There is another issue with this:
I think the best option is use complex solution for internationalization e.g. library vue-i18n( http://kazupon.github.io/vue-i18n/).
I use this plugin and I don't have to worry about such a things. Please look at documentation - it is really simple:
http://kazupon.github.io/vue-i18n/guide/number.html
so you just use:
<div id="app">
<p>{{ $n(100, 'currency') }}</p>
</div>
and set EN-us to get $100.00:
<div id="app">
<p>$100.00</p>
</div>
or set PL to get 100,00 zl:
<div id="app">
<p>100,00 zl</p>
</div>
This plugin also provide different features like translations and date formatting.
You must reference Context name before using getResources()
in Android.
String user=getApplicationContext().getResources().getString(R.string.muser);
OR
Context mcontext=getApplicationContext();
String user=mcontext.getResources().getString(R.string.muser);
For what it's worth, in ASP.NET MVC 3 you can just use User which returns the user for the current request.
I just used Gson
HashMap<String, Object> map = new Gson().fromJson(json.toString(), HashMap.class);
Android already provides a version-aware approach of database management. This approach has been leveraged in the BARACUS framework for Android applications.
Also, it allows you to run hot-backups and hot-recovery of the SQLite.
I am not 100% sure, but a hot-recovery for a specific device may enable you to ship a prepared database in your app. But I am not sure about the database binary format which might be specific to certain devices, vendors or device generations.
Since the stuff is Apache License 2, feel free to reuse any part of the code, which can be found on github
EDIT :
If you only want to ship data, you might consider instantiating and persisting POJOs at the applications first start. BARACUS got a built-in support to this (Built-in key value store for configuration infos, e.g. "APP_FIRST_RUN" plus a after-context-bootstrap hook in order to run post-launch operations on the context). This enables you to have tight coupled data shipped with your app; in most cases this fitted to my use cases.
JMeter is using java SimpleDateFormat
For UTC with timezone use this
${__time(yyyy-MM-dd'T'hh:mm:ssX)}
I faced a similar problem , here's the solution.
Step 1 : Double click on the server listed in Eclipse. Here It will display Server Configuration.
Step 2 : Just change the port Number like from 8080 to 8085.
Step 3 : Save the changes.
Step 4 : re-start your server.
The server will start .Hope it'll help you.
I had similar issue before and in my case the file was in another machine so i have mapped network drive z to the folder location where my file is then i created a context in tomcat so in my web project i could access the HTML file via context
From help(print)
:
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
You can use the end
keyword:
>>> for i in range(1, 11):
... print(i, end='')
...
12345678910>>>
Note that you'll have to print()
the final newline yourself. BTW, you won't get "12345678910" in Python 2 with the trailing comma, you'll get 1 2 3 4 5 6 7 8 9 10
instead.
Alternative: Check out the code in SVN to some folder
double quotes worked in oracle when I had the keyword as one of the column name.
eg:
select t."size" from table t
Following the previous example but with the new nbformat lib version :
import nbformat
from nbconvert import PythonExporter
def convertNotebook(notebookPath, modulePath):
with open(notebookPath) as fh:
nb = nbformat.reads(fh.read(), nbformat.NO_CONVERT)
exporter = PythonExporter()
source, meta = exporter.from_notebook_node(nb)
with open(modulePath, 'w+') as fh:
fh.writelines(source.encode('utf-8'))
Perhaps you could think about the problem in a different way. WebClient
and HttpClient
are essentially different implementations of the same thing. What I recommend is implementing the Dependency Injection pattern with an IoC Container throughout your application. You should construct a client interface with a higher level of abstraction than the low level HTTP transfer. You can write concrete classes that use both WebClient
and HttpClient
, and then use the IoC container to inject the implementation via config.
What this would allow you to do would be to switch between HttpClient
and WebClient
easily so that you are able to objectively test in the production environment.
So questions like:
Will HttpClient be a better design choice if we upgrade to .Net 4.5?
Can actually be objectively answered by switching between the two client implementations using the IoC container. Here is an example interface that you might depend on that doesn't include any details about HttpClient
or WebClient
.
/// <summary>
/// Dependency Injection abstraction for rest clients.
/// </summary>
public interface IClient
{
/// <summary>
/// Adapter for serialization/deserialization of http body data
/// </summary>
ISerializationAdapter SerializationAdapter { get; }
/// <summary>
/// Sends a strongly typed request to the server and waits for a strongly typed response
/// </summary>
/// <typeparam name="TResponseBody">The expected type of the response body</typeparam>
/// <typeparam name="TRequestBody">The type of the request body if specified</typeparam>
/// <param name="request">The request that will be translated to a http request</param>
/// <returns></returns>
Task<Response<TResponseBody>> SendAsync<TResponseBody, TRequestBody>(Request<TRequestBody> request);
/// <summary>
/// Default headers to be sent with http requests
/// </summary>
IHeadersCollection DefaultRequestHeaders { get; }
/// <summary>
/// Default timeout for http requests
/// </summary>
TimeSpan Timeout { get; set; }
/// <summary>
/// Base Uri for the client. Any resources specified on requests will be relative to this.
/// </summary>
Uri BaseUri { get; set; }
/// <summary>
/// Name of the client
/// </summary>
string Name { get; }
}
public class Request<TRequestBody>
{
#region Public Properties
public IHeadersCollection Headers { get; }
public Uri Resource { get; set; }
public HttpRequestMethod HttpRequestMethod { get; set; }
public TRequestBody Body { get; set; }
public CancellationToken CancellationToken { get; set; }
public string CustomHttpRequestMethod { get; set; }
#endregion
public Request(Uri resource,
TRequestBody body,
IHeadersCollection headers,
HttpRequestMethod httpRequestMethod,
IClient client,
CancellationToken cancellationToken)
{
Body = body;
Headers = headers;
Resource = resource;
HttpRequestMethod = httpRequestMethod;
CancellationToken = cancellationToken;
if (Headers == null) Headers = new RequestHeadersCollection();
var defaultRequestHeaders = client?.DefaultRequestHeaders;
if (defaultRequestHeaders == null) return;
foreach (var kvp in defaultRequestHeaders)
{
Headers.Add(kvp);
}
}
}
public abstract class Response<TResponseBody> : Response
{
#region Public Properties
public virtual TResponseBody Body { get; }
#endregion
#region Constructors
/// <summary>
/// Only used for mocking or other inheritance
/// </summary>
protected Response() : base()
{
}
protected Response(
IHeadersCollection headersCollection,
int statusCode,
HttpRequestMethod httpRequestMethod,
byte[] responseData,
TResponseBody body,
Uri requestUri
) : base(
headersCollection,
statusCode,
httpRequestMethod,
responseData,
requestUri)
{
Body = body;
}
public static implicit operator TResponseBody(Response<TResponseBody> readResult)
{
return readResult.Body;
}
#endregion
}
public abstract class Response
{
#region Fields
private readonly byte[] _responseData;
#endregion
#region Public Properties
public virtual int StatusCode { get; }
public virtual IHeadersCollection Headers { get; }
public virtual HttpRequestMethod HttpRequestMethod { get; }
public abstract bool IsSuccess { get; }
public virtual Uri RequestUri { get; }
#endregion
#region Constructor
/// <summary>
/// Only used for mocking or other inheritance
/// </summary>
protected Response()
{
}
protected Response
(
IHeadersCollection headersCollection,
int statusCode,
HttpRequestMethod httpRequestMethod,
byte[] responseData,
Uri requestUri
)
{
StatusCode = statusCode;
Headers = headersCollection;
HttpRequestMethod = httpRequestMethod;
RequestUri = requestUri;
_responseData = responseData;
}
#endregion
#region Public Methods
public virtual byte[] GetResponseData()
{
return _responseData;
}
#endregion
}
You can use Task.Run
to make WebClient
run asynchronously in its implementation.
Dependency Injection, when done well helps alleviate the problem of having to make low level decisions upfront. Ultimately, the only way to know the true answer is try both in a live environment and see which one works the best. It's quite possible that WebClient
may work better for some customers, and HttpClient
may work better for others. This is why abstraction is important. It means that code can quickly be swapped in, or changed with configuration without changing the fundamental design of the app.
BTW: there are numerous other reasons that you should use an abstraction instead of directly calling one of these low-level APIs. One huge one being unit-testability.
They are completely different. is
checks for object identity, while ==
checks for equality (a notion that depends on the two operands' types).
It is only a lucky coincidence that "is
" seems to work correctly with small integers (e.g. 5 == 4+1). That is because CPython optimizes the storage of integers in the range (-5 to 256) by making them singletons. This behavior is totally implementation-dependent and not guaranteed to be preserved under all manner of minor transformative operations.
For example, Python 3.5 also makes short strings singletons, but slicing them disrupts this behavior:
>>> "foo" + "bar" == "foobar"
True
>>> "foo" + "bar" is "foobar"
True
>>> "foo"[:] + "bar" == "foobar"
True
>>> "foo"[:] + "bar" is "foobar"
False
It probably depends on the type of collection you are enumerating and the implementation of its indexer. In general though, using foreach
is likely to be a better approach.
Also, it'll work with any IEnumerable
- not just things with indexers.
What about this?
my_string = "123,456.908"
commas_removed = my_string.replace(',', '') # remove comma separation
my_float = float(commas_removed) # turn from string to float.
In short:
my_float = float(my_string.replace(',', ''))
Now, i'm being told that this will terminate the session (or is it all sessions?) in the 15th minute of use, regardless their activity.
This is wrong. It will just kill the session when the associated client (webbrowser) has not accessed the website for more than 15 minutes. The activity certainly counts, exactly as you initially expected, seeing your attempt to solve this.
The HttpSession#setMaxInactiveInterval()
doesn't change much here by the way. It does exactly the same as <session-timeout>
in web.xml
, with the only difference that you can change/set it programmatically during runtime. The change by the way only affects the current session instance, not globally (else it would have been a static
method).
To play around and experience this yourself, try to set <session-timeout>
to 1 minute and create a HttpSessionListener
like follows:
@WebListener
public class HttpSessionChecker implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent event) {
System.out.printf("Session ID %s created at %s%n", event.getSession().getId(), new Date());
}
public void sessionDestroyed(HttpSessionEvent event) {
System.out.printf("Session ID %s destroyed at %s%n", event.getSession().getId(), new Date());
}
}
(if you're not on Servlet 3.0 yet and thus can't use @WebListener
, then register in web.xml
as follows):
<listener>
<listener-class>com.example.HttpSessionChecker</listener-class>
</listener>
Note that the servletcontainer won't immediately destroy sessions after exactly the timeout value. It's a background job which runs at certain intervals (e.g. 5~15 minutes depending on load and the servletcontainer make/type). So don't be surprised when you don't see destroyed
line in the console immediately after exactly one minute of inactivity. However, when you fire a HTTP request on a timed-out-but-not-destroyed-yet session, it will be destroyed immediately.
I was having similar problem and
var dataObj = JSON.parse(data);
console.log(dataObj[0].category); //will return Damskie
console.log(dataObj[1].category); //will return Meskie
This solved my problem. Thanks Selvakumar Arumugam
Use the put method: https://developer.android.com/reference/org/json/JSONObject.html
JSONObject person = jsonArray.getJSONObject(0).getJSONObject("person");
person.put("name", "Sammie");
Running console svn cleanup
has solved the same problem for me.
Simplest: dump the whole collection into a Set (using the Set(Collection) constructor or Set.addAll), then see if the Set has the same size as the ArrayList.
List<Integer> list = ...;
Set<Integer> set = new HashSet<Integer>(list);
if(set.size() < list.size()){
/* There are duplicates */
}
Update: If I'm understanding your question correctly, you have a 2d array of Block, as in
Block table[][];
and you want to detect if any row of them has duplicates?
In that case, I could do the following, assuming that Block implements "equals" and "hashCode" correctly:
for (Block[] row : table) {
Set set = new HashSet<Block>();
for (Block cell : row) {
set.add(cell);
}
if (set.size() < 6) { //has duplicate
}
}
I'm not 100% sure of that for syntax, so it might be safer to write it as
for (int i = 0; i < 6; i++) {
Set set = new HashSet<Block>();
for (int j = 0; j < 6; j++)
set.add(table[i][j]);
...
Set.add
returns a boolean false if the item being added is already in the set, so you could even short circuit and bale out on any add that returns false
if all you want to know is whether there are any duplicates.
If you'd like a string
> (1.7289).ToString("#.##")
"1.73"
Or a decimal
> Math.Round((Decimal)x, 2)
1.73m
But remember! Rounding is not distributive, ie. round(x*y) != round(x) * round(y)
. So don't do any rounding until the very end of a calculation, else you'll lose accuracy.
By default, MomentJS parses in local time. If only a date string (with no time) is provided, the time defaults to midnight.
In your code, you create a local date and then convert it to the UTC timezone (in fact, it makes the moment instance switch to UTC mode), so when it is formatted, it is shifted (depending on your local time) forward or backwards.
If the local timezone is UTC+N (N being a positive number), and you parse a date-only string, you will get the previous date.
Here are some examples to illustrate it (my local time offset is UTC+3 during DST):
>>> moment('07-18-2013', 'MM-DD-YYYY').utc().format("YYYY-MM-DD HH:mm")
"2013-07-17 21:00"
>>> moment('07-18-2013 12:00', 'MM-DD-YYYY HH:mm').utc().format("YYYY-MM-DD HH:mm")
"2013-07-18 09:00"
>>> Date()
"Thu Jul 25 2013 14:28:45 GMT+0300 (Jerusalem Daylight Time)"
If you want the date-time string interpreted as UTC, you should be explicit about it:
>>> moment(new Date('07-18-2013 UTC')).utc().format("YYYY-MM-DD HH:mm")
"2013-07-18 00:00"
or, as Matt Johnson mentions in his answer, you can (and probably should) parse it as a UTC date in the first place using moment.utc()
and include the format string as a second argument to prevent ambiguity.
>>> moment.utc('07-18-2013', 'MM-DD-YYYY').format("YYYY-MM-DD HH:mm")
"2013-07-18 00:00"
To go the other way around and convert a UTC date to a local date, you can use the local()
method, as follows:
>>> moment.utc('07-18-2013', 'MM-DD-YYYY').local().format("YYYY-MM-DD HH:mm")
"2013-07-18 03:00"
Another option either using Double
or double
is use Double.valueOf(double d).intValue();
. Simple and clean
Since FFT is symmetric over it's centre, half the values are just enough.
import numpy as np
import matplotlib.pyplot as plt
fs = 30.0
t = np.arange(0,10,1/fs)
x = np.cos(2*np.pi*10*t)
xF = np.fft.fft(x)
N = len(xF)
xF = xF[0:N/2]
fr = np.linspace(0,fs/2,N/2)
plt.ion()
plt.plot(fr,abs(xF)**2)
for me just add ob_start(); at the start of the file.
I would love the ability to use a role as a collection of tasks such that, in my playbook, I can choose which subset of tasks to run. Unfortunately, the playbook can only load them all in and then you have to use the --tags
option on the cmdline to choose which tasks to run. The problem with this is that all of the tasks will run unless you remember to set --tags
or --skip-tags
.
I have set up some tasks, however, with a when:
clause that will only fire if a var is set.
e.g.
# role/stuff/tasks/main.yml
- name: do stuff
when: stuff|default(false)
Now, this task will not fire by default, but only if I set the stuff=true
$ ansible-playbook -e '{"stuff":true}'
or in a playbook:
roles:
- {"role":"stuff", "stuff":true}
You start a thread which runs the static method SumData
. However, SumData
calls SetTextboxText
which isn't static. Thus you need an instance of your form to call SetTextboxText
.
For disabling Hibernate:select
message in log, it is possible to set the property into HibernateJpaVendorAdapter
:
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="false"/>
</bean>
Not sure why the file path is not working, I have some similar code that works fine.
But if with two "\" it works, you can always do path = path.Replace(@"\", @"\\");
In v7.7, I had to go to Plugins menu and select "Open Plugins Folder..." (which goes to C:\Program Files\Notepad++\plugins).
I had to create a folder for the plugin and extract the .dll into the folder. For example, create a folder called "JSMinNPP" and place the "JSMinNPP.dll" in that folder. It doesn't work if you put the dll into the plugins folder.
Finally go to Settings --> Import --> Import plugin(s) and import that dll and restart Notepad++.
Actually you can only style few CSS properties on :modified option elements.
color
does not work, background-color
either, but you can set a background-image
.
You can couple this with gradients to do the trick.
option:hover,_x000D_
option:focus,_x000D_
option:active,_x000D_
option:checked {_x000D_
background: linear-gradient(#5A2569, #5A2569);_x000D_
}
_x000D_
<select>_x000D_
<option>A</option>_x000D_
<option>B</option>_x000D_
<option>C</option>_x000D_
</select>
_x000D_
Works on gecko/webkit.
The following is a test class that mocks private static final Logger named log
in class LogUtil
.
In addition to mocking the getLogger
factory call, it is necessary to explicitly set the field using reflection, in @BeforeClass
public class LogUtilTest {
private static Logger logger;
private static MockedStatic<LoggerFactory> loggerFactoryMockedStatic;
/**
* Since {@link LogUtil#log} being a static final variable it is only initialized once at the class load time
* So assertions are also performed against the same mock {@link LogUtilTest#logger}
*/
@BeforeClass
public static void beforeClass() {
logger = mock(Logger.class);
loggerFactoryMockedStatic = mockStatic(LoggerFactory.class);
loggerFactoryMockedStatic.when(() -> LoggerFactory.getLogger(anyString())).thenReturn(logger);
Whitebox.setInternalState(LogUtil.class, "log", logger);
}
@AfterClass
public static void after() {
loggerFactoryMockedStatic.close();
}
}
It makes a difference with array elements.
Consider this example
$a = array('test' => 1);
$a['test'] = NULL;
echo "Key test ", array_key_exists('test', $a)? "exists": "does not exist";
Here, the key 'test' still exists. However, in this example
$a = array('test' => 1);
unset($a['test']);
echo "Key test ", array_key_exists('test', $a)? "exists": "does not exist";
the key no longer exists.
This article explains that your sequence might be out of sync and that you have to manually bring it back in sync.
An excerpt from the article in case the URL changes:
If you get this message when trying to insert data into a PostgreSQL database:
ERROR: duplicate key violates unique constraint
That likely means that the primary key sequence in the table you're working with has somehow become out of sync, likely because of a mass import process (or something along those lines). Call it a "bug by design", but it seems that you have to manually reset the a primary key index after restoring from a dump file. At any rate, to see if your values are out of sync, run these two commands:
SELECT MAX(the_primary_key) FROM the_table; SELECT nextval('the_primary_key_sequence');
If the first value is higher than the second value, your sequence is out of sync. Back up your PG database (just in case), then run thisL
SELECT setval('the_primary_key_sequence', (SELECT MAX(the_primary_key) FROM the_table)+1);
That will set the sequence to the next available value that's higher than any existing primary key in the sequence.
I did not have a .vimrc file in my home directory. I created one, added this line:
set number
and that solved the problem.
You can try to use pandoc
as your converter. Here's a jekyll plugin to implement this. Pandoc will be able to add a figure caption the same as your alt
attribute automatically.
But you have to push the compiled site because github doesn't allow plugins in Github pages for security.
Use MultiDataTrigger type
<Style TargetType="ListBoxItem">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=State}" Value="WA">
<Setter Property="Foreground" Value="Red" />
</DataTrigger>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding Path=Name}" Value="Portland" />
<Condition Binding="{Binding Path=State}" Value="OR" />
</MultiDataTrigger.Conditions>
<Setter Property="Background" Value="Cyan" />
</MultiDataTrigger>
</Style.Triggers>
</Style>
Using the -n /usr/local/bin flag does work, BUT I had to come back to this page every time I wanted to update a package again. So I figured out a permanent fix for this.
For those interested in fixing this permanently:
Create a ~/.gemrc file
vim .gemrc
With the following content:
:gemdir:
- ~/.gem/ruby
install: -n /usr/local/bin
Now you can run your command normally without the -n flag.
Enjoy!
If you add file ipython_config.py into the ~/.ipython/profile_default directory with lines like below, then the autoreload functionality will be loaded on IPython startup (tested on 2.0.0):
print "--------->>>>>>>> ENABLE AUTORELOAD <<<<<<<<<------------"
c = get_config()
c.InteractiveShellApp.exec_lines = []
c.InteractiveShellApp.exec_lines.append('%load_ext autoreload')
c.InteractiveShellApp.exec_lines.append('%autoreload 2')
Not really anything to do with jQuery, but if you want to trim a pattern from a string, then use a regular expression:
<textarea id="ta0"></textarea>
<button onclick="
var ta = document.getElementById('ta0');
var text = 'some<br>text<br />to<br/>replace';
var re = /<br *\/?>/gi;
ta.value = text.replace(re, '\n');
">Add stuff to text area</button>
It'll vary depending on resources, but you could run the script bellow and see for yourself ;)
<?php
$tests = 100000;
for ($i = 0; $i < $tests; $i++)
{
$string = md5(rand());
$position = rand(0, 31);
$start1 = microtime(true);
$char1 = $string[$position];
$end1 = microtime(true);
$time1[$i] = $end1 - $start1;
$start2 = microtime(true);
$char2 = substr($string, $position, 1);
$end2 = microtime(true);
$time2[$i] = $end2 - $start2;
$start3 = microtime(true);
$char3 = $string{$position};
$end3 = microtime(true);
$time3[$i] = $end3 - $start3;
}
$avg1 = array_sum($time1) / $tests;
echo 'the average float microtime using "array[]" is '. $avg1 . PHP_EOL;
$avg2 = array_sum($time2) / $tests;
echo 'the average float microtime using "substr()" is '. $avg2 . PHP_EOL;
$avg3 = array_sum($time3) / $tests;
echo 'the average float microtime using "array{}" is '. $avg3 . PHP_EOL;
?>
Some reference numbers (on an old CoreDuo machine)
$ php 1.php
the average float microtime using "array[]" is 1.914701461792E-6
the average float microtime using "substr()" is 2.2536706924438E-6
the average float microtime using "array{}" is 1.821768283844E-6
$ php 1.php
the average float microtime using "array[]" is 1.7251944541931E-6
the average float microtime using "substr()" is 2.0931363105774E-6
the average float microtime using "array{}" is 1.7225742340088E-6
$ php 1.php
the average float microtime using "array[]" is 1.7293763160706E-6
the average float microtime using "substr()" is 2.1037721633911E-6
the average float microtime using "array{}" is 1.7249774932861E-6
It seems that using the []
or {}
operators is more or less the same.
It's very simple,
listViewRequests.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
**AppCompatCheckedTextView checkBox = (AppCompatCheckedTextView) view;**
Log.i("CHECK",checkBox.isChecked()+""+checkBox.getText().toString());**
}
});
You should read Learn Prolog Now! Chapter 10.2 Using Cut. This provides an example:
max(X,Y,Z) :- X =< Y,!, Y = Z.
to be said,
Z
is equal to Y
IF !
is true (which it always is) AND X
is <= Y
.
If your problem is same as mine where you just want to reset the column headers from 0 to column size. Do
df = pd.DataFrame(df.values);
EDIT:
Not a good idea if you have heterogenous data types. Better just use
df.columns = range(len(df.columns))
I would strongly recommend using a library like PHPMailer to send emails.
It's easier and handles most of the issues automatically for you.
Regarding displaying embedded (inline) images, here's what's on their documentation:
Inline Attachments
There is an additional way to add an attachment. If you want to make a HTML e-mail with images incorporated into the desk, it's necessary to attach the image and then link the tag to it. For example, if you add an image as inline attachment with the CID my-photo, you would access it within the HTML e-mail with
<img src="cid:my-photo" alt="my-photo" />
.In detail, here is the function to add an inline attachment:
$mail->AddEmbeddedImage(filename, cid, name);
//By using this function with this example's value above, results in this code:
$mail->AddEmbeddedImage('my-photo.jpg', 'my-photo', 'my-photo.jpg ');
To give you a more complete example of how it would work:
<?php
require_once('../class.phpmailer.php');
$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch
$mail->IsSMTP(); // telling the class to use SMTP
try {
$mail->Host = "mail.yourdomain.com"; // SMTP server
$mail->Port = 25; // set the SMTP port
$mail->SetFrom('[email protected]', 'First Last');
$mail->AddAddress('[email protected]', 'John Doe');
$mail->Subject = 'PHPMailer Test';
$mail->AddEmbeddedImage("rocks.png", "my-attach", "rocks.png");
$mail->Body = 'Your <b>HTML</b> with an embedded Image: <img src="cid:my-attach"> Here is an image!';
$mail->AddAttachment('something.zip'); // this is a regular attachment (Not inline)
$mail->Send();
echo "Message Sent OK<p></p>\n";
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
?>
Regarding your comment, you asked how to send HTML email with embedded images, so I gave you an example of how to do that.
The library I told you about can send emails using a lot of methods other than SMTP.
Take a look at the PHPMailer Example page for other examples.
One way or the other, if you don't want to send the email in the ways supported by the library, you can (should) still use the library to build the message, then you send it the way you want.
For example:
You can replace the line that send the email:
$mail->Send();
With this:
$mime_message = $mail->CreateBody(); //Retrieve the message content
echo $mime_message; // Echo it to the screen or send it using whatever method you want
Hope that helps. Let me know if you run into trouble using it.
You can also take a look at this module for angular
I had the same problem and none of the above worked, but the following solution worked for me:
On my Nexus 4:
Go to Settings
Choose Developer options (from the end of the list after pressing seven times on "About phone")
Check the "USB debugging" and press OK.
There are a couple of ways to address your problem, however this is probably the most straightforward:
Your main
method is static, so it does not have access to instance members (isLeapYear
field and isLeapYear
method. One approach to rectify this is to make both the field and the method static as well:
static boolean isLeapYear;
/* (snip) */
public static boolean isLeapYear(int year)
{
/* (snip) */
}
Lastly, you're not actually calling your isLeapYear
method (which is why you're not seeing any results). Add this line after int year = kboard.nextInt();
:
isLeapYear(year);
That should be a start. There are some other best practices you could follow but for now just focus on getting your code to work; you can refactor later.
The test for undefined is unnecessary and isn't as robust as it could be because, as user568458 pointed out, the solution provided fails if null or false is passed. Users of your API might think false or null would force the method to avoid that parameter.
function PaulDixonSolution(required, optionalArg){
optionalArg = (typeof optionalArg === "undefined") ? "defaultValue" : optionalArg;
console.log(optionalArg);
};
PaulDixonSolution("required");
PaulDixonSolution("required", "provided");
PaulDixonSolution("required", null);
PaulDixonSolution("required", false);
The result is:
defaultValue
provided
null
false
Those last two are potentially bad. Instead try:
function bulletproof(required, optionalArg){
optionalArg = optionalArg ? optionalArg : "defaultValue";;
console.log(optionalArg);
};
bulletproof("required");
bulletproof("required", "provided");
bulletproof("required", null);
bulletproof("required", false);
Which results in:
defaultValue
provided
defaultValue
defaultValue
The only scenario where this isn't optimal is when you actually have optional parameters that are meant to be booleans or intentional null.
Using Collections#addAll()
String[] words = {"ace","boom","crew","dog","eon"};
List<String> arrayList = new ArrayList<>();
Collections.addAll(arrayList, words);
You can parse the string using Html Agility pack and get the InnerText.
HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(@"<b> Hulk Hogan's Celebrity Championship Wrestling <font color=\"#228b22\">[Proj # 206010]</font></b> (Reality Series, )");
string result = htmlDoc.DocumentNode.InnerText;
Having Clause may come prior/before the group by clause.
Example: select * FROM test_std; ROLL_NO SNAME DOB TEACH
1 John 27-AUG-18 Wills
2 Knit 27-AUG-18 Prestion
3 Perl 27-AUG-18 Wills
4 Ohrm 27-AUG-18 Woods
5 Smith 27-AUG-18 Charmy
6 Jony 27-AUG-18 Wills
Warner 20-NOV-18 Wills
Marsh 12-NOV-18 Langer
FINCH 18-OCT-18 Langer
9 rows selected.
select teach, count() count from test_std having count() > 1 group by TEACH ;
TEACH COUNT
Langer 2 Wills 4
curl -u username:password http://
curl -u username http://
From the documentation page:
-u, --user <user:password>
Specify the user name and password to use for server authentication. Overrides -n, --netrc and --netrc-optional.
If you simply specify the user name, curl will prompt for a password.
The user name and passwords are split up on the first colon, which makes it impossible to use a colon in the user name with this option. The password can, still.
When using Kerberos V5 with a Windows based server you should include the Windows domain name in the user name, in order for the server to succesfully obtain a Kerberos Ticket. If you don't then the initial authentication handshake may fail.
When using NTLM, the user name can be specified simply as the user name, without the domain, if there is a single domain and forest in your setup for example.
To specify the domain name use either Down-Level Logon Name or UPN (User Principal Name) formats. For example, EXAMPLE\user and [email protected] respectively.
If you use a Windows SSPI-enabled curl binary and perform Kerberos V5, Negotiate, NTLM or Digest authentication then you can tell curl to select the user name and password from your environment by specifying a single colon with this option: "-u :".
If this option is used several times, the last one will be used.
http://curl.haxx.se/docs/manpage.html#-u
Note that you do not need --basic
flag as it is the default.
You can try also with userInput.bat which uses the html input element.
This will assign the input to the value jstackId:
call userInput.bat jstackId
echo %jstackId%
This will just print the input value which eventually you can capture with FOR /F
:
call userInput.bat
System.Reflection.Assembly.GetEntryAssembly().Location;
jQuery:
$('#foo').click(function() { alert('foo'); });
Or if you don't want it to follow the link href:
$('#foo').click(function() { alert('foo'); return false; });
For me it was important to delete the "php.executablePath" path from the VS code settings and leave only the path to PHP in the Path variable.
When I had the Path variable together with php.executablePath, an irritating error still occurred (despite the fact that the path to php was correct).
$('form').submit( function(e){
e.preventDefault();
//later you decide you want to submit
$(this).trigger('submit'); or $(this).trigger('anyEvent');
I am using the following code in one of my projects:
using (var _context = new DBContext(new DbContextOptions<DBContext>()))
{
try
{
_context.MyItems.Remove(new MyItem() { MyItemId = id });
await _context.SaveChangesAsync();
}
catch (Exception ex)
{
if (!_context.MyItems.Any(i => i.MyItemId == id))
{
return NotFound();
}
else
{
throw ex;
}
}
}
This way, it will query the database twice only if an exception occurs when trying to remove the item with the specified ID. Then if the item is not found, it returns a meaningful message; otherwise, it just throws the exception back (you can handle this in a way more fit to your case using different catch blocks for different exception types, add more custom checks using if blocks etc.).
[I am using this code in a MVC .Net Core/.Net Core project with Entity Framework Core.]
You need to install it first. Create a new Dockerfile
, and install wget in it:
FROM ubuntu:14.04
RUN apt-get update \
&& apt-get install -y wget \
&& rm -rf /var/lib/apt/lists/*
Then, build that image:
docker build -t my-ubuntu .
Finally, run it:
docker run my-ubuntu wget https://downloads-packages.s3.amazonaws.com/ubuntu-14.04/gitlab_7.8.2-omnibus.1-1_amd64.deb
I spent some time to remove the git integration from my visual studio 2015 project. any time i remove git from visual studio, and add TFS by following this -- Tools -> option -> sourceControl -> plugin selection -> Visual Studio Team foundation server, it used to come back.
My solution was -
making the physical location of my project- Show all hidden files. you can do this by show hidden files and folder option of windows. then i realize, there was a hidden folder called .git something. I kept a full back up of my project folder and also the git folder any other back up that necessary (I kept this back up incase my project breaks, so that i can go back to previous condition).
then i have deleted the hidden .git folder and any other .git related files.
then i try to Tools -> option -> sourceControl -> plugin selection -> Visual Studio Team foundation server. then i open the project by visual studio- File -> open -> project/solution..
after that i noiticed in solution explorer , right clicking the solution namei see "Source control" option , and also in project - right click i see "Add soution to source control".. and this time it didn't add solution to git..
also it is good to remove any git connection from your source control exploerer..if there is any..
so the main thing is that make sure there is no hidden git file in your project file and any other git extension.. hope this will be helpful to someone..