You have to modify the control template instead of ItemsPanelTemplate:
<ItemsControl >
<ItemsControl.Template>
<ControlTemplate>
<ScrollViewer x:Name="ScrollViewer" Padding="{TemplateBinding Padding}">
<ItemsPresenter />
</ScrollViewer>
</ControlTemplate>
</ItemsControl.Template>
</ItemsControl>
Maybe, your code does not working because StackPanel has own scrolling functionality. Try to use StackPanel.CanVerticallyScroll property.
As you have noticed, xscale
and yscale
does not support a simple linear re-scaling (unfortunately). As an alternative to Hooked's answer, instead of messing with the data, you can trick the labels like so:
ticks = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x*scale))
ax.xaxis.set_major_formatter(ticks)
A complete example showing both x and y scaling:
import numpy as np
import pylab as plt
import matplotlib.ticker as ticker
# Generate data
x = np.linspace(0, 1e-9)
y = 1e3*np.sin(2*np.pi*x/1e-9) # one period, 1k amplitude
# setup figures
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
# plot two identical plots
ax1.plot(x, y)
ax2.plot(x, y)
# Change only ax2
scale_x = 1e-9
scale_y = 1e3
ticks_x = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_x))
ax2.xaxis.set_major_formatter(ticks_x)
ticks_y = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_y))
ax2.yaxis.set_major_formatter(ticks_y)
ax1.set_xlabel("meters")
ax1.set_ylabel('volt')
ax2.set_xlabel("nanometers")
ax2.set_ylabel('kilovolt')
plt.show()
And finally I have the credits for a picture:
Note that, if you have text.usetex: true
as I have, you may want to enclose the labels in $
, like so: '${0:g}$'
.
Sharing my case, hope that will help.
In my situation inside MY_PROJ.Database->MY_PROJ.Database.sqlproj
I had to put this:
<Build Include="dbo\Tables\MyTableGeneratingScript.sql" />
It works for me:
CREATE TABLE `users`(
`user_id` INT(10) NOT NULL AUTO_INCREMENT,
`username` VARCHAR(255) NOT NULL,
`password` VARCHAR(255) NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE = MyISAM;
Short solution for preventing user from using context menu, copy and cut in jQuery:
jQuery(document).bind("cut copy contextmenu",function(e){
e.preventDefault();
});
Also disabling text selection in CSS might come handy:
.noselect {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
winrm set winrm/config/client '@{TrustedHosts="machineA,machineB"}'
Small improvement to the code from ryyst (who got the most votes) is to not use dynamically allocated decoding table but rather static const precomputed table. This eliminates the use of pointer and initialization of the table, and also avoids memory leakage if one forgets to clean up the decoding table with base64_cleanup() (by the way, in base64_cleanup(), after calling free(decoding_table), one should have decoding_table=NULL, otherwise accidentally calling base64_decode after base64_cleanup() will crash or cause undetermined behavior). Another solution could be to use std::unique_ptr...but I'm satisfied with just having const char[256] on the stack and avoid using pointers alltogether - the code looks cleaner and shorter this way.
The decoding table is computed as follows:
const char encoding_table[] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/' };
unsigned char decoding_table[256];
for (int i = 0; i < 256; i++)
decoding_table[i] = '\0';
for (int i = 0; i < 64; i++)
decoding_table[(unsigned char)encoding_table[i]] = i;
for (int i = 0; i < 256; i++)
cout << "0x" << (int(decoding_table[i]) < 16 ? "0" : "") << hex << int(decoding_table[i]) << (i != 255 ? "," : "") << ((i+1) % 16 == 0 ? '\n' : '\0');
cin.ignore();
and the modified code I am using is:
static const char encoding_table[] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/' };
static const unsigned char decoding_table[256] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x00, 0x00, 0x3f,
0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
char* base64_encode(const unsigned char *data, size_t input_length, size_t &output_length) {
const int mod_table[] = { 0, 2, 1 };
output_length = 4 * ((input_length + 2) / 3);
char *encoded_data = (char*)malloc(output_length);
if (encoded_data == nullptr)
return nullptr;
for (int i = 0, j = 0; i < input_length;) {
uint32_t octet_a = i < input_length ? (unsigned char)data[i++] : 0;
uint32_t octet_b = i < input_length ? (unsigned char)data[i++] : 0;
uint32_t octet_c = i < input_length ? (unsigned char)data[i++] : 0;
uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;
encoded_data[j++] = encoding_table[(triple >> 3 * 6) & 0x3F];
encoded_data[j++] = encoding_table[(triple >> 2 * 6) & 0x3F];
encoded_data[j++] = encoding_table[(triple >> 1 * 6) & 0x3F];
encoded_data[j++] = encoding_table[(triple >> 0 * 6) & 0x3F];
}
for (int i = 0; i < mod_table[input_length % 3]; i++)
encoded_data[output_length - 1 - i] = '=';
return encoded_data;
};
unsigned char* base64_decode(const char *data, size_t input_length, size_t &output_length) {
if (input_length % 4 != 0)
return nullptr;
output_length = input_length / 4 * 3;
if (data[input_length - 1] == '=') (output_length)--;
if (data[input_length - 2] == '=') (output_length)--;
unsigned char* decoded_data = (unsigned char*)malloc(output_length);
if (decoded_data == nullptr)
return nullptr;
for (int i = 0, j = 0; i < input_length;) {
uint32_t sextet_a = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
uint32_t sextet_b = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
uint32_t sextet_c = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
uint32_t sextet_d = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
uint32_t triple = (sextet_a << 3 * 6)
+ (sextet_b << 2 * 6)
+ (sextet_c << 1 * 6)
+ (sextet_d << 0 * 6);
if (j < output_length) decoded_data[j++] = (triple >> 2 * 8) & 0xFF;
if (j < output_length) decoded_data[j++] = (triple >> 1 * 8) & 0xFF;
if (j < output_length) decoded_data[j++] = (triple >> 0 * 8) & 0xFF;
}
return decoded_data;
};
Try this Swift code in a UIViewController -
func doAlertControllerDemo() {
var inputTextField: UITextField?;
let passwordPrompt = UIAlertController(title: "Enter Password", message: "You have selected to enter your passwod.", preferredStyle: UIAlertControllerStyle.Alert);
passwordPrompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
// Now do whatever you want with inputTextField (remember to unwrap the optional)
let entryStr : String = (inputTextField?.text)! ;
print("BOOM! I received '\(entryStr)'");
self.doAlertViewDemo(); //do again!
}));
passwordPrompt.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
print("done");
}));
passwordPrompt.addTextFieldWithConfigurationHandler({(textField: UITextField!) in
textField.placeholder = "Password"
textField.secureTextEntry = false /* true here for pswd entry */
inputTextField = textField
});
self.presentViewController(passwordPrompt, animated: true, completion: nil);
return;
}
I am not sure what the last line means. Does it mean, I read the file, create multiple Movie objects. Then make a vector of pointers where each element (pointer) points to one of those Movie objects?
I would guess this is what is intended. The intent is probably that you read the data for one movie, allocate an object with new
, fill the object in with the data, and then push the address of the data onto the vector
(probably not the best design, but most likely what's intended anyway).
If you don't understand anything then download vcredist_x86.exe from http://www.microsoft.com/en-us/download/details.aspx?id=8328 . It will solve your problem.
$.ajax({
type:'POST',
url: 'ajaxRequest.php',
data:{
userEmail : userEmail
},
success:function(data){
if(data == "error"){
$('#ShowError').show().text("Email dosen't Match ");
$('#ShowSuccess').hide();
}
else{
$('#ShowSuccess').show().text(data);
}
}
});
Yes you can do it.
In Swift you can still use the "#if/#else/#endif" preprocessor macros (although more constrained), as per Apple docs. Here's an example:
#if DEBUG
let a = 2
#else
let a = 3
#endif
Now, you must set the "DEBUG" symbol elsewhere, though. Set it in the "Swift Compiler - Custom Flags" section, "Other Swift Flags" line. You add the DEBUG symbol with the -D DEBUG
entry.
As usual, you can set a different value when in Debug or when in Release.
I tested it in real code and it works; it doesn't seem to be recognized in a playground though.
You can read my original post here.
IMPORTANT NOTE: -DDEBUG=1
doesn't work. Only -D DEBUG
works. Seems compiler is ignoring a flag with a specific value.
In case of PUT or POST Request. if you receive statusCode 405 or method not allowed. Try this implementation with "request" library, and add mentioned properties.
followAllRedirects: true,
followOriginalHttpMethod: true
const options = {
headers: {
Authorization: TOKEN,
'Content-Type': 'application/json',
'Accept': 'application/json'
},
url: `https://${url}`,
json: true,
body: payload,
followAllRedirects: true,
followOriginalHttpMethod: true
}
console.log('DEBUG: API call', JSON.stringify(options));
request(options, function (error, response, body) {
if (!error) {
console.log(response);
}
});
}
The first reason that comes to mind is historical:
Since most C, C++, and Java programmers are not accustomed to having such freedoms, they do not demand them.
Another, more valid, reason is that the language complexity would increase:
First of all, should the objects be compared with .Equals()
or with the ==
operator? Both are valid in some cases. Should we introduce new syntax to do this? Should we allow the programmer to introduce their own comparison method?
In addition, allowing to switch on objects would break underlying assumptions about the switch statement. There are two rules governing the switch statement that the compiler would not be able to enforce if objects were allowed to be switched on (see the C# version 3.0 language specification, ยง8.7.2):
Consider this code example in the hypothetical case that non-constant case values were allowed:
void DoIt()
{
String foo = "bar";
Switch(foo, foo);
}
void Switch(String val1, String val2)
{
switch ("bar")
{
// The compiler will not know that val1 and val2 are not distinct
case val1:
// Is this case block selected?
break;
case val2:
// Or this one?
break;
case "bar":
// Or perhaps this one?
break;
}
}
What will the code do? What if the case statements are reordered? Indeed, one of the reasons why C# made switch fall-through illegal is that the switch statements could be arbitrarily rearranged.
These rules are in place for a reason - so that the programmer can, by looking at one case block, know for certain the precise condition under which the block is entered. When the aforementioned switch statement grows into 100 lines or more (and it will), such knowledge is invaluable.
I recommend checking for invalid dates too:
set @PreviousStartDate=case ISDATE(@PreviousStartDate)
when 1 then @PreviousStartDate
else '1/1/2010'
end
This solution provides CONVERT_IMPLICIT operation for your condition in predicate
SELECT *
FROM xxx
WHERE CAST(dates AS date) BETWEEN '1/1/2013' and '1/2/2013'
OR
SELECT *
FROM xxx
WHERE CONVERT(date, dates, 101) BETWEEN '1/1/2013' and '1/2/2013'
Demo on SQLFiddle
I assume that your style-sheet "style.css" is already located in the assets-folder
load the web-page with jsoup:
doc = Jsoup.connect("http://....").get();
remove links to external style-sheets:
// remove links to external style-sheets
doc.head().getElementsByTag("link").remove();
set link to local style-sheet:
// set link to local stylesheet
// <link rel="stylesheet" type="text/css" href="style.css" />
doc.head().appendElement("link").attr("rel", "stylesheet").attr("type", "text/css").attr("href", "style.css");
make string from jsoup-doc/web-page:
String htmldata = doc.outerHtml();
display web-page in webview:
WebView webview = new WebView(this);
setContentView(webview);
webview.loadDataWithBaseURL("file:///android_asset/.", htmlData, "text/html", "UTF-8", null);
int ArraySize = 400;
int[] terms = new int[ArraySize];
for(int runs = 0; runs < ArraySize; runs++)
{
terms[runs] = runs;
}
That would be how I'd code it.
Another simple solution is to add jackson-databind dependency in POM.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.1</version>
</dependency>
Keep Rest of the code as it is.
Call the recreate method of the activity.
I Know it's late but this may help, this is an example how I write custom adapter class for different click actions
public class CustomAdapter extends BaseAdapter {
TextView title;
Button button1,button2;
public long getItemId(int position) {
return position;
}
public int getCount() {
return mAlBasicItemsnav.size(); // size of your list array
}
public Object getItem(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.listnavsub_layout, null, false); // use sublayout which you want to inflate in your each list item
}
title = (TextView) convertView.findViewById(R.id.textViewnav); // see you have to find id by using convertView.findViewById
title.setText(mAlBasicItemsnav.get(position));
button1=(Button) convertView.findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//your click action
// if you have different click action at different positions then
if(position==0)
{
//click action of 1st list item on button click
}
if(position==1)
{
//click action of 2st list item on button click
}
});
// similarly for button 2
button2=(Button) convertView.findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//your click action
});
return convertView;
}
}
Python (until version 3) supports "old-style" and new-style classes. New-style classes are derived from object
and are what you are using, and invoke their base class through super()
, e.g.
class X(object):
def __init__(self, x):
pass
def doit(self, bar):
pass
class Y(X):
def __init__(self):
super(Y, self).__init__(123)
def doit(self, foo):
return super(Y, self).doit(foo)
Because python knows about old- and new-style classes, there are different ways to invoke a base method, which is why you've found multiple ways of doing so.
For completeness sake, old-style classes call base methods explicitly using the base class, i.e.
def doit(self, foo):
return X.doit(self, foo)
But since you shouldn't be using old-style anymore, I wouldn't care about this too much.
Python 3 only knows about new-style classes (no matter if you derive from object
or not).
There are moduli other than powers of 2 for which efficient algorithms exist.
For example, if x is 32 bits unsigned int then x % 3 = popcnt (x & 0x55555555) - popcnt (x & 0xaaaaaaaa)
First off I should point out that css animations would probably work best if you are doing this a lot but I ended getting the desired effect by wrapping .scrollLeft inside .animate
$('.swipeRight').click(function()
{
$('.swipeBox').animate( { scrollLeft: '+=460' }, 1000);
});
$('.swipeLeft').click(function()
{
$('.swipeBox').animate( { scrollLeft: '-=460' }, 1000);
});
The second parameter is speed, and you can also add a third parameter if you are using smooth scrolling of some sort.
Without using any extra plugins,
var myOptions = {
val1 : 'text1',
val2 : 'text2'
};
var mySelect = $('#mySelect');
$.each(myOptions, function(val, text) {
mySelect.append(
$('<option></option>').val(val).html(text)
);
});
If you had lots of options, or this code needed to be run very frequently, then you should look into using a DocumentFragment instead of modifying the DOM many times unnecessarily. For only a handful of options, I'd say it's not worth it though.
------------------------------- Added --------------------------------
DocumentFragment
is good option for speed enhancement, but we cannot create option element using document.createElement('option')
since IE6 and IE7 are not supporting it.
What we can do is, create a new select element and then append all options. Once loop is finished, append it to actual DOM object.
var myOptions = {
val1 : 'text1',
val2 : 'text2'
};
var _select = $('<select>');
$.each(myOptions, function(val, text) {
_select.append(
$('<option></option>').val(val).html(text)
);
});
$('#mySelect').append(_select.html());
This way we'll modify DOM for only one time!
You're going to need DATEPART here. You can concatenate the results of the DATEPART calls together.
To get the month abbreviations, you might be able to use DATENAME; if that doesn't work for you, you can use a CASE statement on the DATEPART.
DATEPART also works for the time field.
I can think of a couple of ways of getting the AM/PM indicator, including comparing new dates built via DATEPART or calculating the total seconds elapsed in the day and comparing that to known AM/PM thresholds.
I hope this might help you
<!DOCTYPE html>
<html>
<head>
<style>
:root:after {
content: "Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark Watermark ";
position: fixed;
transform: rotate(300deg);
-webkit-transform: rotate(300deg);
color: rgb(187, 182, 182);
top:0;
z-index: -1;
}
</style>
</head>
<body>
<p>hey my name is JHM</p>
</body>
</html>
_x000D_
If key
isn't an int
or float
but a str
ing, you need to convert it to an int
first by doing
key = int(key)
or to a float
by doing
key = float(key)
Otherwise, what you have in your question should work, but
if (key < 1) or (key > 34):
or
if not (1 <= key <= 34):
would be a bit clearer.
This error happened to me when I was using Visual Studio Code. I think it must have been because I was trying to build a project while there was an executable running in the same bin\debug folder. I stopped the executable, closed the folder, reopened, rebuilt, and the error went away.
Use the .text()
function:
var text = $("<p> example ive got a string</P>").text();
Update: As Brilliand points out below, if the input string does not contain any tags and you are unlucky enough, it might be treated as a CSS selector. So this version is more robust:
var text = $("<div/>").html("<p> example ive got a string</P>").text();
Downside of all answers here is that they use static field names, so I wrote an adjusted version in OOP style. Assumed you are using getter methods you could directly use this Class and use the field name as parameter. Probably someone find it useful.
class CustomSort{
public $field = '';
public function cmp($a, $b)
{
/**
* field for order is in a class variable $field
* using getter function with naming convention getVariable() we set first letter to uppercase
* we use variable variable names - $a->{'varName'} would directly access a field
*/
return strcmp($a->{'get'.ucfirst($this->field)}(), $b->{'get'.ucfirst($this->field)}());
}
public function sortObjectArrayByField($array, $field)
{
$this->field = $field;
usort($array, array("Your\Namespace\CustomSort", "cmp"));;
return $array;
}
}
I had the same problem.please do the following it may help you: By Default List View Threshold set at only 5,000 items this is because of Sharepoint server performance.
To Change the LVT:
Click OK to save it.
JSON-js - JSON in JavaScript.
To convert an object to a string, use JSON.stringify
:
var json_text = JSON.stringify(your_object, null, 2);
To convert a JSON string to object, use JSON.parse
:
var your_object = JSON.parse(json_text);
It was recently recommended by John Resig:
...PLEASE start migrating your JSON-using applications over to Crockford's json2.js. It is fully compatible with the ECMAScript 5 specification and gracefully degrades if a native (faster!) implementation exists.
In fact, I just landed a change in jQuery yesterday that utilizes the JSON.parse method if it exists, now that it has been completely specified.
I tend to trust what he says on JavaScript matters :)
All modern browsers (and many older ones which aren't ancient) support the JSON object natively. The current version of Crockford's JSON library will only define JSON.stringify
and JSON.parse
if they're not already defined, leaving any browser native implementation intact.
I combined these two answers: https://stackoverflow.com/a/9524878/86967 and https://stackoverflow.com/a/7390874/86967 and did some escaping so that this could be used from inside a makefile.
.PHONY: no_targets__ list
no_targets__:
list:
sh -c "$(MAKE) -p no_targets__ | awk -F':' '/^[a-zA-Z0-9][^\$$#\/\\t=]*:([^=]|$$)/ {split(\$$1,A,/ /);for(i in A)print A[i]}' | grep -v '__\$$' | sort"
.
$ make -s list
build
clean
default
distclean
doc
fresh
install
list
makefile ## this is kind of extraneous, but whatever...
run
In my case, I opened my .csproj file in notepad and removed the following three lines. Worked like a charm:
<Import Project="..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props" Condition="Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" />
<Import Project="..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props" Condition="Exists('..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props')" />
<Import Project="..\packages\Microsoft.Net.Compilers.1.3.2\build\Microsoft.Net.Compilers.props" Condition="Exists('..\packages\Microsoft.Net.Compilers.1.3.2\build\Microsoft.Net.Compilers.props')" />
Gnome terminal defaults to ControlShiftv
OSX terminal defaults to Commandv. You can also use CommandControlv to paste the text in escaped form.
Windows 7 terminal defaults to CtrlShiftInsert
I am almost sure you are not actually getting it installed correctly. Since you are trying to install it globally, you will need to run it with sudo:
sudo npm install -g bower
The solution proposed above by Sai Kiriti Badam worked for me.
I'm using Azure Databricks to read data captured from an EventHub. This contains a string column named EnqueuedTimeUtc with the following format...
12/7/2018 12:54:13 PM
I'm using a Python notebook and used the following...
import pyspark.sql.functions as func
sports_messages = sports_df.withColumn("EnqueuedTimestamp", func.to_timestamp("EnqueuedTimeUtc", "MM/dd/yyyy hh:mm:ss aaa"))
... to create a new column EnqueuedTimestamp of type "timestamp" with data in the following format...
2018-12-07 12:54:13
Declare the global variable for InputMethodManager:
private InputMethodManager im ;
Under onCreate() define it:
im = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(youredittext.getWindowToken(), 0);
Set the onClickListener to that edit text inside oncreate():
youredittext.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
im.showSoftInput(youredittext, InputMethodManager.SHOW_IMPLICIT);
}
});
This will work.
If you want to see what you haven't git add
ed yet:
git diff myfile.txt
or if you want to see already added changes
git diff --cached myfile.txt
Found this good site https://stefancosma.xyz/2018/10/01/how-to-use-tomcat-intellij-idea-community/ All credits to the author
It looks like you are calling a non static member (a property or method, specifically setTextboxText
) from a static method (specifically SumData
). You will need to either:
Make the called member static also:
static void setTextboxText(int result)
{
// Write static logic for setTextboxText.
// This may require a static singleton instance of Form1.
}
Create an instance of Form1
within the calling method:
private static void SumData(object state)
{
int result = 0;
//int[] icount = (int[])state;
int icount = (int)state;
for (int i = icount; i > 0; i--)
{
result += i;
System.Threading.Thread.Sleep(1000);
}
Form1 frm1 = new Form1();
frm1.setTextboxText(result);
}
Passing in an instance of Form1
would be an option also.
Make the calling method a non-static instance method (of Form1
):
private void SumData(object state)
{
int result = 0;
//int[] icount = (int[])state;
int icount = (int)state;
for (int i = icount; i > 0; i--)
{
result += i;
System.Threading.Thread.Sleep(1000);
}
setTextboxText(result);
}
More info about this error can be found on MSDN.
scrollViewObject.fullScroll(ScrollView.FOCUS_UP)
this works fine, but only the problem with this line is that, when data is populating in scrollViewObject, has been called immediately. You have to wait for some milliseconds until data is populated. Try this code:
scrollViewObject.postDelayed(new Runnable() {
@Override
public void run() {
scroll.fullScroll(ScrollView.FOCUS_UP);
}
}, 600);
OR
scrollViewObject.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
scrollViewObject.getViewTreeObserver().removeOnGlobalLayoutListener(this);
scrollViewObject.fullScroll(View.FOCUS_UP);
}
});
Strictly with sed:
grep ... | sed -e 's/^\(.\{N\}\).*$/\1/'
"^.*$"
literally just means select everything
"^" // anchors to the beginning of the line
".*" // zero or more of any character
"$" // anchors to end of line
Not quite sure why everyone is giving you a hard time for wanting to do this - there are several scenarios where you'd want a fixed size initialised list. And you've correctly deduced that arrays are sensible in these cases.
import array
verts=array.array('i',(0,)*1000)
For the non-pythonistas, the (0,)*1000
term is creating a tuple containing 1000 zeros. The comma forces python to recognise (0)
as a tuple, otherwise it would be evaluated as 0.
I've used a tuple instead of a list because they are generally have lower overhead.
Kaloyan Stamatov method is the best. First go to https://fonts.googleapis.com/icon?family=Material+Icons. and copy the css file. the content look like this
/* fallback */
@font-face {
font-family: 'Material Icons';
font-style: normal;
font-weight: 400;
src: url(https://fonts.gstatic.com/s/materialicons/v37/flUhRq6tzZclQEJ-Vdg-IuiaDsNc.woff2) format('woff2');
}
.material-icons {
font-family: 'Material Icons';
font-weight: normal;
font-style: normal;
font-size: 24px;
line-height: 1;
letter-spacing: normal;
text-transform: none;
display: inline-block;
white-space: nowrap;
word-wrap: normal;
direction: ltr;
-moz-font-feature-settings: 'liga';
-moz-osx-font-smoothing: grayscale;
}
Paste the source of the font to the browser to download the woff2 file https://fonts.gstatic.com/s/materialicons/v37/flUhRq6tzZclQEJ-Vdg-IuiaDsNc.woff2 Then replace the file in the original source. You can rename it if you want No need to download 60MB file from github. Dead simple My code looks like this
@font-face {
font-family: 'Material Icons';
font-style: normal;
font-weight: 400;
src: url(materialIcon.woff2) format('woff2');
}
.material-icons {
font-family: 'Material Icons';
font-weight: normal;
font-style: normal;
font-size: 24px;
line-height: 1;
letter-spacing: normal;
text-transform: none;
display: inline-block;
white-space: nowrap;
word-wrap: normal;
direction: ltr;
-moz-font-feature-settings: 'liga';
-moz-osx-font-smoothing: grayscale;
}
while materialIcon.woff2 is the downloaded and replaced woff2 file.
If you happen to be using Visual Studio Code as your IDE, this is a fun little extension to make updating package.json
a one click process.
I didn't want to import anything other than csv, and all my lists have the same number of items. The top answer here seems to make the lists into one row each, instead of one column each. Thus I took the answers here and came up with this:
import csv
list1 = ['a', 'b', 'c', 'd', 'e']
list2 = ['f', 'g', 'i', 'j','k']
with open('C:/test/numbers.csv', 'wb+') as myfile:
wr = csv.writer(myfile)
wr.writerow(("list1", "list2"))
rcount = 0
for row in list1:
wr.writerow((list1[rcount], list2[rcount]))
rcount = rcount + 1
myfile.close()
According to this excellent comparison made by GaspardP I would not choose this solution. It's not the worst, but it's not the best either. The only thing it got going for it is that it's possibly easier to understand.
I found the other two answers to be pretty hard to understand. They also produce some warnings in my compiler and the use of a find function in the decode part should result in a pretty bad efficiency. So I decided to roll my own.
Header:
#ifndef _BASE64_H_
#define _BASE64_H_
#include <vector>
#include <string>
typedef unsigned char BYTE;
class Base64
{
public:
static std::string encode(const std::vector<BYTE>& buf);
static std::string encode(const BYTE* buf, unsigned int bufLen);
static std::vector<BYTE> decode(std::string encoded_string);
};
#endif
Body:
static const BYTE from_base64[] = { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 62, 255, 62, 255, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255, 255, 255, 255, 255,
255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 63,
255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 255, 255, 255, 255, 255};
static const char to_base64[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
std::string Base64::encode(const std::vector<BYTE>& buf)
{
if (buf.empty())
return ""; // Avoid dereferencing buf if it's empty
return encode(&buf[0], (unsigned int)buf.size());
}
std::string Base64::encode(const BYTE* buf, unsigned int bufLen)
{
// Calculate how many bytes that needs to be added to get a multiple of 3
size_t missing = 0;
size_t ret_size = bufLen;
while ((ret_size % 3) != 0)
{
++ret_size;
++missing;
}
// Expand the return string size to a multiple of 4
ret_size = 4*ret_size/3;
std::string ret;
ret.reserve(ret_size);
for (unsigned int i=0; i<ret_size/4; ++i)
{
// Read a group of three bytes (avoid buffer overrun by replacing with 0)
size_t index = i*3;
BYTE b3[3];
b3[0] = (index+0 < bufLen) ? buf[index+0] : 0;
b3[1] = (index+1 < bufLen) ? buf[index+1] : 0;
b3[2] = (index+2 < bufLen) ? buf[index+2] : 0;
// Transform into four base 64 characters
BYTE b4[4];
b4[0] = ((b3[0] & 0xfc) >> 2);
b4[1] = ((b3[0] & 0x03) << 4) + ((b3[1] & 0xf0) >> 4);
b4[2] = ((b3[1] & 0x0f) << 2) + ((b3[2] & 0xc0) >> 6);
b4[3] = ((b3[2] & 0x3f) << 0);
// Add the base 64 characters to the return value
ret.push_back(to_base64[b4[0]]);
ret.push_back(to_base64[b4[1]]);
ret.push_back(to_base64[b4[2]]);
ret.push_back(to_base64[b4[3]]);
}
// Replace data that is invalid (always as many as there are missing bytes)
for (size_t i=0; i<missing; ++i)
ret[ret_size - i - 1] = '=';
return ret;
}
std::vector<BYTE> Base64::decode(std::string encoded_string)
{
// Make sure string length is a multiple of 4
while ((encoded_string.size() % 4) != 0)
encoded_string.push_back('=');
size_t encoded_size = encoded_string.size();
std::vector<BYTE> ret;
ret.reserve(3*encoded_size/4);
for (size_t i=0; i<encoded_size; i += 4)
{
// Get values for each group of four base 64 characters
BYTE b4[4];
b4[0] = (encoded_string[i+0] <= 'z') ? from_base64[encoded_string[i+0]] : 0xff;
b4[1] = (encoded_string[i+1] <= 'z') ? from_base64[encoded_string[i+1]] : 0xff;
b4[2] = (encoded_string[i+2] <= 'z') ? from_base64[encoded_string[i+2]] : 0xff;
b4[3] = (encoded_string[i+3] <= 'z') ? from_base64[encoded_string[i+3]] : 0xff;
// Transform into a group of three bytes
BYTE b3[3];
b3[0] = ((b4[0] & 0x3f) << 2) + ((b4[1] & 0x30) >> 4);
b3[1] = ((b4[1] & 0x0f) << 4) + ((b4[2] & 0x3c) >> 2);
b3[2] = ((b4[2] & 0x03) << 6) + ((b4[3] & 0x3f) >> 0);
// Add the byte to the return value if it isn't part of an '=' character (indicated by 0xff)
if (b4[1] != 0xff) ret.push_back(b3[0]);
if (b4[2] != 0xff) ret.push_back(b3[1]);
if (b4[3] != 0xff) ret.push_back(b3[2]);
}
return ret;
}
Usage:
BYTE buf[] = "ABCD";
std::string encoded = Base64::encode(buf, 4);
// encoded = "QUJDRA=="
std::vector<BYTE> decoded = Base64::decode(encoded);
A bonus here is that the decode function can also decode the URL variant of Base64 encoding.
This worked for me from within Fragment:
Fragment frg = null;
Class fragmentClass;
fragmentClass = MainFragment.class;
try {
frg = (android.support.v4.app.Fragment)
fragmentClass.newInstance();
} catch(Exception ex) {
ex.printStackTrace();
}
getFragmentManager()
.beginTransaction()
.replace(R.id.flContent, frg)
.commit();
For Ubuntu 14.04 and Android try:
hcitool scan #get hardware address
sudo bluetooth-agent PIN HARDWARE-ADDRESS
PIN dialog pops up on Android device. Enter same PIN.
Note: sudo apt-get install bluez-utils
might be necessary.
Note2: If PIN dialog does not appear, try pairing from Android first (will fail because of wrong PIN). Then try again as described above.
If you need to handle multiple currencies, various number formats etc. I can recommend autoNumeric. Works a treat. Have been using it successfully for several years now.
i. Please check the InnerException
property of the TypeInitializationException
ii. Also, this may occur due to mismatch between the runtime versions of the assemblies. Please verify the runtime versions of the main assembly (calling application) and the referred assembly
If you have any issues in your controller to map to an unique URL you get this error.
The best way to find the cause of issue is exclude all controllers from project. Then try running the app by enabling one controller or one or more methods in a controller at a time to find the controllers/ controller method(S) which have an issue. Or you could get smart and do a binary search logic to find the disable enable multiple controller/methods to find the faulty ones.
Some of the causes is
Having public methods in controller without HTTP method attributes
Having multiple methods with same Http attributes which could map to same api call if you are not using "[action]" based mapping
If you are using versioning make sure you have the method in all the controller versions (if using inheritance even though you use from base)
In Angular 5
you can just say
this.http.get<Example>('assets/example.json')
This will give you Observable<Example>
This will definately work for you.
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/top_bg" >
<Button
android:id="@+id/btn_report_lbAlert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="@dimen/btn_back_margin_left"
android:background="@drawable/btn_edit" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_centerVertical="true"
android:text="FlitsLimburg"
android:textColor="@color/white"
android:textSize="@dimen/tv_header_text"
android:textStyle="bold" />
<Button
android:id="@+id/btn_refresh_lbAlert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="@dimen/btn_back_margin_right"
android:background="@drawable/btn_refresh" />
</RelativeLayout>
So I was having this problem, none of the other remedies worked. The error message was opaque, but checking dmesg was key:
[ 10.118255] NVRM: API mismatch: the client has the version 410.79, but
NVRM: this kernel module has the version 384.130. Please
NVRM: make sure that this kernel module and all NVIDIA driver
NVRM: components have the same version.
However I had completely removed the 384 version, and removed any remaining kernel drivers nvidia-384*
. But even after reboot, I was still getting this. Seeing this meant that the kernel was still compiled to reference 384, but was only finding 410. So I recompiled my kernel:
# uname -a # find the kernel it's using
Linux blah 4.13.0-43-generic #48~16.04.1-Ubuntu SMP Thu May 17 12:56:46 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
# update-initramfs -c -k 4.13.0-43-generic #recompile it
# reboot
And then it worked.
After removing 384, I still had 384 files in: /var/lib/dkms/nvidia-XXX/XXX.YY/4.13.0-43-generic/x86_64/module /lib/modules/4.13.0-43-generic/kernel/drivers
I recommend using the locate
command (not installed by default) rather than searching the filesystem every time.
Try this:
C:/Users/(YourUserName)/
.gitconfig
let imageDataDict:[String: UIImage] = ["image": image]
// post a notification
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict)
// `default` is now a property, not a method call
// Register to receive notification in your class
NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)
// handle notification
func showSpinningWheel(_ notification: NSNotification) {
print(notification.userInfo ?? "")
if let dict = notification.userInfo as NSDictionary? {
if let id = dict["image"] as? UIImage{
// do something with your image
}
}
}
let imageDataDict:[String: UIImage] = ["image": image]
// post a notification
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict)
// `default` is now a property, not a method call
// Register to receive notification in your class
NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)
// handle notification
@objc func showSpinningWheel(_ notification: NSNotification) {
print(notification.userInfo ?? "")
if let dict = notification.userInfo as NSDictionary? {
if let id = dict["image"] as? UIImage{
// do something with your image
}
}
}
You can use some thing like this
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div ng-app="" ng-init="btn1=false" ng-init="btn2=false">_x000D_
<p>_x000D_
<input type="submit" ng-disabled="btn1||btn2" ng-click="btn1=true" ng-model="btn1" />_x000D_
</p>_x000D_
<p>_x000D_
<button ng-disabled="btn1||btn2" ng-model="btn2" ng-click="btn2=true">Click Me!</button>_x000D_
</p>_x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Here's another CSS only solution that works with any HTML layout.
It works with any element you need to switch. Whatever your toggle layout is you just put it inside a couple of elements with the if-collapsed
and if-not-collapsed
classes inside the toggle element.
The only catch is that you have to make sure you put the desired initial state of the toggle. If it's initially closed, then put a collapsed
class on the toggle.
It also requires the :not
selector, so it doesn't work on IE8.
HTML example:
<a class="btn btn-primary collapsed" data-toggle="collapse" href="#collapseExample">
<!--You can put any valid html inside these!-->
<span class="if-collapsed">Open</span>
<span class="if-not-collapsed">Close</span>
</a>
<div class="collapse" id="collapseExample">
<div class="well">
...
</div>
</div>
Less version:
[data-toggle="collapse"] {
&.collapsed .if-not-collapsed {
display: none;
}
&:not(.collapsed) .if-collapsed {
display: none;
}
}
CSS version:
[data-toggle="collapse"].collapsed .if-not-collapsed {
display: none;
}
[data-toggle="collapse"]:not(.collapsed) .if-collapsed {
display: none;
}
The built-in module querystring
is what you're looking for:
var querystring = require("querystring");
var result = querystring.stringify({query: "SELECT name FROM user WHERE uid = me()"});
console.log(result);
#prints 'query=SELECT%20name%20FROM%20user%20WHERE%20uid%20%3D%20me()'
a = a + b - (b=a);
It's very simple, but it may raise a warning.
If you're using zsh and it has not been set up to read .bashrc, you need to add the Miniconda directory to the zsh shell PATH environment variable. Add this to your .zshrc
:
export PATH="/home/username/miniconda/bin:$PATH"
Make sure to replace /home/username/miniconda
with your actual path.
Save, exit the terminal and then reopen the terminal. conda
command should work.
You can't use primitive types as generic arguments in Java. Use instead:
Map<String, Integer> myMap = new HashMap<String, Integer>();
With auto-boxing/unboxing there is little difference in the code. Auto-boxing means you can write:
myMap.put("foo", 3);
instead of:
myMap.put("foo", new Integer(3));
Auto-boxing means the first version is implicitly converted to the second. Auto-unboxing means you can write:
int i = myMap.get("foo");
instead of:
int i = myMap.get("foo").intValue();
The implicit call to intValue()
means if the key isn't found it will generate a NullPointerException
, for example:
int i = myMap.get("bar"); // NullPointerException
The reason is type erasure. Unlike, say, in C# generic types aren't retained at runtime. They are just "syntactic sugar" for explicit casting to save you doing this:
Integer i = (Integer)myMap.get("foo");
To give you an example, this code is perfectly legal:
Map<String, Integer> myMap = new HashMap<String, Integer>();
Map<Integer, String> map2 = (Map<Integer, String>)myMap;
map2.put(3, "foo");
You could also use this:
ini_alter('date.timezone','Asia/Calcutta');
You should call this before calling any date function. It accepts the key as the first parameter to alter PHP settings during runtime and the second parameter is the value.
I had done these things before I figured out this:
date_default_timezone_set("Asia/Calcutta");
- did not workini_alter()
- IT WORKEDdate_default_timezone_set("Asia/Calcutta");
- IT WORKEDFor me the init_alter()
method got it all working.
I am running Apache 2 (pre-installed), PHP 5.3 on OSX mountain lion
It works for me:
<div class="text-center">
<ul class="pagination pagination-lg">
<li>
<a href="#" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
<li><a href="#">5</a></li>
<li>
<a href="#" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</ul>
Not a regexp expert, but I think you could use a negative lookahead from the start, e.g. ^(?!foo).*$
shouldn't match anything starting with foo
.
I assume that you're running a Linux, and you're using gEdit to edit your files. In the /etc/nginx/sites-enabled
, it may have left a temp file e.g. default~
(watch the ~
).
Depending on your editor, the file could be named .save
or something like it. Just run $ ls -lah
to see which files are unintended to be there and remove them (Thanks @Tisch for this).
Delete this file, and it will solve your problem.
IMHO, the best explanation about its meaning gave us Stroustrup + take into account examples of Dรกniel Sรกndor and Mohan:
Stroustrup:
Now I was seriously worried. Clearly we were headed for an impasse or a mess or both. I spent the lunchtime doing an analysis to see which of the properties (of values) were independent. There were only two independent properties:
has identity
โ i.e. and address, a pointer, the user can determine whether two copies are identical, etc.can be moved from
โ i.e. we are allowed to leave to source of a "copy" in some indeterminate, but valid stateThis led me to the conclusion that there are exactly three kinds of values (using the regex notational trick of using a capital letter to indicate a negative โ I was in a hurry):
iM
: has identity and cannot be moved fromim
: has identity and can be moved from (e.g. the result of casting an lvalue to a rvalue reference)
Im
: does not have identity and can be moved from.The fourth possibility,
IM
, (doesnโt have identity and cannot be moved) is not useful inC++
(or, I think) in any other language.In addition to these three fundamental classifications of values, we have two obvious generalizations that correspond to the two independent properties:
i
: has identitym
: can be moved fromThis led me to put this diagram on the board:
Naming
I observed that we had only limited freedom to name: The two points to the left (labeled
iM
andi
) are what people with more or less formality have calledlvalues
and the two points on the right (labeledm
andIm
) are what people with more or less formality have calledrvalues
. This must be reflected in our naming. That is, the left "leg" of theW
should have names related tolvalue
and the right "leg" of theW
should have names related torvalue.
I note that this whole discussion/problem arise from the introduction of rvalue references and move semantics. These notions simply donโt exist in Stracheyโs world consisting of justrvalues
andlvalues
. Someone observed that the ideas that
- Every
value
is either anlvalue
or anrvalue
- An
lvalue
is not anrvalue
and anrvalue
is not anlvalue
are deeply embedded in our consciousness, very useful properties, and traces of this dichotomy can be found all over the draft standard. We all agreed that we ought to preserve those properties (and make them precise). This further constrained our naming choices. I observed that the standard library wording uses
rvalue
to meanm
(the generalization), so that to preserve the expectation and text of the standard library the right-hand bottom point of theW
should be namedrvalue.
This led to a focused discussion of naming. First, we needed to decide on
lvalue.
Shouldlvalue
meaniM
or the generalizationi
? Led by Doug Gregor, we listed the places in the core language wording where the wordlvalue
was qualified to mean the one or the other. A list was made and in most cases and in the most tricky/brittle textlvalue
currently meansiM
. This is the classical meaning of lvalue because "in the old days" nothing was moved;move
is a novel notion inC++0x
. Also, naming the topleft point of theW
lvalue
gives us the property that every value is anlvalue
or anrvalue
, but not both.So, the top left point of the
W
islvalue
and the bottom right point isrvalue.
What does that make the bottom left and top right points? The bottom left point is a generalization of the classical lvalue, allowing for move. So it is ageneralized lvalue.
We named itglvalue.
You can quibble about the abbreviation, but (I think) not with the logic. We assumed that in serious usegeneralized lvalue
would somehow be abbreviated anyway, so we had better do it immediately (or risk confusion). The top right point of the W is less general than the bottom right (now, as ever, calledrvalue
). That point represent the original pure notion of an object you can move from because it cannot be referred to again (except by a destructor). I liked the phrasespecialized rvalue
in contrast togeneralized lvalue
butpure rvalue
abbreviated toprvalue
won out (and probably rightly so). So, the left leg of the W islvalue
andglvalue
and the right leg isprvalue
andrvalue.
Incidentally, every value is either a glvalue or a prvalue, but not both.This leaves the top middle of the
W
:im
; that is, values that have identity and can be moved. We really donโt have anything that guides us to a good name for those esoteric beasts. They are important to people working with the (draft) standard text, but are unlikely to become a household name. We didnโt find any real constraints on the naming to guide us, so we picked โxโ for the center, the unknown, the strange, the xpert only, or even x-rated.
I met a similar problem when I tried to store my existing repo in my Ubunt One
account, I fixed it by the following steps:
Step-1: create remote repo
$ cd ~/Ubuntu\ One/
$ mkdir <project-name>
$ cd <project-name>
$ mkdir .git
$ cd .git
$ git --bare init
Step-2: add the remote
$ git remote add origin /home/<linux-user-name>/Ubuntu\ One/<project-name>/.git
Step-3: push the exising git reop to the remote
$ git push -u origin --all
Ok, for @AndrewS solution to work with v7 appCompat library:
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:someNamespace="http://schemas.android.com/apk/res-auto" >
<item
android:id="@+id/saved_badge"
someNamespace:showAsAction="always"
android:icon="@drawable/shape_notification" />
</menu>
.
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.main, menu);
MenuItem item = menu.findItem(R.id.saved_badge);
MenuItemCompat.setActionView(item, R.layout.feed_update_count);
View view = MenuItemCompat.getActionView(item);
notifCount = (Button)view.findViewById(R.id.notif_count);
notifCount.setText(String.valueOf(mNotifCount));
}
private void setNotifCount(int count){
mNotifCount = count;
supportInvalidateOptionsMenu();
}
The rest of the code is the same.
It is a server error, not a client error. If server errors weren't to be returned to the client, there wouldn't have been created an entire status code class for them (i.e. 5xx).
You can't hide the fact that you either made a programming error or some service you rely on is unavailable, and that certainly isn't the client's fault. Returning any other range of code in those cases than the 5xx series would make no sense.
RFC 7231 mentions in section 6.6. Server Error 5xx:
The 5xx (Server Error) class of status code indicates that the server is aware that it has erred or is incapable of performing the requested method.
This is exactly the case. There's nothing "internal" about the code "500 Internal Server Error" in the sense that it shouldn't be exposed to the client.
I had many issues involving C# and SqlServer. I ended up doing the following:
Also make sure that all your machines run on the same timezone.
Regarding the different result sets you get, your first example is "July First" while the second is "4th of July" ...
Also, the second example can be also interpreted as "April 7th", it depends on your server localization configuration (my solution doesn't suffer from this issue).
EDIT: hh was replaced with HH, as it doesn't seem to capture the correct hour on systems with AM/PM as opposed to systems with 24h clock. See the comments below.
If you want to read a CSV File with encoding utf-8, a minimalistic approach that I recommend you is to use something like this:
with open(file_name, encoding="utf8") as csv_file:
With that statement, you can use later a CSV reader to work with.
If you are looking for the diff on a specific commit and you want to use the github UI instead of the command line (say you want to link it to other folks), you can do:
https://github.com/<org>/<repo>/commit/<commit-sha>/<path-to-file>
For example:
Note the Previous and Next links at the top right that allow you to navigate through all the files in the commit.
This only works for a specific commit though, not for comparing between any two arbitrary versions.
Since I have recently developed an Android application using gyroscope data (steady compass), I tried to collect a list with such devices. This is not an exhaustive list at all, but it is what I have so far:
*** Phones:
*** Tablets:
Hope the list keeps growing and hope that gyros will be soon available on mid and low price smartphones.
By chance: Default error pages often contain detailed information, e.g.
Apache/{Version} ({OS}) {Modules} PHP/{Version} {Modules} Server at {Domain}
Not so easy: Find out which versions of PHP applications run on the server and which version of PHP they require.
Another approach, only mentioned for the sake of completeness; please forget after reading: You could (but you won't!) detect the PHP version by trying known exploits.
Sometimes, it may help switching off AllowAutoRedirect
and setting both login POST
and page GET
requests the same user agent.
request.UserAgent = userAgent;
request.AllowAutoRedirect = false;
You can try this before using job_titles
string:
source = unicode(job_titles, 'utf-8')
Often an attribute is used to describe the mechanism or real-world thing.
A property is used to describe the model.
For instance, a document (sitting on your desk) may have the attribute that it is a draft.
The class that models documents has a property to indicate whether or not it's a draft. In this case the property captures the state.
Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3
NOTE: this component only works in boostrap-4 since version 1.13.0
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
<option>Mustard</option>_x000D_
<option>Ketchup</option>_x000D_
<option>Relish</option>_x000D_
</select>
_x000D_
The chapter on CAST and CONVERT on MSDN Books Online, you've missed the right answer by one line.... you can use style no. 121 (ODBC canonical (with milliseconds)) to get the result you're looking for:
SELECT CONVERT(VARCHAR(30), GETDATE(), 121)
This gives me the output of:
2012-04-14 21:44:03.793
Update: based on your updated question - of course this won't work - you're converting a string (this: '4/14/2012 2:44:01 PM'
is just a string - it's NOT a datetime!) to a string......
You need to first convert the string you have to a DATETIME
and THEN convert it back to a string!
Try this:
SELECT CONVERT(VARCHAR(30), CAST('4/14/2012 2:44:01 PM' AS DATETIME), 121)
Now you should get:
2012-04-14 14:44:01.000
All zeroes for the milliseconds, obviously, since your original values didn't include any ....
You guys are completely right numbers can only go in the numeric field. I use the exact same thing as already listed with a bit of css styling on a span tag:
<span>$</span><input type="number" min="0.01" step="0.01" max="2500" value="25.67">
Then add a bit of styling magic:
span{
position:relative;
margin-right:-20px
}
input[type='number']{
padding-left:20px;
text-align:left;
}
Complementing the other answers, you can use the option --no-cache-dir
to disable caching in pip. My virtual machine was crashing when installing many packages at once with pip install -r requirements.txt
. What solved for me was:
pip install --no-cache-dir -r requirements.txt
I've spoken to Tab Atkins (author of the flexbox spec) about this, and this is what we came up with:
HTML:
<div class="content">
<div class="box">
<div class="column">Column 1</div>
<div class="column">Column 2</div>
<div class="column">Column 3</div>
</div>
</div>
CSS:
.content {
flex: 1;
display: flex;
overflow: auto;
}
.box {
display: flex;
min-height: min-content; /* needs vendor prefixes */
}
Here are the pens:
The reason this works is because align-items: stretch
doesn't shrink its items if they have an intrinsic height, which is accomplished here by min-content
.
@Transactional
@RequestMapping(value = { "/getDatabaseTables" }, method = RequestMethod.GET)
public @ResponseBody String getDatabaseTables() throws Exception{
Connection con = ((SessionImpl) sessionFactory.getCurrentSession()).connection();
DatabaseMetaData md = con.getMetaData();
ResultSet rs = md.getTables(null, null, "%", null);
HashMap<String,List<String>> databaseTables = new HashMap<String,List<String>>();
List<String> tables = new ArrayList<String>();
String db = "";
while (rs.next()) {
tables.add(rs.getString(3));
db = rs.getString(1);
}
List<String> database = new ArrayList<String>();
database.add(db);
databaseTables.put("database", database);
Collections.reverse(tables);
databaseTables.put("tables", tables);
return new ObjectMapper().writeValueAsString(databaseTables);
}
@Transactional
@RequestMapping(value = { "/getTableDetails" }, method = RequestMethod.GET)
public @ResponseBody String getTableDetails(@RequestParam(value="tablename")String tablename) throws Exception{
System.out.println("...tablename......"+tablename);
Connection con = ((SessionImpl) sessionFactory.getCurrentSession()).connection();
Statement st = con.createStatement();
String sql = "select * from "+tablename;
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metaData = rs.getMetaData();
int rowCount = metaData.getColumnCount();
List<HashMap<String,String>> databaseColumns = new ArrayList<HashMap<String,String>>();
HashMap<String,String> columnDetails = new HashMap<String,String>();
for (int i = 0; i < rowCount; i++) {
columnDetails = new HashMap<String,String>();
Method method = com.mysql.jdbc.ResultSetMetaData.class.getDeclaredMethod("getField", int.class);
method.setAccessible(true);
com.mysql.jdbc.Field field = (com.mysql.jdbc.Field) method.invoke(metaData, i+1);
columnDetails.put("columnName", field.getName());//metaData.getColumnName(i + 1));
columnDetails.put("columnType", metaData.getColumnTypeName(i + 1));
columnDetails.put("columnSize", field.getLength()+"");//metaData.getColumnDisplaySize(i + 1)+"");
columnDetails.put("columnColl", field.getCollation());
columnDetails.put("columnNull", ((metaData.isNullable(i + 1)==0)?"NO":"YES"));
if (field.isPrimaryKey()) {
columnDetails.put("columnKEY", "PRI");
} else if(field.isMultipleKey()) {
columnDetails.put("columnKEY", "MUL");
} else if(field.isUniqueKey()) {
columnDetails.put("columnKEY", "UNI");
} else {
columnDetails.put("columnKEY", "");
}
columnDetails.put("columnAINC", (field.isAutoIncrement()?"AUTO_INC":""));
databaseColumns.add(columnDetails);
}
HashMap<String,List<HashMap<String,String>>> tableColumns = new HashMap<String,List<HashMap<String,String>>>();
Collections.reverse(databaseColumns);
tableColumns.put("columns", databaseColumns);
return new ObjectMapper().writeValueAsString(tableColumns);
}
You have to explicitly define the constructor in B and explicitly call the constructor for the parent.
B(int x) : A(x) { }
or
B() : A(5) { }
If you are styling calc in a GWT project, its parser might not parse calc for you as it did not for me... the solution is to wrap it in a css literal like this:
height: literal("-moz-calc(100% - (20px + 30px))");
height: literal("-webkit-calc(100% - (20px + 30px))");
height: literal("calc(100% - (20px + 30px))");
You can also create a custom reverse mechanism in python. Which can be use anywhere for looping an iterable backwards
class Reverse:
"""Iterator for looping over a sequence backwards"""
def __init__(self, seq):
self.seq = seq
self.index = len(seq)
def __iter__(self):
return self
def __next__(self):
if self.index == 0:
raise StopIteration
self.index -= 1
return self.seq[self.index]
>>> d = [1,2,3,4,5]
>>> for i in Reverse(d):
... print(i)
...
5
4
3
2
1
And if you want to vary the speed and include callbacks simply add them like this :
jQuery.fn.extend({
slideRightShow: function(speed,callback) {
return this.each(function() {
$(this).show('slide', {direction: 'right'}, speed, callback);
});
},
slideLeftHide: function(speed,callback) {
return this.each(function() {
$(this).hide('slide', {direction: 'left'}, speed, callback);
});
},
slideRightHide: function(speed,callback) {
return this.each(function() {
$(this).hide('slide', {direction: 'right'}, speed, callback);
});
},
slideLeftShow: function(speed,callback) {
return this.each(function() {
$(this).show('slide', {direction: 'left'}, speed, callback);
});
}
});
You can use Length annotation for a column. By using it you can maximize or minimize column length. Length annotation only be used for Strings
.
@Column(name = "NAME", nullable = false, length = 50)
@Length(max = 50)
public String getName() {
return this.name;
}
Don't use str() method directly in html instead use with y=x|string()
<div class="row">
{% for x in range(photo_upload_count) %}
{% with y=x|string() %}
<div col-md-4 >
<div class="col-md-12">
<div class="card card-primary " style="border:1px solid #000">
<div class="card-body">
{% if data['profile_photo']!= None: %}
<img class="profile-user-img img-responsive" src="{{ data['photo_'+y] }}" width="200px" alt="User profile picture">
{% else: %}
<img class="profile-user-img img-responsive" src="static/img/user.png" width="200px" alt="User profile picture">
{% endif %}
</div>
<div class="card-footer text-center">
<a href="{{value}}edit_photo/{{ 'photo_'+y }}" class="btn btn-primary">Edit</a>
</div>
</div>
</div>
</div>
{% endwith %}
{% endfor %}
</div>
You can use Guava's Streams
.
concat(Stream<? extends T>... streams)
method, which will be very short with static imports:
Stream stream = concat(stream1, stream2, of(element));
In wamp/alias/mySite.conf, be careful to add a slash "/" at the end of the alias' adress :
Replace :
Alias /mySite/ "D:/Work/Web/mySite/www"
By :
Alias /mySite/ "D:/Work/Web/mySite/www/"
Or the index.php is not read correctly.
for latest Jquery. Simply:
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
I suspect the or one or more characters had no match in the target code page part of the error.
If you remove the rows with values in that column, does it load? Can you identify, in other words, the rows which cause the package to fail? It could be the data is too long, or it could be that there's some funky character in there SQL Server doesn't like.
With rails >= 3.0, you can simply use the placeholder
option.
f.text_field :attr, placeholder: "placeholder text"
You can try it, use this method to make it easy
/**
* array insert element on position
*
* @link https://vector.cool
*
* @since 1.01.38
*
* @param array $original
* @param mixed $inserted
* @param int $position
* @return array
*/
function array_insert(&$original, $inserted, int $position): array
{
array_splice($original, $position, 0, array($inserted));
return $original;
}
$columns = [
['name' => '????', 'column' => 'item_name'],
['name' => '????', 'column' => 'start_time'],
['name' => '????', 'column' => 'full_name'],
['name' => '????', 'column' => 'phone'],
['name' => '????', 'column' => 'create_time']
];
$col = ['name' => '????', 'column' => 'user_id'];
$columns = array_insert($columns, $col, 3);
print_r($columns);
Print out:
Array
(
[0] => Array
(
[name] => ????
[column] => item_name
)
[1] => Array
(
[name] => ????
[column] => start_time
)
[2] => Array
(
[name] => ????
[column] => full_name
)
[3] => Array
(
[name] => ????1
[column] => num_of_people
)
[4] => Array
(
[name] => ????
[column] => phone
)
[5] => Array
(
[name] => ????
[column] => user_id
)
[6] => Array
(
[name] => ????
[column] => create_time
)
)
There is now an XML alternative:
<ImageView
android:id="@+id/example"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/example"
android:alpha="0.7" />
It is: android:alpha="0.7"
With a value from 0 (transparent) to 1 (opaque).
Seems like serialize is the one I'm going to use for 2 reasons:
Someone pointed out that unserialize is faster than json_decode and a 'read' case sounds more probable than a 'write' case.
I've had trouble with json_encode when having strings with invalid UTF-8 characters. When that happens the string ends up being empty causing loss of information.
First, you need to configure your computer to get a static IP from your router. Instructions for how to do this can be found: here
For example, let's say you picked the IP address 192.168.1.102. After the above step is completed, you should be able to get to the website on your local machine by going to both http://localhost and http://192.168.1.102, since your computer will now always have that IP address on your network.
If you look up your IP address (such as http://www.ip-adress.com/), the IP you see is actually the IP of your router. When your friend accesses your website, you'll give him this IP. However, you need to tell your router that when it gets a request for a webpage, forward that request to your server. This is done through port forwarding.
Two examples of how to do this can be found here and here, although the exact screens you see will vary depending on the manufacturer of your router (Google for exact instructions, if needed).
For the Linksys router I have, I enter http://192.168.1.1/, enter my username/password, Applications & Gaming tab > Port Range Forward. Enter the application name (whatever you want to call it), start port (80), end port (80), protocol (TCP), ip address (using the above example, you would enter 192.168.1.102, which is the static IP you assigned your server), and be sure to check to enable the forwarding. Restart your router and the changes should take effect.
Having done all that, your friend should now be able to access your webpage by going to his web browser on his machine and entering http://IP.address.of.your.computer (the same one you see when you go here ).
As mentioned earlier, the IP address assigned to you by your ISP will eventually change whether you sign offline or not. I strongly recommend using DynDns, which is absolutely free. You can choose a hostname at their domain (such as cuga.kicks-ass.net) and your friend can then always access your website by simply going to http://cuga.kicks-ass.net in his browser. Here is their site again: DynDns
I hope this helps.
So..it was SSL problem. Whatever I was doing was absolutely correct. Only that I was not using the ssl option. So I added "-Usessl true" to my original command and it worked.
function isUnset(inp) {
return (typeof inp === 'undefined')
}
Returns false if variable is set, and true if is undefined.
Then use:
if (isUnset(var)) {
// initialize variable here
}
You could just use the imageView's image cache. It will render the entire view as it is layed out (scaled,bordered with a background etc) to a new bitmap.
just make sure it built.
imageView.buildDrawingCache();
Bitmap bmap = imageView.getDrawingCache();
there's your bitmap as the screen saw it.
I do not think you can do it in CSS, but you can calculate a pixel perfect width with javascript. Let's say you use jQuery:
HTML code:
<div id="container">
<div id="col1"></div>
<div id="col2"></div>
<div id="col3"></div>
</div>
JS Code:
$(function(){
var total = $("#container").width();
$("#col1").css({width: Math.round(total/3)+"px"});
$("#col2").css({width: Math.round(total/3)+"px"});
$("#col3").css({width: Math.round(total/3)+"px"});
});
Try Jedi! There's a Vim plugin at https://github.com/davidhalter/jedi-vim.
It works just much better than anything else for Python in Vim. It even has support for renaming, goto, etc. The best part is probably that it really tries to understand your code (decorators, generators, etc. Just look at the feature list).
That sort of functionality is going to require some Javascript, but it is probably possible just to use CSS (in browsers other than IE6&7).
[float(i) for i in lst]
to be precise, it creates a new list with float values. Unlike the map
approach it will work in py3k.
If you are stuck on django 1.2 like I am and RedirectView doesn't exist, another route-centric way to add the redirect mapping is using:
(r'^match_rules/$', 'django.views.generic.simple.redirect_to', {'url': '/new_url'}),
You can also re-route everything on a match. This is useful when changing the folder of an app but wanting to preserve bookmarks:
(r'^match_folder/(?P<path>.*)', 'django.views.generic.simple.redirect_to', {'url': '/new_folder/%(path)s'}),
This is preferable to django.shortcuts.redirect if you are only trying to modify your url routing and do not have access to .htaccess, etc (I'm on Appengine and app.yaml doesn't allow url redirection at that level like an .htaccess).
I had a similar error..This might be due to two reasons. a) If you have used variables, re-evaluate the expressions in which variables are used and make sure the expression is evaluated without errors. b) If you are deleting the excel sheet and creating excel sheet on the fly in your package.
The "vw" solution has a problem when going to very small screens. You can set the base size and go up from there with calc():
font-size: calc(16px + 0.4vw);
My Thought,
Implicit Wait : If wait is set, it will wait for specified amount of time for each findElement/findElements call. It will throw an exception if action is not complete.
Explicit Wait : If wait is set, it will wait and move on to next step when the provided condition becomes true else it will throw an exception after waiting for specified time. Explicit wait is applicable only once wherever specified.
If you see an out of memory, consider if that is plausible: Do you really need that much memory? If not (i.e. when you don't have huge objects and if you don't need to create millions of objects for some reason), chances are that you have a memory leak.
In Java, this means that you're keeping a reference to an object somewhere even though you don't need it anymore. Common causes for this is forgetting to call close() on resources (files, DB connections, statements and result sets, etc.).
If you suspect a memory leak, use a profiler to find which object occupies all the available memory.
Configuring a working email client from localhost is quite a chore, I have spent hours of frustration attempting it. I'm sure someone more experienced may be able to help, or they may perhaps agree with me.
If you just want to test, here is a great tool for testing mail locally, that requires almost no configuration:
http://www.toolheap.com/test-mail-server-tool/
It worked right off the bat for me, hope this helps you.
equals() checks whether two strings are equal or not.It gives boolean value. compareTo() checks whether string object is equal to,greater or smaller to the other string object.It gives result as : 1 if string object is greater 0 if both are equal -1 if string is smaller than other string
eq:
String a = "Amit";
String b = "Sumit";
String c = new String("Amit");
System.out.println(a.equals(c));//true
System.out.println(a.compareTo(c)); //0
System.out.println(a.compareTo(b)); //1
This confused me for a while until I worked out that the dependencies of the various projects in the solution had been messed up. Get that straight and naturally your assembly appears in the right place.
This error happens basically for two reasons.
You can try this code below.
# Simplification to execute an SQL string of getting a data from the database
def get(self, sql_string, sql_vars=(), debug_sql=0):
try:
self.cursor.execute(sql_string, sql_vars)
return self.cursor.fetchall()
except (AttributeError, MySQLdb.OperationalError):
self.__init__()
self.cursor.execute(sql_string, sql_vars)
return self.cursor.fetchall()
It mitigates the error whatever the reason behind it, especially for the second reason.
If it's caused by low RAM, you either have to raise database connection efficiency from the code, from the database configuration, or simply raise the RAM.
There are a number of ways that you could do this, but the fastest might be to use IndexOf to find the index position of the letter you want to replace and then substring out the text before and after what you want to replace.
You can use too
style="overflow-y: scroll; height:150px; width: auto;"
It's works for me
Usually, string comparisons are case-insensitive. If your database is configured to case sensitive collation, you need to force to use a case insensitive one:
SELECT balance FROM people WHERE email = '[email protected]'
COLLATE SQL_Latin1_General_CP1_CI_AS
There are two ways to tackle this based on what you want:
Solution 1: Remove purple commits, preserving history (incase you want to roll back)
git revert -m 1 <SHA of merge>
-m 1
specifies which parent line to choose
Purple commits will still be there in history but since you have reverted, you will not see code from those commits.
Solution 2: Completely remove purple commits (disruptive change if repo is shared)
git rebase -i <SHA before branching out>
and delete (remove lines) corresponding to purple commits.
This would be less tricky if commits were not made after merge. Additional commits increase the chance of conflicts during revert/rebase
.
A "sort merge" join is performed by sorting the two data sets to be joined according to the join keys and then merging them together. The merge is very cheap, but the sort can be prohibitively expensive especially if the sort spills to disk. The cost of the sort can be lowered if one of the data sets can be accessed in sorted order via an index, although accessing a high proportion of blocks of a table via an index scan can also be very expensive in comparison to a full table scan.
A hash join is performed by hashing one data set into memory based on join columns and reading the other one and probing the hash table for matches. The hash join is very low cost when the hash table can be held entirely in memory, with the total cost amounting to very little more than the cost of reading the data sets. The cost rises if the hash table has to be spilled to disk in a one-pass sort, and rises considerably for a multipass sort.
(In pre-10g, outer joins from a large to a small table were problematic performance-wise, as the optimiser could not resolve the need to access the smaller table first for a hash join, but the larger table first for an outer join. Consequently hash joins were not available in this situation).
The cost of a hash join can be reduced by partitioning both tables on the join key(s). This allows the optimiser to infer that rows from a partition in one table will only find a match in a particular partition of the other table, and for tables having n partitions the hash join is executed as n independent hash joins. This has the following effects:
You should note that hash joins can only be used for equi-joins, but merge joins are more flexible.
In general, if you are joining large amounts of data in an equi-join then a hash join is going to be a better bet.
This topic is very well covered in the documentation.
http://download.oracle.com/docs/cd/B28359_01/server.111/b28274/optimops.htm#i51523
12.1 docs: https://docs.oracle.com/database/121/TGSQL/tgsql_join.htm
You mean this?
<style type="text/css">
.bgimg {
background-image: url('../images/divbg.png');
}
</style>
...
<div class="bgimg">
div with background
</div>
HashMap does not allow primitive data types as arguments. It can only accept objects so
HashMap<int, myObject> myMap = new HashMap<int, myObject>();
will not work.
You have to change the declaration to
HashMap<Integer, myObject> myMap = new HashMap<Integer, myObject>();
so even when you do the following
myMap.put(2,myObject);
The primitive data type is autoboxed to an Integer object.
8 (int) === boxing ===> 8 (Integer)
You can read more on autoboxing here http://docs.oracle.com/javase/tutorial/java/data/autoboxing.html
There are lots of great solutions here already. However, to provide a more streamlined solution and one more in keeping with the idea of a querySelector behavior and syntax, I opted for a solution that extends Object with a couple prototype functions. Both of these functions use regular expressions for matching text, however, a string can be provided as a loose search parameter.
Simply implement the following functions:
// find all elements with inner text matching a given regular expression
// args:
// selector: string query selector to use for identifying elements on which we
// should check innerText
// regex: A regular expression for matching innerText; if a string is provided,
// a case-insensitive search is performed for any element containing the string.
Object.prototype.queryInnerTextAll = function(selector, regex) {
if (typeof(regex) === 'string') regex = new RegExp(regex, 'i');
const elements = [...this.querySelectorAll(selector)];
const rtn = elements.filter((e)=>{
return e.innerText.match(regex);
});
return rtn.length === 0 ? null : rtn
}
// find the first element with inner text matching a given regular expression
// args:
// selector: string query selector to use for identifying elements on which we
// should check innerText
// regex: A regular expression for matching innerText; if a string is provided,
// a case-insensitive search is performed for any element containing the string.
Object.prototype.queryInnerText = function(selector, text){
return this.queryInnerTextAll(selector, text)[0];
}
With these functions implemented, you can now make calls as follows:
document.queryInnerTextAll('div.link', 'go');
document.queryInnerText('div.link', 'go');
document.queryInnerTextAll('a', /^Next$/);
document.queryInnerText('a', /next/i);
e = document.querySelector('#page');
e.queryInnerText('button', /Continue/);
Select TableName.* from TableName DESC LIMIT 5
you can use
var match=myList.Where(item=>item.Contains("Required String"));
foreach(var i in match)
{
//do something with the matched items
}
LINQ provides you with capabilities to "query" any collection of data. You can use syntax like a database query (select, where, etc) on a collection (here the collection (list) of strings).
so you are doing like "get me items from the list Where it satisfies a given condition"
inside the Where you are using a "lambda expression"
to tell briefly lambda expression is something like (input parameter => return value)
so for a parameter "item", it returns "item.Contains("required string")" . So it returns true if the item contains the string and thereby it gets selected from the list since it satisfied the condition.
SQL Statement:
SELECT * FROM employee WHERE employeeName LIKE 'A%';
Result:
Number of Records: 4
employeeID employeeName employeeName Address City PostalCode Country
1 Alam Wipro Delhi Delhi 11005 India
2 Aditya Wipro Delhi Delhi 11005 India
3 Alok HCL Delhi Delhi 11005 India
4 Ashok IBM Delhi Delhi 11005 India
In this navbar CSS, set to own color:
/* Navbar */_x000D_
.navbar-default {_x000D_
background-color: #F8F8F8;_x000D_
border-color: #E7E7E7;_x000D_
}_x000D_
/* Title */_x000D_
.navbar-default .navbar-brand {_x000D_
color: #777;_x000D_
}_x000D_
.navbar-default .navbar-brand:hover,_x000D_
.navbar-default .navbar-brand:focus {_x000D_
color: #5E5E5E;_x000D_
}_x000D_
/* Link */_x000D_
.navbar-default .navbar-nav > li > a {_x000D_
color: #777;_x000D_
}_x000D_
.navbar-default .navbar-nav > li > a:hover,_x000D_
.navbar-default .navbar-nav > li > a:focus {_x000D_
color: #333;_x000D_
}_x000D_
.navbar-default .navbar-nav > .active > a, _x000D_
.navbar-default .navbar-nav > .active > a:hover, _x000D_
.navbar-default .navbar-nav > .active > a:focus {_x000D_
color: #555;_x000D_
background-color: #E7E7E7;_x000D_
}_x000D_
.navbar-default .navbar-nav > .open > a, _x000D_
.navbar-default .navbar-nav > .open > a:hover, _x000D_
.navbar-default .navbar-nav > .open > a:focus {_x000D_
color: #555;_x000D_
background-color: #D5D5D5;_x000D_
}_x000D_
/* Caret */_x000D_
.navbar-default .navbar-nav > .dropdown > a .caret {_x000D_
border-top-color: #777;_x000D_
border-bottom-color: #777;_x000D_
}_x000D_
.navbar-default .navbar-nav > .dropdown > a:hover .caret,_x000D_
.navbar-default .navbar-nav > .dropdown > a:focus .caret {_x000D_
border-top-color: #333;_x000D_
border-bottom-color: #333;_x000D_
}_x000D_
.navbar-default .navbar-nav > .open > a .caret, _x000D_
.navbar-default .navbar-nav > .open > a:hover .caret, _x000D_
.navbar-default .navbar-nav > .open > a:focus .caret {_x000D_
border-top-color: #555;_x000D_
border-bottom-color: #555;_x000D_
}
_x000D_
Use this because whenever transaction open more than one transaction then below will work SELECT * FROM sys.sysprocesses WHERE open_tran <> 0
string name = "Paul Creasey";
if (name.contains(" ")) {
}
Why has nobody used sprintf?
#include <string>
#include <stdio.h>
static const std::string str = "hello world!";
int main()
{
//copy the data from the string to a char array
char *strarr = new char[str.size()+1];
strarr[str.size()+1] = 0; //set the null terminator
memcpy(strarr, str.c_str(),str.size()); //memory copy to the char array
printf(strarr);
printf("\n\nHEX: ");
//now print the data
for(int i = 0; i < str.size()+1; i++)
{
char x = strarr[i];
sprintf("%x ", reinterpret_cast<const char*>(x));
}
//DO NOT FORGET TO DELETE
delete(strarr);
return 0;
}
For last and second last:
INSERT INTO `t_parent_user`(`u_id`, `p_id`) VALUES ((SELECT MAX(u_id-1) FROM user) ,(SELECT MAX(u_id) FROM user ) );
According to http://www.cplusplus.com/reference/std/iterator/distance/, since vec.begin()
is a random access iterator, the distance method uses the -
operator.
So the answer is, from a performance point of view, it is the same, but maybe using distance()
is easier to understand if anybody would have to read and understand your code.
static void PrintSmallestLargest(int[] arr)
{
if (arr.Length > 0)
{
int small = arr[0];
int large = arr[0];
for (int i = 0; i < arr.Length; i++)
{
if (large < arr[i])
{
int tmp = large;
large = arr[i];
arr[i] = large;
}
if (small > arr[i])
{
int tmp = small;
small = arr[i];
arr[i] = small;
}
}
Console.WriteLine("Smallest is {0}", small);
Console.WriteLine("Largest is {0}", large);
}
}
This way you can have smallest and largest number in a single loop.
The ideal is 1 thread per core, as long as none of the threads will block.
One case where this may not be true: there are other threads running on the core, in which case more threads may give your program a bigger slice of the execution time.
If you want a generic way, you can define an error page in web.xml:
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/500</location>
</error-page>
And add mapping in Spring MVC:
@Controller
public class ErrorController {
@RequestMapping(value="/500")
public @ResponseBody String handleException(HttpServletRequest req) {
// you can get the exception thrown
Throwable t = (Throwable)req.getAttribute("javax.servlet.error.exception");
// customize response to what you want
return "Internal server error.";
}
}
There is no standard, so there is no guarantee. With that said, its common for the sitemap to be self labeled and on the root, like this:
example.com/sitemap.xml
Case is sensitive on some servers, so keep that in mind. If its not there, look in the robots file on the root:
example.com/robots.txt
If you don't see it listed in the robots file head to Google and search this:
site:example.com filetype:xml
This will limit the results to XML files on your target domain. At this point its trial-and-error and based on the specifics of the website you are working with. If you get several pages of results from the Google search phrase above then try to limit the results further:
filetype:xml site:example.com inurl:sitemap
or
filetype:xml site:example.com inurl:products
If you still can't find it you can right-click > "View Source"
and do a search (aka: "control find" or Ctrl + F
) for .xml
to see if there is a reference to it in the code.
Other approach for Vanilla JavaScript:
for(var o of document.querySelectorAll('#models > option')) {
o.remove()
}
I thought that since the js file was already loaded, that I didn't need to load/enqueue it again in the separate add_ajax function.
But this must be necessary, or I did this and it's now working.
Hopefully will help someone else.
Here is the corrected code from the question:
// code to load jquery - working fine
// code to load javascript file - working fine
// ENABLE AJAX :
function add_ajax()
{
wp_enqueue_script(
'function',
'http://host/blog/wp-content/themes/theme/js.js',
array( 'jquery' ),
'1.0',
1
);
wp_localize_script(
'function',
'ajax_script',
array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
$dirName = get_stylesheet_directory(); // use this to get child theme dir
require_once ($dirName."/ajax.php");
add_action("wp_ajax_nopriv_function1", "function1"); // function in ajax.php
add_action('template_redirect', 'add_ajax');
It depends on how and where you declared your array list. If it is an instance variable in the same class like your AnalyseArray() method you don't have to pass it along. The method will know the list and you can simply use the A in whatever purpose you need.
If they don't know each other, e.g. beeing a local variable or declared in a different class, define that your AnalyseArray() method needs an ArrayList parameter
public void AnalyseArray(ArrayList<Integer> theList){}
and then work with theList inside that method. But don't forget to actually pass it on when calling the method.AnalyseArray(A);
PS: Some maybe helpful Information to Variables and parameters.
One important point that is alluded to but not directly addressed is the difference between "precision" and "scale" and how they are used in the two statements. "precision" is the total number of significant digits in a number. "scale" is the number of digits to the right of the decimal point.
The MathContext constructor only accepts precision and RoundingMode as arguments, and therefore scale is never specified in the first statement.
setScale()
obviously accepts scale as an argument, as well as RoundingMode, however precision is never specified in the second statement.
If you move the decimal point one place to the right, the difference will become clear:
// 1.
new BigDecimal("35.3456").round(new MathContext(4, RoundingMode.HALF_UP));
//result = 35.35
// 2.
new BigDecimal("35.3456").setScale(4, RoundingMode.HALF_UP);
// result = 35.3456
A deadlock occurs when there is a circular chain of threads or processes which each hold a locked resource and are trying to lock a resource held by the next element in the chain. For example, two threads that hold respectively lock A and lock B, and are both trying to acquire the other lock.
to copy one list into the other list, u can use the method called Collection.copy(myObject myTempObject).now after executing these line of code u can see all the list values in the myObject.
You first have to 'dot' source the script, so for you :
. .\Get-NetworkStatistics.ps1
The first 'dot' asks PowerShell to load the script file into your PowerShell environment, not to start it. You should also use set-ExecutionPolicy Unrestricted
or set-ExecutionPolicy AllSigned
see(the Execution Policy instructions).
In most housing services just add in the .htaccess on the target server folder this:
Header set Access-Control-Allow-Origin 'https://your.site.folder'
You can pass the configuration name to the post-build script and check it in there to see if it should run.
Pass the configuration name with $(ConfigurationName)
.
Checking it is based on how you are implementing the post-build step -- it will be a command-line argument.
Connection object is for illustration only. The DataAdapter is the key bit:
Dim strSql As String = "SELECT EmpCode,EmpID,EmpName FROM dbo.Employee"
Dim dtb As New DataTable
Using cnn As New SqlConnection(connectionString)
cnn.Open()
Using dad As New SqlDataAdapter(strSql, cnn)
dad.Fill(dtb)
End Using
cnn.Close()
End Using
declare Regione int;
set Regione=(select id from users
where id=1) ;
select Regione ;
I found a solution that is more efficient than currently accepted answer, because current answer forces all list elements to be refreshed. My solution will refresh only one element (that was touched) by calling adapters getView and recycling current view which adds even more efficiency.
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Edit object data that is represented in Viewat at list's "position"
view = mAdapter.getView(position, view, parent);
}
});
In rxjs 6 map operator usage has been changed now you need to Use it like this.
import { map } from 'rxjs/operators';
myObservable
.pipe(map(data => data * 2))
.subscribe(...);
For reference https://www.academind.com/learn/javascript/rxjs-6-what-changed/#operators-update-path
Just Do it.....
( It will create same table structure as from table as to table with same data )
create table toDatabaseName.toTableName as select * from fromDatabaseName.fromTableName;
There are two separate things here:
For example:
{
vector<MyObject> v;
// do some stuff, push some objects onto v
v.clear(); // 1
// maybe do some more stuff
} // 2
At 1
, you clear v
: this destroys all the objects it was storing. Each gets its destructor called, if your wrote one, and anything owned by that MyObject
is now released.
However, vector v
has the right to keep the raw storage around in case you want it later.
If you decide to push some more things into it between 1
and 2
, this saves time as it can reuse the old memory.
At 2
, the vector v
goes out of scope: any objects you pushed into it since 1
will be destroyed (as if you'd explicitly called clear again), but now the underlying storage is also released (v
won't be around to reuse it any more).
If I change the example so v
becomes a pointer to a dynamically-allocated vector, you need to explicitly delete it, as the pointer going out of scope at 2
doesn't do that for you. It's better to use something like std::unique_ptr
in that case, but if you don't and v
is leaked, the storage it allocated will be leaked as well. As above, you need to make sure v
is deleted, and calling clear
isn't sufficient.
First download the dex2jar tool from Following link http://code.google.com/p/dex2jar/downloads/list
Extract the file it create dex2jar
folder
Now you pick your apk file and change its extension .apk to .zip after changing extension it seems to be zip file then extract this zip file you found classes.dex
file
Now pick classes.dex file and put it into dex2jar
folder
Now open cmd window and type the path of dex2jar
folder
Now type the command dex2jar.bat classes.dex
and press Enter
Now Open the dex2jar
folder you found classes_dex2jar.jar
file
Next you download the java decompiler tool from the following link http://java.decompiler.free.fr/?q=jdgui
Last Step Open the file classes_dex2jar.jar
in java decompiler tool now you can see apk code
Beside the obvious reloadData from UI/Main Thread (whatever Apple calls it), in my case, I had forgotten to also update the SECTIONS info. Therefor it did not detect any new sections!
Ideally, you want to be using window.location.replace(...)
.
See this answer here for a full explanation: How do I redirect to another webpage?
C99 way, also supported by VC++ compiler.
#define FOO(fmt, ...) printf(fmt, ##__VA_ARGS__)
I have a work around for this problem. I have verified this fix in my own app(300K+ DAU), which can reduce at least 95% of this kind of crash, but still cannot 100% avoid this problem.
This problem happens even when you ensure to call startForeground() just after service started as Google documented. It may be because the service creation and initialization process already cost more than 5 seconds in many scenarios, then no matter when and where you call startForeground() method, this crash is unavoidable.
My solution is to ensure that startForeground() will be executed within 5 seconds after startForegroundService() method, no matter how long your service need to be created and initialized. Here is the detailed solution.
Do not use startForegroundService at the first place, use bindService() with auto_create flag. It will wait for the service initialization. Here is the code, my sample service is MusicService:
final Context applicationContext = context.getApplicationContext();
Intent intent = new Intent(context, MusicService.class);
applicationContext.bindService(intent, new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
if (binder instanceof MusicBinder) {
MusicBinder musicBinder = (MusicBinder) binder;
MusicService service = musicBinder.getService();
if (service != null) {
// start a command such as music play or pause.
service.startCommand(command);
// force the service to run in foreground here.
// the service is already initialized when bind and auto_create.
service.forceForeground();
}
}
applicationContext.unbindService(this);
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}, Context.BIND_AUTO_CREATE);
Then here is MusicBinder implementation:
/**
* Use weak reference to avoid binder service leak.
*/
public class MusicBinder extends Binder {
private WeakReference<MusicService> weakService;
/**
* Inject service instance to weak reference.
*/
public void onBind(MusicService service) {
this.weakService = new WeakReference<>(service);
}
public MusicService getService() {
return weakService == null ? null : weakService.get();
}
}
The most important part, MusicService implementation, forceForeground() method will ensure that startForeground() method is called just after startForegroundService():
public class MusicService extends MediaBrowserServiceCompat {
...
private final MusicBinder musicBind = new MusicBinder();
...
@Override
public IBinder onBind(Intent intent) {
musicBind.onBind(this);
return musicBind;
}
...
public void forceForeground() {
// API lower than 26 do not need this work around.
if (Build.VERSION.SDK_INT >= 26) {
Intent intent = new Intent(this, MusicService.class);
// service has already been initialized.
// startForeground method should be called within 5 seconds.
ContextCompat.startForegroundService(this, intent);
Notification notification = mNotificationHandler.createNotification(this);
// call startForeground just after startForegroundService.
startForeground(Constants.NOTIFICATION_ID, notification);
}
}
}
If you want to run the step 1 code snippet in a pending intent, such as if you want to start a foreground service in a widget (a click on widget button) without opening your app, you can wrap the code snippet in a broadcast receiver, and fire a broadcast event instead of start service command.
That is all. Hope it helps. Good luck.
And what about just searching for the first non-zero character?
[1-9]\d+
This regex finds the first digit between 1 and 9 followed by any number of digits, so for "00012345" it returns "12345". It can be easily adapted for alphanumeric strings.
Starting Python 3.8
, and the introduction of assignment expressions (PEP 572) (:=
operator), we can now capture the condition value re.search(pattern, statement)
in a variable (let's all it match
) in order to both check if it's not None
and then re-use it within the body of the condition:
if match := re.search('I love (\w+)', statement):
print(f'He loves {match.group(1)}')
elif match := re.search("Ich liebe (\w+)", statement):
print(f'Er liebt {match.group(1)}')
elif match := re.search("Je t'aime (\w+)", statement):
print(f'Il aime {match.group(1)}')
P stands for polynomial time. NP stands for non-deterministic polynomial time.
Definitions:
Polynomial time means that the complexity of the algorithm is O(n^k), where n is the size of your data (e. g. number of elements in a list to be sorted), and k is a constant.
Complexity is time measured in the number of operations it would take, as a function of the number of data items.
Operation is whatever makes sense as a basic operation for a particular task. For sorting, the basic operation is a comparison. For matrix multiplication, the basic operation is multiplication of two numbers.
Now the question is, what does deterministic vs. non-deterministic mean? There is an abstract computational model, an imaginary computer called a Turing machine (TM). This machine has a finite number of states, and an infinite tape, which has discrete cells into which a finite set of symbols can be written and read. At any given time, the TM is in one of its states, and it is looking at a particular cell on the tape. Depending on what it reads from that cell, it can write a new symbol into that cell, move the tape one cell forward or backward, and go into a different state. This is called a state transition. Amazingly enough, by carefully constructing states and transitions, you can design a TM, which is equivalent to any computer program that can be written. This is why it is used as a theoretical model for proving things about what computers can and cannot do.
There are two kinds of TM's that concern us here: deterministic and non-deterministic. A deterministic TM only has one transition from each state for each symbol that it is reading off the tape. A non-deterministic TM may have several such transition, i. e. it is able to check several possibilities simultaneously. This is sort of like spawning multiple threads. The difference is that a non-deterministic TM can spawn as many such "threads" as it wants, while on a real computer only a specific number of threads can be executed at a time (equal to the number of CPUs). In reality, computers are basically deterministic TMs with finite tapes. On the other hand, a non-deterministic TM cannot be physically realized, except maybe with a quantum computer.
It has been proven that any problem that can be solved by a non-deterministic TM can be solved by a deterministic TM. However, it is not clear how much time it will take. The statement P=NP means that if a problem takes polynomial time on a non-deterministic TM, then one can build a deterministic TM which would solve the same problem also in polynomial time. So far nobody has been able to show that it can be done, but nobody has been able to prove that it cannot be done, either.
NP-complete problem means an NP problem X, such that any NP problem Y can be reduced to X by a polynomial reduction. That implies that if anyone ever comes up with a polynomial-time solution to an NP-complete problem, that will also give a polynomial-time solution to any NP problem. Thus that would prove that P=NP. Conversely, if anyone were to prove that P!=NP, then we would be certain that there is no way to solve an NP problem in polynomial time on a conventional computer.
An example of an NP-complete problem is the problem of finding a truth assignment that would make a boolean expression containing n variables true.
For the moment in practice any problem that takes polynomial time on the non-deterministic TM can only be done in exponential time on a deterministic TM or on a conventional computer.
For example, the only way to solve the truth assignment problem is to try 2^n possibilities.
All answers are based on anonymous inner class. We have one more way for adding click event for buttons as well as other components too.
An activity needs to implement View.OnClickListener interface and we need to override the onClick function. I think this is best approach compared to using anonymous class.
package com.pointerunits.helloworld;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
private Button login;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
login = (Button)findViewById(R.id.loginbutton);
login.setOnClickListener((OnClickListener) this);
Log.i(DISPLAY_SERVICE, "Activity is created");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View v) {
Log.i(DISPLAY_SERVICE, "Button clicked : " + v.getId());
}
}
KEEPING THE DIRECTORY NAME
The subdirectory-filter (or the shorter command git subtree) works good but did not work for me since they remove the directory name from the commit info. In my scenario I just want to merge parts of one repository into another and retain the history WITH full path name.
My solution was to use the tree-filter and to simply remove the unwanted files and directories from a temporary clone of the source repository, then pull from that clone into my target repository in 5 simple steps.
# 1. clone the source
git clone ssh://<user>@<source-repo url>
cd <source-repo>
# 2. remove the stuff we want to exclude
git filter-branch --tree-filter "rm -rf <files to exclude>" --prune-empty HEAD
# 3. move to target repo and create a merge branch (for safety)
cd <path to target-repo>
git checkout -b <merge branch>
# 4. Add the source-repo as remote
git remote add source-repo <path to source-repo>
# 5. fetch it
git pull source-repo master
# 6. check that you got it right (better safe than sorry, right?)
gitk
Based on @Sailesh and @DavidCulp:
(on branch development)
$ git fetch origin master
$ git merge FETCH_HEAD
(resolve any merge conflicts if there are any)
$ git checkout master
$ git merge --no-ff development (there won't be any conflicts now)
The first command will make sure you have all upstream commits made to remote master, with Sailesh response that would not happen.
The second will perform a merge and create conflicts that you can then resolve.
After doing so, you can finally checkout master to switch to master.
Then you merge the development branch onto the local master. The no-ff flag will create a commit node in master for the whole merge to be trackable.
After that you can commit and push your merge.
This procedure will make sure there's a merge commit from development to master that people can see, then if they go look at the development branch they can see the individual commits you've made to that branch during its development.
Optionally, you can amend your merge commit before you push it, if you want to add a summary of what was done in the development branch.
EDIT: my original answer suggested a git merge master
which didn't do anything, it's better to do git merge FETCH_HEAD
after fetching the origin/master
If you are using php you can add any function to your sql statement by using: SQLite3::createFunction. In PDO you can use PDO::sqliteCreateFunction and implement the preg_match function within your statement:
See how its done by Havalite (RegExp in SqLite using Php)
import urllib2
Traceback (most recent call last):
File "", line 1, in
import urllib2
ImportError: No module named 'urllib2' So urllib2 has been been replaced by the package : urllib.request.
Here is the PEP link (Python Enhancement Proposals )
http://www.python.org/dev/peps/pep-3108/#urllib-package
so instead of urllib2 you can now import urllib.request and then use it like this:
>>>import urllib.request
>>>urllib.request.urlopen('http://www.placementyogi.com')
Original Link : http://placementyogi.com/articles/python/importerror-no-module-named-urllib2-in-python-3-x
-XX:PermSize -XX:MaxPermSize
are used to set size for Permanent Generation.
Permanent Generation: The Permanent Generation is where class files are kept. These are the result of compiled classes and JSP pages. If this space is full, it triggers a Full Garbage Collection. If the Full Garbage Collection cannot clean out old unreferenced classes and there is no room left to expand the Permanent Space, an Out-of- Memory error (OOME) is thrown and the JVM will crash.
Using the appropriate VerificationMode:
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
verify(mockObject, atLeast(2)).someMethod("was called at least twice");
verify(mockObject, times(3)).someMethod("was called exactly three times");
You can set CSS using three different ways as mentioned below :-
1.External style sheet
2.Internal style sheet
3.Inline style
Preferred / ideal way of setting the css style is using as external style sheets when the style is applied to many pages. With an external style sheet, you can change the look of an entire Web site by changing one file.
sample usage can be :-
<head>
<link rel="stylesheet" type="text/css" href="your_css_file_name.css">
</head>
If you want to apply a unique style to a single document then you can use Internal style sheet.
Don't use inline style sheet,as it mixes content with presentation and looses many advantages.
Please try this
<!DOCTYPE html>
<html>
<head>
<title>Jquery</title>
<meta charset="utf-8">
<script src='http://code.jquery.com/jquery-1.7.1.min.js'></script>
</head>
<body>
<input type="text" id="message" value="" />
<input type="button" id="sendButton" value="Send">
<script>
$(document).ready(function(){
var checkField;
//checking the length of the value of message and assigning to a variable(checkField) on load
checkField = $("input#message").val().length;
var enableDisableButton = function(){
if(checkField > 0){
$('#sendButton').removeAttr("disabled");
}
else {
$('#sendButton').attr("disabled","disabled");
}
}
//calling enableDisableButton() function on load
enableDisableButton();
$('input#message').keyup(function(){
//checking the length of the value of message and assigning to the variable(checkField) on keyup
checkField = $("input#message").val().length;
//calling enableDisableButton() function on keyup
enableDisableButton();
});
});
</script>
</body>
</html>
Getting all the subsets with recursion. Crazy-ass one-liner
from typing import List
def subsets(xs: list) -> List[list]:
return subsets(xs[1:]) + [x + [xs[0]] for x in subsets(xs[1:])] if xs else [[]]
Based on a Haskell solution
subsets :: [a] -> [[a]]
subsets [] = [[]]
subsets (x:xs) = map (x:) (subsets xs) ++ subsets xs
You need to have the testng.jar
under classpath.
try C:\projectfred> java -cp "path-tojar/testng.jar:path_to_yourtest_classes" org.testng.TestNG testng.xml
Update:
Under linux I ran this command and it would be some thing similar on Windows either
test/bin# java -cp ".:../lib/*" org.testng.TestNG testng.xml
Directory structure:
/bin - All my test packages are under bin including testng.xml
/src - All source files are under src
/lib - All libraries required for the execution of tests are under this.
Once I compile all sources they go under bin directory. So, in the classpath I need to specify contents of bin directory and all the libraries like testng.xml, loggers etc over here. Also copy testng.xml to bin folder if you dont want to specify the full path where the testng.xml is available.
/bin
-- testng.xml
-- testclasses
-- Properties files if any.
/lib
-- testng.jar
-- log4j.jar
Update
:
Go to the folder MyProject
and type run the java command like the way shown below:-
java -cp ".: C:\Program Files\jbdevstudio4\studio\plugins\*" org.testng.TestNG testng.xml
I believe the testng.xml file is under C:\Users\me\workspace\MyProject
if not please give the full path for testng.xml
file
Visit here to see the complete code. Here you will also find a link for an online terminal where the complete code can be run and the program represents how to extract structure's information(field's name their type & value). Below is the program snippet that only prints the field names.
package main
import "fmt"
import "reflect"
func main() {
type Book struct {
Id int
Name string
Title string
}
book := Book{1, "Let us C", "Enjoy programming with practice"}
e := reflect.ValueOf(&book).Elem()
for i := 0; i < e.NumField(); i++ {
fieldName := e.Type().Field(i).Name
fmt.Printf("%v\n", fieldName)
}
}
/*
Id
Name
Title
*/
If you first convert the int to a char, you will have your ascii code.
For example:
int iAsciiValue = 9; // Currently just the number 9, but we want Tab character
// Put the tab character into a string
String strAsciiTab = Character.toString((char) iAsciiValue);
This solution matches the process name more strictly:
ps -Ac -o pid,comm | awk '/^ *[0-9]+ Dropbox$/ {print $1}'
This solution has the following advantages:
tail -f ~/Dropbox
~/Dropbox/foo.sh
~/DropboxUID.sh
No, it is not possible to change the content of the buttons in the dialog displayed by the confirm
function. You can use Javascript to create a dialog that looks similar.
None of the other answers seemed correct in my case, however I found the real answer here
My id_rsa
file was already in PEM format, I just needed to add the .pem
extension to the filename.
The possible options to the openssl rsa -inform
parameter are one of: PEM
DER
A
PEM
encoded file is a plain-text encoding that looks something like:-----BEGIN RSA PRIVATE KEY----- MIGrAgEAAiEA0tlSKz5Iauj6ud3helAf5GguXeLUeFFTgHrpC3b2O20CAwEAAQIh ALeEtAIzebCkC+bO+rwNFVORb0bA9xN2n5dyTw/Ba285AhEA9FFDtx4VAxMVB2GU QfJ/2wIRANzuXKda/nRXIyRw1ArE2FcCECYhGKRXeYgFTl7ch7rTEckCEQDTMShw 8pL7M7DsTM7l3HXRAhAhIMYKQawc+Y7MNE4kQWYe -----END RSA PRIVATE KEY-----
While
DER
is a binary encoding format.
Make the value of first item of selection box to blank.
So when every you post the FORM you get blank value and using this way you would know that user hasn't selected anything from dropdown.
<select name="user_role" required>
<option value="">-Select-</option>
<option value="User">User</option>
<option value="Admin">Admin</option>
</select>
extension UITableView {
/// Reloads a table view without losing track of what was selected.
func reloadDataSavingSelections() {
let selectedRows = indexPathsForSelectedRows
reloadData()
if let selectedRow = selectedRows {
for indexPath in selectedRow {
selectRow(at: indexPath, animated: false, scrollPosition: .none)
}
}
}
}
tableView.reloadDataSavingSelections()
Mutable default arguments don't generally do what you want. Instead, try this:
class Node:
def __init__(self, wordList=None, adjacencyList=None):
if wordList is None:
self.wordList = []
else:
self.wordList = wordList
if adjacencyList is None:
self.adjacencyList = []
else:
self.adjacencyList = adjacencyList
To find it from Windows OS,
catalina.bat version
It should print jre version details along with other informative details.
Using CATALINA_BASE: "C:\User\software\enterprise-server-tome...
Using CATALINA_HOME: "C:\User\software\enterprise-server-tome...
Using CATALINA_TMPDIR: "C:\User\software\enterprise-server-tome...
Using JRE_HOME: "C:\Program Files\Java\jdk1.8.0_25"
Using CLASSPATH: "C:\User\software\enterprise-server-tome...
Server version: Apache Tomcat/8.5.11
Server built: Jan 10 2017 21:02:52 UTC
Server number: 8.5.11.0
OS Name: Windows 7
OS Version: 6.1
Architecture: amd64
JVM Version: 1.8.0_25-b18
JVM Vendor: Oracle Corporation
You won't be able to send a message through other people mail servers. Check with your host provider how to send emails. Try to send an email from your server without PHP, you can use any email client like Outook. Just after it works, try to configure PHP.ini with your email client SMTP (sending e-mail) configuration.
You can get the values directly in case of one array like this:
var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"[email protected]","Phone":"123 dead drive"}';
var result = $.parseJSON(resultJSON);
result['FirstName']; // return 'John'
result['LastName']; // return ''Doe'
result['Email']; // return '[email protected]'
result['Phone']; // return '123'
int total = (int) Math.ceil( (double)157/ (double) 32);
You can put and actionCommand to each radio button (string).
this.jButton1.setActionCommand("dog");
this.jButton2.setActionCommand("cat");
this.jButton3.setActionCommand("bird");
Assuming they're already in a ButtonGroup (state_group in this case) you can get the selected radio button like this:
String selection = this.state_group.getSelection().getActionCommand();
Hope this helps
if you are facing this error in windows with android
open your root directory app folder and move into android folder .
cd android
gradlew clean
start your app again react-native run-android
bhooom it works
In my case, although size '2' is displayed in the spinner, nothing happens till some selection is done!
I have an xml file (data_sizes.xml) which lists all the spinner values.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="chunks">
<item>2</item>
<item>4</item>
<item>8</item>
<item>16</item>
<item>32</item>
</string-array>
</resources>
In main.xml file: Spinner element
<Spinner android:id="@+id/spinnerSize"
android:layout_marginLeft="50px"
android:layout_width="fill_parent"
android:drawSelectorOnTop="true"
android:layout_marginTop="5dip"
android:prompt="@string/SelectSize"
android:layout_marginRight="30px"
android:layout_height="35px" />
Then in my java code, I added:
In my activity: Declaration
Spinner spinnerSize;
ArrayAdapter adapter;
In a public void function - initControls(): Definition
spinnerSize = (Spinner)findViewById(R.id.spinnerSize);
adapter = ArrayAdapter.createFromResource(this, R.array.chunks, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSize.setAdapter(adapter);
spinnerSize.setOnItemSelectedListener(new MyOnItemSelectedListener());
My spinner listener:
/* Spinner Listener */
class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
chunkSize = new Integer(parent.getItemAtPosition(pos).toString()).intValue();
}
public void onNothingSelected(AdapterView<?> parent) {
// Dummy
}
}
For example you can find any textView:
TextView textView = (TextView) ((Activity) context).findViewById(R.id.textView1);
Thank you all for your help, I added this code and it seems it fixed the issue:
.navbar .navbar-nav {
display: inline-block;
float: none;
}
.navbar .navbar-collapse {
text-align: center;
}
Source
There are a lot of answers here. I am adding a few tricky ways to create arrays (from an exam point of view it's good to know this)
Declare and define an array
int intArray[] = new int[3];
This will create an array of length 3. As it holds a primitive type, int, all values are set to 0 by default. For example,
intArray[2]; // Will return 0
Using box brackets [] before the variable name
int[] intArray = new int[3];
intArray[0] = 1; // Array content is now {1, 0, 0}
Initialise and provide data to the array
int[] intArray = new int[]{1, 2, 3};
This time there isn't any need to mention the size in the box bracket. Even a simple variant of this is:
int[] intArray = {1, 2, 3, 4};
An array of length 0
int[] intArray = new int[0];
int length = intArray.length; // Will return length 0
Similar for multi-dimensional arrays
int intArray[][] = new int[2][3];
// This will create an array of length 2 and
//each element contains another array of length 3.
// { {0,0,0},{0,0,0} }
int lenght1 = intArray.length; // Will return 2
int length2 = intArray[0].length; // Will return 3
Using box brackets before the variable:
int[][] intArray = new int[2][3];
It's absolutely fine if you put one box bracket at the end:
int[] intArray [] = new int[2][4];
int[] intArray[][] = new int[2][3][4]
Some examples
int [] intArray [] = new int[][] {{1,2,3},{4,5,6}};
int [] intArray1 [] = new int[][] {new int[] {1,2,3}, new int [] {4,5,6}};
int [] intArray2 [] = new int[][] {new int[] {1,2,3},{4,5,6}}
// All the 3 arrays assignments are valid
// Array looks like {{1,2,3},{4,5,6}}
It's not mandatory that each inner element is of the same size.
int [][] intArray = new int[2][];
intArray[0] = {1,2,3};
intArray[1] = {4,5};
//array looks like {{1,2,3},{4,5}}
int[][] intArray = new int[][2] ; // This won't compile. Keep this in mind.
You have to make sure if you are using the above syntax, that the forward direction you have to specify the values in box brackets. Else it won't compile. Some examples:
int [][][] intArray = new int[1][][];
int [][][] intArray = new int[1][2][];
int [][][] intArray = new int[1][2][3];
Another important feature is covariant
Number[] numArray = {1,2,3,4}; // java.lang.Number
numArray[0] = new Float(1.5f); // java.lang.Float
numArray[1] = new Integer(1); // java.lang.Integer
// You can store a subclass object in an array that is declared
// to be of the type of its superclass.
// Here 'Number' is the superclass for both Float and Integer.
Number num[] = new Float[5]; // This is also valid
IMPORTANT: For referenced types, the default value stored in the array is null.
in your servlet
request.setAttribute("submitDone","done");
return mapping.findForward("success");
In your jsp
<c:if test="${not empty submitDone}">
<script>alert("Form submitted");
</script></c:if>
var postData = "text";
$.ajax({
type: "post",
url: "url",
data: postData,
contentType: "application/x-www-form-urlencoded",
success: function(responseData, textStatus, jqXHR) {
alert("data saved")
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
})
Global variables and static variables are automatically initialized to zero. If you have simply
char ZEROARRAY[1024];
at global scope it will be all zeros at runtime. But actually there is a shorthand syntax if you had a local array. If an array is partially initialized, elements that are not initialized receive the value 0 of the appropriate type. You could write:
char ZEROARRAY[1024] = {0};
The compiler would fill the unwritten entries with zeros. Alternatively you could use memset
to initialize the array at program startup:
memset(ZEROARRAY, 0, 1024);
That would be useful if you had changed it and wanted to reset it back to all zeros.
I made a simple class to check if your code is running for the first time/ n-times!
Example
Create a unique preferences
FirstTimePreference prefFirstTime = new FirstTimePreference(getApplicationContext());
Use runTheFirstTime, choose a key to check your event
if (prefFirstTime.runTheFirstTime("myKey")) {
Toast.makeText(this, "Test myKey & coutdown: " + prefFirstTime.getCountDown("myKey"),
Toast.LENGTH_LONG).show();
}
Use runTheFirstNTimes, choose a key and how many times execute
if(prefFirstTime.runTheFirstNTimes("anotherKey" , 5)) {
Toast.makeText(this, "ciccia Test coutdown: "+ prefFirstTime.getCountDown("anotherKey"),
Toast.LENGTH_LONG).show();
}
You can configure logging in your settings.py
file.
One example:
if DEBUG:
# will output to your console
logging.basicConfig(
level = logging.DEBUG,
format = '%(asctime)s %(levelname)s %(message)s',
)
else:
# will output to logging file
logging.basicConfig(
level = logging.DEBUG,
format = '%(asctime)s %(levelname)s %(message)s',
filename = '/my_log_file.log',
filemode = 'a'
)
However that's dependent upon setting DEBUG, and maybe you don't want to have to worry about how it's set up. See this answer on How can I tell whether my Django application is running on development server or not? for a better way of writing that conditional. Edit: the example above is from a Django 1.1 project, logging configuration in Django has changed somewhat since that version.
Depending on your needs, you could allow both secure and unsecure connections and still only use one Socket.io instance.
You simply have to instanciate two servers, one for HTTP and one for HTTPS, then attach those servers to the Socket.io instance.
Server side :
// needed to read certificates from disk
const fs = require( "fs" );
// Servers with and without SSL
const http = require( "http" )
const https = require( "https" );
const httpPort = 3333;
const httpsPort = 3334;
const httpServer = http.createServer();
const httpsServer = https.createServer({
"key" : fs.readFileSync( "yourcert.key" ),
"cert": fs.readFileSync( "yourcert.crt" ),
"ca" : fs.readFileSync( "yourca.crt" )
});
httpServer.listen( httpPort, function() {
console.log( `Listening HTTP on ${httpPort}` );
});
httpsServer.listen( httpsPort, function() {
console.log( `Listening HTTPS on ${httpsPort}` );
});
// Socket.io
const ioServer = require( "socket.io" );
const io = new ioServer();
io.attach( httpServer );
io.attach( httpsServer );
io.on( "connection", function( socket ) {
console.log( "user connected" );
// ... your code
});
Client side :
var url = "//example.com:" + ( window.location.protocol == "https:" ? "3334" : "3333" );
var socket = io( url, {
// set to false only if you use self-signed certificate !
"rejectUnauthorized": true
});
socket.on( "connect", function( e ) {
console.log( "connect", e );
});
If your NodeJS server is different from your Web server, you will maybe need to set some CORS headers. So in the server side, replace:
const httpServer = http.createServer();
const httpsServer = https.createServer({
"key" : fs.readFileSync( "yourcert.key" ),
"cert": fs.readFileSync( "yourcert.crt" ),
"ca" : fs.readFileSync( "yourca.crt" )
});
With:
const CORS_fn = (req, res) => {
res.setHeader( "Access-Control-Allow-Origin" , "*" );
res.setHeader( "Access-Control-Allow-Credentials", "true" );
res.setHeader( "Access-Control-Allow-Methods" , "*" );
res.setHeader( "Access-Control-Allow-Headers" , "*" );
if ( req.method === "OPTIONS" ) {
res.writeHead(200);
res.end();
return;
}
};
const httpServer = http.createServer( CORS_fn );
const httpsServer = https.createServer({
"key" : fs.readFileSync( "yourcert.key" ),
"cert": fs.readFileSync( "yourcert.crt" ),
"ca" : fs.readFileSync( "yourca.crt" )
}, CORS_fn );
And of course add/remove headers and set the values of the headers according to your needs.