I know this is an old question and I probably won't help, but many Linux distributions(e.g., ubuntu) have a "Live cd/usb" function, so if you really need to run this script, you could try booting your computer into Linux. Just burn a .iso to a flash drive (here's how http://goo.gl/U1wLYA), start your computer with the drive plugged in, and press the F key for boot menu. If you choose "...USB...", you will boot into the OS you just put on the drive.
To wrap in single quotes (for example) ciw'<C-r>"'<esc>
works, but repeat won't work. Try:
ciw'<C-r><C-o>"'<esc>
This puts the contents of the default register "literally". Now you can press .
on any word to wrap it in quotes. To learn more see :h[elp] i_ctrl-r
and more about text objects at :h text-objects
Source: http://vimcasts.org/episodes/pasting-from-insert-mode/
For anyone looking for how to do it programmatically:
Drawable bckgrndDr = new ColorDrawable(Color.RED);
Drawable secProgressDr = new ColorDrawable(Color.GRAY);
Drawable progressDr = new ScaleDrawable(new ColorDrawable(Color.BLUE), Gravity.LEFT, 1, -1);
LayerDrawable resultDr = new LayerDrawable(new Drawable[] { bckgrndDr, secProgressDr, progressDr });
//setting ids is important
resultDr.setId(0, android.R.id.background);
resultDr.setId(1, android.R.id.secondaryProgress);
resultDr.setId(2, android.R.id.progress);
Setting ids to drawables is crucial, and takes care of preserving bounds and actual state of progress bar
Uninstall(delete) this: jre, jdk, eclipse. Download 32 bit(x86) version of this programs:jre, jdk, eclipse. And install it.
I have made a simple function included in a package for the ROC curve. I just started practicing machine learning so please also let me know if this code has any problem!
Have a look at the github readme file for more details! :)
https://github.com/bc123456/ROC
from sklearn.metrics import confusion_matrix, accuracy_score, roc_auc_score, roc_curve
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
def plot_ROC(y_train_true, y_train_prob, y_test_true, y_test_prob):
'''
a funciton to plot the ROC curve for train labels and test labels.
Use the best threshold found in train set to classify items in test set.
'''
fpr_train, tpr_train, thresholds_train = roc_curve(y_train_true, y_train_prob, pos_label =True)
sum_sensitivity_specificity_train = tpr_train + (1-fpr_train)
best_threshold_id_train = np.argmax(sum_sensitivity_specificity_train)
best_threshold = thresholds_train[best_threshold_id_train]
best_fpr_train = fpr_train[best_threshold_id_train]
best_tpr_train = tpr_train[best_threshold_id_train]
y_train = y_train_prob > best_threshold
cm_train = confusion_matrix(y_train_true, y_train)
acc_train = accuracy_score(y_train_true, y_train)
auc_train = roc_auc_score(y_train_true, y_train)
print 'Train Accuracy: %s ' %acc_train
print 'Train AUC: %s ' %auc_train
print 'Train Confusion Matrix:'
print cm_train
fig = plt.figure(figsize=(10,5))
ax = fig.add_subplot(121)
curve1 = ax.plot(fpr_train, tpr_train)
curve2 = ax.plot([0, 1], [0, 1], color='navy', linestyle='--')
dot = ax.plot(best_fpr_train, best_tpr_train, marker='o', color='black')
ax.text(best_fpr_train, best_tpr_train, s = '(%.3f,%.3f)' %(best_fpr_train, best_tpr_train))
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.0])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC curve (Train), AUC = %.4f'%auc_train)
fpr_test, tpr_test, thresholds_test = roc_curve(y_test_true, y_test_prob, pos_label =True)
y_test = y_test_prob > best_threshold
cm_test = confusion_matrix(y_test_true, y_test)
acc_test = accuracy_score(y_test_true, y_test)
auc_test = roc_auc_score(y_test_true, y_test)
print 'Test Accuracy: %s ' %acc_test
print 'Test AUC: %s ' %auc_test
print 'Test Confusion Matrix:'
print cm_test
tpr_score = float(cm_test[1][1])/(cm_test[1][1] + cm_test[1][0])
fpr_score = float(cm_test[0][1])/(cm_test[0][0]+ cm_test[0][1])
ax2 = fig.add_subplot(122)
curve1 = ax2.plot(fpr_test, tpr_test)
curve2 = ax2.plot([0, 1], [0, 1], color='navy', linestyle='--')
dot = ax2.plot(fpr_score, tpr_score, marker='o', color='black')
ax2.text(fpr_score, tpr_score, s = '(%.3f,%.3f)' %(fpr_score, tpr_score))
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.0])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC curve (Test), AUC = %.4f'%auc_test)
plt.savefig('ROC', dpi = 500)
plt.show()
return best_threshold
Most users who receive the "not JSON serializable" error simply need to specify default=str
when using json.dumps
. For example:
json.dumps(my_obj, default=str)
This will force a conversion to str
, preventing the error. Of course then look at the generated output to confirm that it is what you need.
I think this would solve the problem:
df = data.frame(read.csv("data.csv"))
# Split the dataset into 80-20
numberOfRows = nrow(df)
bound = as.integer(numberOfRows *0.8)
train=df[1:bound ,2]
test1= df[(bound+1):numberOfRows ,2]
You will have to open the file in one way or another if you want to access the data within it. Obviously, one way is to open it in your Excel application instance, e.g.:-
(untested code)
Dim wbk As Workbook
Set wbk = Workbooks.Open("C:\myworkbook.xls")
' now you can manipulate the data in the workbook anyway you want, e.g. '
Dim x As Variant
x = wbk.Worksheets("Sheet1").Range("A6").Value
Call wbk.Worksheets("Sheet2").Range("A1:G100").Copy
Call ThisWorbook.Worksheets("Target").Range("A1").PasteSpecial(xlPasteValues)
Application.CutCopyMode = False
' etc '
Call wbk.Close(False)
Another way to do it would be to use the Excel ADODB provider to open a connection to the file and then use SQL to select data from the sheet you want, but since you are anyway working from within Excel I don't believe there is any reason to do this rather than just open the workbook. Note that there are optional parameters for the Workbooks.Open() method to open the workbook as read-only, etc.
Three options: First:
<input type='text' autocomplete='off' />
Second:
<form action='' autocomplete='off'>
Third (javascript code):
$('input').attr('autocomplete', 'off');
Use:
System.Configuration.ConfigurationSettings.AppSettings["MyKey"];
AppSettings has been deprecated and is now considered obsolete (link).
In addition, the appSettings section of the app.config has been replaced by the applicationSettings section.
As someone else mentioned, you should be using System.Configuration.ConfigurationManager (link) which is new for .NET 2.0.
Another useful variant is pipe to tr
:
echo "${my_array[@]}" | tr ' ' '\n'
This looks simple and compact
Using <section>
may be neater, help screen readers and SEO while <div>
is smaller in bytes and quicker to type
Overall very little difference.
Also, would not recommend putting <section>
in a <section>
, instead place a <div>
inside a <section>
#include<stdio.h>
int main() {
int num; //given integer
int reminder;
int rev=0; //To reverse the given integer
int count=1;
printf("Enter the integer:");
scanf("%i",&num);
/*First while loop will reverse the number*/
while(num!=0)
{
reminder=num%10;
rev=rev*10+reminder;
num/=10;
}
/*Second while loop will give the number from left to right*/
while(rev!=0)
{
reminder=rev%10;
printf("The %d digit is %d\n",count, reminder);
rev/=10;
count++; //to give the number from left to right
}
return (EXIT_SUCCESS);}
First of all, you shouldn't rebuild all your views to fit a new screen, nor use different views for different screen sizes.
Use the auto-resizing capabilities of iOS, so your views can adjust, and adapt any screen size.
That's not very hard, read some documentation about that. It will save you a lot of time.
iOS 6 also offers new features about this.
Be sure to read the iOS 6 API changelog on Apple Developer website.
And check the new iOS 6 AutoLayout capabilities.
That said, if you really need to detect the iPhone 5, you can simply rely on the screen size.
[ [ UIScreen mainScreen ] bounds ].size.height
The iPhone 5's screen has a height of 568.
You can imagine a macro, to simplify all of this:
#define IS_IPHONE_5 ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON )
The use of fabs
with the epsilon is here to prevent precision errors, when comparing floating points, as pointed in the comments by H2CO3.
So from now on you can use it in standard if/else statements:
if( IS_IPHONE_5 )
{}
else
{}
Edit - Better detection
As stated by some people, this does only detect a widescreen, not an actual iPhone 5.
Next versions of the iPod touch will maybe also have such a screen, so we may use another set of macros.
Let's rename the original macro IS_WIDESCREEN
:
#define IS_WIDESCREEN ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON )
And let's add model detection macros:
#define IS_IPHONE ( [ [ [ UIDevice currentDevice ] model ] isEqualToString: @"iPhone" ] )
#define IS_IPOD ( [ [ [ UIDevice currentDevice ] model ] isEqualToString: @"iPod touch" ] )
This way, we can ensure we have an iPhone model AND a widescreen, and we can redefine the IS_IPHONE_5
macro:
#define IS_IPHONE_5 ( IS_IPHONE && IS_WIDESCREEN )
Also note that, as stated by @LearnCocos2D, this macros won't work if the application is not optimised for the iPhone 5 screen (missing the [email protected] image), as the screen size will still be 320x480 in such a case.
I don't think this may be an issue, as I don't see why we would want to detect an iPhone 5 in a non-optimized app.
IMPORTANT - iOS 8 support
On iOS 8, the bounds
property of the UIScreen
class now reflects the device orientation.
So obviously, the previous code won't work out of the box.
In order to fix this, you can simply use the new nativeBounds
property, instead of bounds
, as it won't change with the orientation, and as it's based on a portrait-up mode.
Note that dimensions of nativeBounds
is measured in pixels, so for an iPhone 5 the height will be 1136 instead of 568.
If you're also targeting iOS 7 or lower, be sure to use feature detection, as calling nativeBounds
prior to iOS 8 will crash your app:
if( [ [ UIScreen mainScreen ] respondsToSelector: @selector( nativeBounds ) ] )
{
/* Detect using nativeBounds - iOS 8 and greater */
}
else
{
/* Detect using bounds - iOS 7 and lower */
}
You can adapt the previous macros the following way:
#define IS_WIDESCREEN_IOS7 ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON )
#define IS_WIDESCREEN_IOS8 ( fabs( ( double )[ [ UIScreen mainScreen ] nativeBounds ].size.height - ( double )1136 ) < DBL_EPSILON )
#define IS_WIDESCREEN ( ( [ [ UIScreen mainScreen ] respondsToSelector: @selector( nativeBounds ) ] ) ? IS_WIDESCREEN_IOS8 : IS_WIDESCREEN_IOS7 )
And obviously, if you need to detect an iPhone 6 or 6 Plus, use the corresponding screen sizes.
Use
.one-word-per-line {
word-spacing: <parent-width>;
}
.your-classname{
width: min-intrinsic;
width: -webkit-min-content;
width: -moz-min-content;
width: min-content;
display: table-caption;
display: -ms-grid;
-ms-grid-columns: min-content;
}
where <parent-width>
is the width of the parent element (or an arbitrary high value that doesn't fit into one line). That way you can be sure that there is even a line-break after a single letter. Works with Chrome/FF/Opera/IE7+ (and probably even IE6 since it's supporting word-spacing as well).
The previous answers come close, but to meet the actual requirement that the @
symbol stay close, you'd want that to be str.Replace("@", "@" + System.Environment.NewLine)
. That will keep the @
symbol and add the appropriate newline character(s) for the current platform.
you can try this
$('body').on('hidden.bs.modal', '.modal', function () {
$(this).removeData('bs.modal');
});
It will remove all the data from the model and reset it.
In fact, depends what you want to get: - Just the min value:
SELECT MIN(price) FROM pieces
A table (multiples rows) whith the min value: Is as John Woo said above.
But, if can be different rows with same min value, the best is ORDER them from another column, because after or later you will need to do it (starting from John Woo answere):
SELECT * FROM pieces WHERE price = ( SELECT MIN(price) FROM pieces) ORDER BY stock ASC
on android devices using chrome we can't detect a backspace. You can use workaround for it:
var oldInput = '',
newInput = '';
$("#ID").keyup(function () {
newInput = $('#ID').val();
if(newInput.length < oldInput.length){
//backspace pressed
}
oldInput = newInput;
})
Is super() is used to call the parent constructor?
Yes.
Pls explain about Super().
super()
is a special use of the super
keyword where you call a parameterless parent constructor. In general, the super
keyword can be used to call overridden methods, access hidden fields or invoke a superclass's constructor.
Here's the official tutorial
If your html is similar to the example, so the click event is produced over the label, not in the input, so I use the next code: Html example:
<div id="myButtons" class="btn-group" data-toggle="buttons">
<label class="btn btn-primary active">
<input type="radio" name="options" id="option1" autocomplete="off" checked> Radio 1 (preselected)
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option2" autocomplete="off"> Radio 2
</label>
</div>
Javascript code for the event:
$('#option1').parent().on("click", function () {
alert("click fired");
});
The key here is the name
attribute of the f
object representing the opened file. You get it like that:
>>> f = open('/Users/Desktop/febROSTER2012.xls')
>>> f.name
'/Users/Desktop/febROSTER2012.xls'
Does it help?
You can use regular expressions to get the occurrences:
>>> import re
>>> print(re.findall(r'( |t)', to_search_in)) # searches for t or space
['t', ' ', 't', ' ', ' ']
Recursive solution in C++
int main (int argc, char * const argv[]) {
string s = "sarp";
bool used [4];
permute(0, "", used, s);
}
void permute(int level, string permuted, bool used [], string &original) {
int length = original.length();
if(level == length) { // permutation complete, display
cout << permuted << endl;
} else {
for(int i=0; i<length; i++) { // try to add an unused character
if(!used[i]) {
used[i] = true;
permute(level+1, original[i] + permuted, used, original); // find the permutations starting with this string
used[i] = false;
}
}
}
The difference between the two is best brought in what seems a necessary and sufficient definition of the dependencyManagement element available in Maven website docs:
dependencyManagement
"Default dependency information for projects that inherit from this one. The dependencies in this section are not immediately resolved. Instead, when a POM derived from this one declares a dependency described by a matching groupId and artifactId, the version and other values from this section are used for that dependency if they were not already specified." [ https://maven.apache.org/ref/3.6.1/maven-model/maven.html ]
It should be read along with some more information available on a different page:
“..the minimal set of information for matching a dependency reference against a dependencyManagement section is actually {groupId, artifactId, type, classifier}. In many cases, these dependencies will refer to jar artifacts with no classifier. This allows us to shorthand the identity set to {groupId, artifactId}, since the default for the type field is jar, and the default classifier is null.” [https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html ]
Thus, all the sub-elements (scope, exclusions etc.,) of a dependency element--other than groupId, artifactId, type, classifier, not just version--are available for lockdown/default at the point (and thus inherited from there onward) you specify the dependency within a dependencyElement. If you’d specified a dependency with the type and classifier sub-elements (see the first-cited webpage to check all sub-elements) as not jar and not null respectively, you’d need {groupId, artifactId, classifier, type} to reference (resolve) that dependency at any point in an inheritance originating from the dependencyManagement element. Else, {groupId, artifactId} would suffice if you do not intend to override the defaults for classifier and type (jar and null respectively). So default is a good keyword in that definition; any sub-element(s) (other than groupId, artifactId, classifier and type, of course) explicitly assigned value(s) at the point you reference a dependency override the defaults in the dependencyManagement element.
So, any dependency element outside of dependencyManagement, whether as a reference to some dependencyManagement element or as a standalone is immediately resolved (i.e. installed to the local repository and available for classpaths).
You don't need to set "fixed"
- all you need is setting overflow:hidden
since the column width is set.
<context:property-placeholder location="classpath*:spring/*.properties" />
If you place it somewhere in the classpath in a directory named spring (change names/dirs accordingly), you can access with above
<property name="locations" value ="config/springcontext.properties" />
this will be pointing to web-inf/classes/config/springcontext.properties
Setting margin in layout params will not work in Alertdialog. you have to set padding in parent layout and then add edittext in that layout.
This is my working kotlin code...
val alert = AlertDialog.Builder(context!!)
val edittext = EditText(context!!)
edittext.hint = "Enter Name"
edittext.maxLines = 1
val layout = FrameLayout(context!!)
//set padding in parent layout
layout.setPaddingRelative(45,15,45,0)
alert.setTitle(title)
layout.addView(edittext)
alert.setView(layout)
alert.setPositiveButton(getString(R.string.label_save), DialogInterface.OnClickListener {
dialog, which ->
run {
val qName = edittext.text.toString()
Utility.hideKeyboard(context!!, dialogView!!)
}
})
alert.setNegativeButton(getString(R.string.label_cancel), DialogInterface.OnClickListener {
dialog, which ->
run {
dismiss()
}
})
alert.show()
for large numbers that display with scientific notation set format to just '#'
Accessing CSS property & manipulating is quite easy using .css(). For example, to change single property:
$("selector").css('top', '50px');
I had the same problem, and tried a lot of different variants. After some tries I became able to sudo gem install
, but still have problem to install it without sudo.
Finally I found a decission - reinstalling of rvm helped me. Probably it can save time somebody else.
In my case (Mac OS X and previously used Angular 1.5 environment)
npm -g cache clean --force
npm cache clean --force
worked. (npm install -g @angular/cli@latest
afterwards)
My installation of Android Studio is completely offline. To resolve these kind of problems I have used the Process Monitor. It showed that a few files are missing within "Android Studio\gradle\m2repository". I have downloaded all files from
and copied these files in "Android Studio\gradle\m2repository". You have to create the structure below "m2repository" as it is below "maven2". Maybe there are more missing files, but at this time at least Gradle build is finished without errors.
Now in 2017 with ASP.Net Core you can do it as explained here.
The Microsoft.AspNetCore.Session package provides middleware for managing session state.
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// Adds a default in-memory implementation of IDistributedCache.
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
// Set a short timeout for easy testing.
options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.HttpOnly = true;
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSession();
}
From the Docs: Introduction to session and application state in ASP.NET Core
Already tested on a working project
This should work with any kind of database.
In the spirit of being complete, the answers that instruct you to use Guid.NewGuid()
are correct.
In addressing your subsequent edit, you'll need to post the code for your RequestObject
class. I'm suspecting that your guid property is not marked as a DataMember
, and thus is not being serialized over the wire. Since default(Guid)
is the same as new Guid()
(i.e. all 0
's), this would explain the behavior you're seeing.
import datetime
todays_date = datetime.date.today()
print(todays_date)
>>> 2019-10-12
# adding strftime will remove the seconds
current_time = datetime.datetime.now().strftime('%H:%M')
print(current_time)
>>> 23:38
You're looking for Enum.Parse.
SomeEnum enum = (SomeEnum)Enum.Parse(typeof(SomeEnum), "EnumValue");
Both syntaxes are correct. But the result would be Array
. You probably want to do something like this:
foreach ($tmpArray[1] as $value) {
echo $value[0];
foreach($value[1] as $val){
echo $val;
}
}
This will print out the string "two" ($value[0]) and the integers 4, 5 and 6 from the array ($value[1]).
This is my test. Hope it is useful.
# $COMMAND is the command used to create the reverse ssh tunnel
COMMAND="ssh -p $SSH_PORT -q -N -R $REMOTE_HOST:$REMOTE_HTTP_PORT:localhost:80 $USER_NAME@$REMOTE_HOST"
# Is the tunnel up? Perform two tests:
# 1. Check for relevant process ($COMMAND)
pgrep -f -x "$COMMAND" > /dev/null 2>&1 || $COMMAND
# 2. Test tunnel by looking at "netstat" output on $REMOTE_HOST
ssh -p $SSH_PORT $USER_NAME@$REMOTE_HOST netstat -an | egrep "tcp.*:$REMOTE_HTTP_PORT.*LISTEN" \
> /dev/null 2>&1
if [ $? -ne 0 ] ; then
pkill -f -x "$COMMAND"
$COMMAND
fi
I figured it out. Basically it's an async issue. You can't just submit and expect to render the subsequent page immediately. You have to wait until the onLoad event for the next page is triggered. My code is below:
var page = new WebPage(), testindex = 0, loadInProgress = false;
page.onConsoleMessage = function(msg) {
console.log(msg);
};
page.onLoadStarted = function() {
loadInProgress = true;
console.log("load started");
};
page.onLoadFinished = function() {
loadInProgress = false;
console.log("load finished");
};
var steps = [
function() {
//Load Login Page
page.open("https://website.com/theformpage/");
},
function() {
//Enter Credentials
page.evaluate(function() {
var arr = document.getElementsByClassName("login-form");
var i;
for (i=0; i < arr.length; i++) {
if (arr[i].getAttribute('method') == "POST") {
arr[i].elements["email"].value="mylogin";
arr[i].elements["password"].value="mypassword";
return;
}
}
});
},
function() {
//Login
page.evaluate(function() {
var arr = document.getElementsByClassName("login-form");
var i;
for (i=0; i < arr.length; i++) {
if (arr[i].getAttribute('method') == "POST") {
arr[i].submit();
return;
}
}
});
},
function() {
// Output content of page to stdout after form has been submitted
page.evaluate(function() {
console.log(document.querySelectorAll('html')[0].outerHTML);
});
}
];
interval = setInterval(function() {
if (!loadInProgress && typeof steps[testindex] == "function") {
console.log("step " + (testindex + 1));
steps[testindex]();
testindex++;
}
if (typeof steps[testindex] != "function") {
console.log("test complete!");
phantom.exit();
}
}, 50);
Alternative solution on Windows is to install python-certifi-win32 that will allow Python to use Windows Certificate Store.
pip install python-certifi-win32
In the new version of VSCODE ( version 1.26.1)
comment
Double click the existing shortcut 'keybinding` You can assign any shortcuts you want. Hope it helps.
AFAIK you will need at least a little bit of JavaScript...
I would suggest to use jQuery.
You can include this library in one line. And then you can access your div with
$('div').click(function(){
// do stuff here
});
and respond to the click event.
Its better to build ObservableCollection and take advantage of it
public ObservableCollection<string> list = new ObservableCollection<string>();
list.Add("a");
list.Add("b");
list.Add("c");
this.cbx.ItemsSource = list;
cbx is comobobox name
Also Read : Difference between List, ObservableCollection and INotifyPropertyChanged
According to one of the first Google search hits: http://www.csharp-examples.net/string-format-datetime/
// Where 'dt' is the DateTime object...
String.Format("{0:dd-MM-yyyy}", dt);
ord()
will not work because your end string is two characters long.
Returns the ASCII value of the first character of string.
From my testing, you need to check that the end
string doesn't get "stepped over". The perl-style character incrementation is a cool method, but it is a single-stepping method. For this reason, an inner loop helps it along when necessary. This is actually not a bother, in fact, it is useful because we need to check if the loop(s) should be broken on each single step.
Code: (Demo)
function excelCols($letter,$end,$step=1){ // function doesn't check that $end is "later" than $letter
if($step==0)return []; // prevent infinite loop
do{
$letters[]=$letter; // store letter
for($x=0; $x<$step; ++$x){ // increment in accordance with $step declaration
if($letter===$end)break(2); // break if end is "stepped on"
++$letter;
}
}while(true);
return $letters;
}
echo implode(' ',excelCols('A','JJ',4));
echo "\n --- \n";
echo implode(' ',excelCols('A','BB',3));
echo "\n --- \n";
echo implode(' ',excelCols('A','ZZ',1));
echo "\n --- \n";
echo implode(' ',excelCols('A','ZZ',3));
Output:
A E I M Q U Y AC AG AK AO AS AW BA BE BI BM BQ BU BY CC CG CK CO CS CW DA DE DI DM DQ DU DY EC EG EK EO ES EW FA FE FI FM FQ FU FY GC GG GK GO GS GW HA HE HI HM HQ HU HY IC IG IK IO IS IW JA JE JI
---
A D G J M P S V Y AB AE AH AK AN AQ AT AW AZ
---
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 AA AB AC AD AE AF AG AH AI AJ AK AL AM AN AO AP AQ AR AS AT AU AV AW AX AY AZ BA BB BC BD BE BF BG BH BI BJ BK BL BM BN BO BP BQ BR BS BT BU BV BW BX BY BZ CA CB CC CD CE CF CG CH CI CJ CK CL CM CN CO CP CQ CR CS CT CU CV CW CX CY CZ DA DB DC DD DE DF DG DH DI DJ DK DL DM DN DO DP DQ DR DS DT DU DV DW DX DY DZ EA EB EC ED EE EF EG EH EI EJ EK EL EM EN EO EP EQ ER ES ET EU EV EW EX EY EZ FA FB FC FD FE FF FG FH FI FJ FK FL FM FN FO FP FQ FR FS FT FU FV FW FX FY FZ GA GB GC GD GE GF GG GH GI GJ GK GL GM GN GO GP GQ GR GS GT GU GV GW GX GY GZ HA HB HC HD HE HF HG HH HI HJ HK HL HM HN HO HP HQ HR HS HT HU HV HW HX HY HZ IA IB IC ID IE IF IG IH II IJ IK IL IM IN IO IP IQ IR IS IT IU IV IW IX IY IZ JA JB JC JD JE JF JG JH JI JJ JK JL JM JN JO JP JQ JR JS JT JU JV JW JX JY JZ KA KB KC KD KE KF KG KH KI KJ KK KL KM KN KO KP KQ KR KS KT KU KV KW KX KY KZ LA LB LC LD LE LF LG LH LI LJ LK LL LM LN LO LP LQ LR LS LT LU LV LW LX LY LZ MA MB MC MD ME MF MG MH MI MJ MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ NA NB NC ND NE NF NG NH NI NJ NK NL NM NN NO NP NQ NR NS NT NU NV NW NX NY NZ OA OB OC OD OE OF OG OH OI OJ OK OL OM ON OO OP OQ OR OS OT OU OV OW OX OY OZ PA PB PC PD PE PF PG PH PI PJ PK PL PM PN PO PP PQ PR PS PT PU PV PW PX PY PZ QA QB QC QD QE QF QG QH QI QJ QK QL QM QN QO QP QQ QR QS QT QU QV QW QX QY QZ RA RB RC RD RE RF RG RH RI RJ RK RL RM RN RO RP RQ RR RS RT RU RV RW RX RY RZ SA SB SC SD SE SF SG SH SI SJ SK SL SM SN SO SP SQ SR SS ST SU SV SW SX SY SZ TA TB TC TD TE TF TG TH TI TJ TK TL TM TN TO TP TQ TR TS TT TU TV TW TX TY TZ UA UB UC UD UE UF UG UH UI UJ UK UL UM UN UO UP UQ UR US UT UU UV UW UX UY UZ VA VB VC VD VE VF VG VH VI VJ VK VL VM VN VO VP VQ VR VS VT VU VV VW VX VY VZ WA WB WC WD WE WF WG WH WI WJ WK WL WM WN WO WP WQ WR WS WT WU WV WW WX WY WZ XA XB XC XD XE XF XG XH XI XJ XK XL XM XN XO XP XQ XR XS XT XU XV XW XX XY XZ YA YB YC YD YE YF YG YH YI YJ YK YL YM YN YO YP YQ YR YS YT YU YV YW YX YY YZ ZA ZB ZC ZD ZE ZF ZG ZH ZI ZJ ZK ZL ZM ZN ZO ZP ZQ ZR ZS ZT ZU ZV ZW ZX ZY ZZ
---
A D G J M P S V Y AB AE AH AK AN AQ AT AW AZ BC BF BI BL BO BR BU BX CA CD CG CJ CM CP CS CV CY DB DE DH DK DN DQ DT DW DZ EC EF EI EL EO ER EU EX FA FD FG FJ FM FP FS FV FY GB GE GH GK GN GQ GT GW GZ HC HF HI HL HO HR HU HX IA ID IG IJ IM IP IS IV IY JB JE JH JK JN JQ JT JW JZ KC KF KI KL KO KR KU KX LA LD LG LJ LM LP LS LV LY MB ME MH MK MN MQ MT MW MZ NC NF NI NL NO NR NU NX OA OD OG OJ OM OP OS OV OY PB PE PH PK PN PQ PT PW PZ QC QF QI QL QO QR QU QX RA RD RG RJ RM RP RS RV RY SB SE SH SK SN SQ ST SW SZ TC TF TI TL TO TR TU TX UA UD UG UJ UM UP US UV UY VB VE VH VK VN VQ VT VW VZ WC WF WI WL WO WR WU WX XA XD XG XJ XM XP XS XV XY YB YE YH YK YN YQ YT YW YZ ZC ZF ZI ZL ZO ZR ZU ZX
Here is an array-functions approach:
Code: (Demo)
$start='C';
$end='DD';
$step=4;
// generate and store more than we need (this is an obvious method disadvantage)
$result=$array=range('A','Z',1); // store A - Z as $array and $result
foreach($array as $a){
foreach($array as $b){
$result[]="$a$b"; // store double letter combinations
if(in_array($end,$result)){break(2);} // stop asap
}
}
//echo implode(' ',$result),"\n\n";
// slice away from the front of the array
$result=array_slice($result,array_search($start,$result)); // reindex keys
//echo implode(' ',$result),"\n\n";
// punch out elements that are not "stepped on"
$result=array_filter($result,function($k)use($step){return $k%$step==0;},ARRAY_FILTER_USE_KEY); // use modulo
// result is ready
echo implode(' ',$result);
Output:
C G K O S W AA AE AI AM AQ AU AY BC BG BK BO BS BW CA CE CI CM CQ CU CY DC
If you want to take advantage of the 60FPS smoothness that the "transform" property offers, you can combine the two:
@keyframes changewidth {
from {
transform: scaleX(1);
}
to {
transform: scaleX(2);
}
}
div {
animation-duration: 0.1s;
animation-name: changewidth;
animation-iteration-count: infinite;
animation-direction: alternate;
}
More explanation on why transform offers smoother transitions here: https://medium.com/outsystems-experts/how-to-achieve-60-fps-animations-with-css3-db7b98610108
I suggest another way to solve to this problem. The idea is wrapping your viewPager by a scrollView, so that when this scrollView is non-scrollable, your viewPager is non-scrollable too.
Here is my XML layout:
<HorizontalScrollView
android:id="@+id/horizontalScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true" >
<android.support.v4.view.ViewPager
android:id="@+id/viewPager"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
</HorizontalScrollView>
No code needed.
Works fine for me.
If you want to create a garage and fill it up with new cars that can be accessed later, use this code:
for (int i = 0; i < garage.length; i++)
garage[i] = new Car("argument");
Also, the cars are later accessed using:
garage[0];
garage[1];
garage[2];
etc.
I am using ANGULAR and since it gave me problems the routerLink just add the data-toggle and target in the li tag.... or use jquery like "ZimSystem"
<div class="collapse navbar-collapse" id="navbarSupportedContent">_x000D_
<ul class="navbar-nav mr-auto">_x000D_
<li class="nav-item" data-toggle="collapse" data-target=".navbar-collapse.show">_x000D_
<a class="nav-link" routerLink="/inicio" routerLinkActive="active" >Inicio</a>_x000D_
</li>_x000D_
</ul>_x000D_
</div>
_x000D_
Check this key for 32 bits and 64 bits Windows machines.
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
and this for Windows 64 bits with 32 Bits JRE.
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Java Runtime Environment
This will work for the oracle-sun JRE.
I would go with xml and xpath:
dir C:\Projects\project_*\project*.config -recurse | foreach-object{
$wc = [xml](Get-Content $_.fullname)
$wc.SelectNodes("//add[@key='Environment'][@value='Dev']") | Foreach-Object {$_.value = 'Demo'}
$wc.Save($_.fullname)
}
It exists because it is more convenient to use, also it is a whole different ideology using attributes to mark the authorization parameters rather than xml configuration. It wasn't meant to beat general purpose config or any other authorization frameworks, just MVC's way of doing it. I'm saying this, because it seems you are looking for a technical feature advantages which are probably non... just superb convenience.
BobRock already listed the advantages. Just to add to his answer, another scenarios are that you can apply this attribute to whole controller, not just actions, also you can add different role authorization parameters to different actions in same controller to mix and match.
You need to run the cmd prompt from the Scripts directory of Anaconda where ever you have the Anaconda parent folder installed. I happen to have in the root directory of the C drive on my Windows machine. If you are not familiar there are two ways to do that:
A) Use the key combination Win-key + R
then type cmd
and hit return to launch the terminal window and then type: cd C:\Anaconda\Scripts
(or whatever directory path yours is).
B) Navigate using windows explorer to that Scripts directory then type cmd
in the address bar of that window and hit return (that will launch the terminal already set to that directory).
Next type the follow commands waiting in between for each to complete:
activate root
conda update -n root conda
conda update --all
When complete type the following and Navigator hopefully should launch:
anaconda-navigator
Cross browser testing java scripts
public class MultipleBrowser {
public WebDriver driver= null;
String browser="mozilla";
String url="https://www.omnicard.com";
@BeforeMethod
public void LaunchBrowser() {
if(browser.equalsIgnoreCase("mozilla"))
driver= new FirefoxDriver();
else if(browser.equalsIgnoreCase("safari"))
driver= new SafariDriver();
else if(browser.equalsIgnoreCase("chrome"))
//System.setProperty("webdriver.chrome.driver","/Users/mhossain/Desktop/chromedriver");
driver= new ChromeDriver();
driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
driver.navigate().to(url);
}
}
but when you want to run firefox you need to chrome path disable, otherwise browser will launch but application may not.(try both way) .
I am not sure, but it might be worth running an eval on the commands first.
This will let bash expand the variables $TAR_CMD and such to their full breadth(just as the echo command does to the console, which you say works)
Bash will then read the line a second time with the variables expanded.
eval $TAR_CMD | $ENCRYPT_CMD | $SPLIT_CMD
I just did a Google search and this page looks like it might do a decent job at explaining why that is needed. http://fvue.nl/wiki/Bash:_Why_use_eval_with_variable_expansion%3F
SQL Row_Number() function is to sort and assign an order number to data rows in related record set. So it is used to number rows, for example to identify the top 10 rows which have the highest order amount or identify the order of each customer which is the highest amount, etc.
If you want to sort the dataset and number each row by seperating them into categories we use Row_Number() with Partition By clause. For example, sorting orders of each customer within itself where the dataset contains all orders, etc.
SELECT
SalesOrderNumber,
CustomerId,
SubTotal,
ROW_NUMBER() OVER (PARTITION BY CustomerId ORDER BY SubTotal DESC) rn
FROM Sales.SalesOrderHeader
But as I understand you want to calculate the number of rows of grouped by a column. To visualize the requirement, if you want to see the count of all orders of the related customer as a seperate column besides order info, you can use COUNT() aggregation function with Partition By clause
For example,
SELECT
SalesOrderNumber,
CustomerId,
COUNT(*) OVER (PARTITION BY CustomerId) CustomerOrderCount
FROM Sales.SalesOrderHeader
I am using MySQL 5.5.40. This version has the option --all-databases
mysqldump -u<username> -p<password> --all-databases --events > /tmp/all_databases__`date +%d_%b_%Y_%H_%M_%S`.sql
This command will create a complete backup of all databases in MySQL server to file named to current date-time.
How about treat the external script as a Java class? Based on this article: https://www.jmdawson.net/blog/2014/08/18/using-functions-from-one-groovy-script-in-another/
getThing.groovy The external script
def getThingList() {
return ["thing","thin2","thing3"]
}
printThing.groovy The main script
thing = new getThing() // new the class which represents the external script
println thing.getThingList()
Result
$ groovy printThing.groovy
[thing, thin2, thing3]
What I use (and it's been working great) is a "templates" directory and a "static" directory. I place all my .html files/Flask templates inside the templates directory, and static contains CSS/JS. render_template works fine for generic html files to my knowledge, regardless of the extent at which you used Flask's templating syntax. Below is a sample call in my views.py file.
@app.route('/projects')
def projects():
return render_template("projects.html", title = 'Projects')
Just make sure you use url_for() when you do want to reference some static file in the separate static directory. You'll probably end up doing this anyways in your CSS/JS file links in html. For instance...
<script src="{{ url_for('static', filename='styles/dist/js/bootstrap.js') }}"></script>
Here's a link to the "canonical" informal Flask tutorial - lots of great tips in here to help you hit the ground running.
http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
I know the answers are relating to changing grouped table cells, but in case someone is wanting to also change the tableview's background color:
Not only do you need to set:
tableview.backgroundColor = color;
You also need to change or get rid of the background view:
tableview.backgroundView = nil;
To continue off of bobince's answer
In es6 you can now actually create a class
So now you can do:
class Shape {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return `Shape at ${this.x}, ${this.y}`;
}
}
So extend to a circle (as in the other answer) you can do:
class Circle extends Shape {
constructor(x, y, r) {
super(x, y);
this.r = r;
}
toString() {
let shapeString = super.toString();
return `Circular ${shapeString} with radius ${this.r}`;
}
}
Ends up a bit cleaner in es6 and a little easier to read.
Here is a good example of it in action:
class Shape {_x000D_
constructor(x, y) {_x000D_
this.x = x;_x000D_
this.y = y;_x000D_
}_x000D_
_x000D_
toString() {_x000D_
return `Shape at ${this.x}, ${this.y}`;_x000D_
}_x000D_
}_x000D_
_x000D_
class Circle extends Shape {_x000D_
constructor(x, y, r) {_x000D_
super(x, y);_x000D_
this.r = r;_x000D_
}_x000D_
_x000D_
toString() {_x000D_
let shapeString = super.toString();_x000D_
return `Circular ${shapeString} with radius ${this.r}`;_x000D_
}_x000D_
}_x000D_
_x000D_
let c = new Circle(1, 2, 4);_x000D_
_x000D_
console.log('' + c, c);
_x000D_
Have you tried using the ConflictResolution:=xlLocalSessionChanges parameter in the SaveAs method?
As so:
Public Sub example()
Application.DisplayAlerts = False
Application.EnableEvents = False
For Each element In sArray
XLSMToXLSX(element)
Next element
Application.DisplayAlerts = False
Application.EnableEvents = False
End Sub
Sub XLSMToXLSX(ByVal file As String)
Do While WorkFile <> ""
If Right(WorkFile, 4) <> "xlsx" Then
Workbooks.Open Filename:=myPath & WorkFile
Application.DisplayAlerts = False
Application.EnableEvents = False
ActiveWorkbook.SaveAs Filename:= _
modifiedFileName, FileFormat:= _
xlOpenXMLWorkbook, CreateBackup:=False, _
ConflictResolution:=xlLocalSessionChanges
Application.DisplayAlerts = True
Application.EnableEvents = True
ActiveWorkbook.Close
End If
WorkFile = Dir()
Loop
End Sub
This is the code I use for creating an index sheet.
Sub CreateIndexSheet()
Dim wSheet As Worksheet
ActiveWorkbook.Sheets.Add(Before:=Worksheets(1)).Name = "Contents" 'Call whatever you like
Range("A1").Select
Application.ScreenUpdating = False 'Prevents seeing all the flashing as it updates the sheet
For Each wSheet In Worksheets
ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:="", SubAddress:="'" & wSheet.Name & "'" & "!A1", TextToDisplay:=wSheet.Name
ActiveCell.Offset(1, 0).Select 'Moves down a row
Next
Range("A1").EntireColumn.AutoFit
Range("A1").EntireRow.Delete 'Remove content sheet from content list
Application.ScreenUpdating = True
End Sub
If anyone wants to enable dark mode, you may follow the below steps
Python files are executables, which means that you can run them directly from command prompt(assuming you have windows). You should be able to just enter in the directory, and then run the program. Also, (assuming you have python 3), you can write:
input("Press enter to close program")
and you can just press enter when you've read your results.
First yield program
def countdown_gen(x):
count = x
while count > 0:
yield count
count -= 1
g = countdown_gen(5)
for item in g:
print(item)
Output
5
4
3
2
1
Understand flow
Note
I've found that some developers will for some reason define the server's private IP outside of IIS in an unexpected location, like a nonstandard config file (i.e. not web.config) or a text file. This can cause internal operation to fail even when the service is started, ports aren't being blocked, reg keys are correct, etc.
Kaseya, in particular, places a file called serveripinternal.txt in the root IIS directory of the VSA server. I've seen the text of your error when somebody running their own Kaseya instance changed the server's internal IP. The server will be reachable, IIS will respond, and the login page will come up - but login will fail with the cited message.
A bit late to the party but you can also use a context manager, if you're opening and closing your file multiple times, or logging data, statistics, etc.
from contextlib import contextmanager
import pandas as pd
@contextmanager
def open_file(path, mode):
file_to=open(path,mode)
yield file_to
file_to.close()
##later
saved_df=pd.DataFrame(data)
with open_file('yourcsv.csv','r') as infile:
saved_df.to_csv('yourcsv.csv',mode='a',header=False)`
I also had this problem. I changed port and did other things, but they didn't help me. In my case, I connected Tomcat to IDE after installing Netbeans (before). I just uninstalled Netbeans and Tomcat after that I reinstall Netbeans along with Tomcat (NOT separately). And the problem was solved.
I found a website offering a list of 20 distinctive colours: https://sashat.me/2017/01/11/list-of-20-simple-distinct-colors/
col_vector<-c('#e6194b', '#3cb44b', '#ffe119', '#4363d8', '#f58231', '#911eb4', '#46f0f0', '#f032e6', '#bcf60c', '#fabebe', '#008080', '#e6beff', '#9a6324', '#fffac8', '#800000', '#aaffc3', '#808000', '#ffd8b1', '#000075', '#808080', '#ffffff', '#000000')
You can have a try!
This worked well for me. I hope it will fix your issues too.
function toFixedNumber(number) {
const spitedValues = String(number.toLocaleString()).split('.');
let decimalValue = spitedValues.length > 1 ? spitedValues[1] : '';
decimalValue = decimalValue.concat('00').substr(0,2);
return '$'+spitedValues[0] + '.' + decimalValue;
}
// 5.56789 ----> $5.56
// 0.342 ----> $0.34
// -10.3484534 ----> $-10.34
// 600 ----> $600.00
function convertNumber(){_x000D_
var result = toFixedNumber(document.getElementById("valueText").value);_x000D_
document.getElementById("resultText").value = result;_x000D_
}_x000D_
_x000D_
_x000D_
function toFixedNumber(number) {_x000D_
const spitedValues = String(number.toLocaleString()).split('.');_x000D_
let decimalValue = spitedValues.length > 1 ? spitedValues[1] : '';_x000D_
decimalValue = decimalValue.concat('00').substr(0,2);_x000D_
_x000D_
return '$'+spitedValues[0] + '.' + decimalValue;_x000D_
}
_x000D_
<div>_x000D_
<input type="text" id="valueText" placeholder="Input value here..">_x000D_
<br>_x000D_
<button onclick="convertNumber()" >Convert</button>_x000D_
<br><hr>_x000D_
<input type="text" id="resultText" placeholder="result" readonly="true">_x000D_
</div>
_x000D_
As guruz mentioned, the JIT has several lovely graph/tree layouts, including quite appealing RGraph and HyperTree visualizations.
Also, I've just put up a super simple SVG-based implementation at github (no dependencies, ~125 LOC) that should work well enough for small graphs displayed in modern browsers.
running make clean
and then ./configure
should solve your problem.
when you are in El Capitan, will get error: ln: /usr/lib/libmysqlclient.18.dylib: Operation not permitted
need to close the "System Integrity Protection".
first, reboot and hold on cmd + R to enter the Recovery mode, then launch the terminal and type the command: csrutil disable
, now you can reboot and try again.
You can also delete the branch on the remote directly. Having done that, the next update will remove it from your working copy.
svn rm "^/reponame/branches/name_of_branch" -m "cleaning up old branch name_of_branch"
The ^
is short for the URL of the remote, as seen in 'svn info'. The double quotes are necessary on Windows command line, because ^
is a special character.
This command will also work if you have never checked out the branch.
I have a way, you guys tell me how good it is.
Create a new object of the class and compare it with your object (which you want to check for emptiness).
To be correctly able to do it :
Override the hashCode() and equals() methods of your model class and also of the classes, objects of whose are members of your class, for example :
Person class (primary model class) :
public class Person {
private int age;
private String firstName;
private String lastName;
private Address address;
//getters and setters
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((address == null) ? 0 : address.hashCode());
result = prime * result + age;
result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (address == null) {
if (other.address != null)
return false;
} else if (!address.equals(other.address))
return false;
if (age != other.age)
return false;
if (firstName == null) {
if (other.firstName != null)
return false;
} else if (!firstName.equals(other.firstName))
return false;
if (lastName == null) {
if (other.lastName != null)
return false;
} else if (!lastName.equals(other.lastName))
return false;
return true;
}
@Override
public String toString() {
return "Person [age=" + age + ", firstName=" + firstName + ", lastName=" + lastName + ", address=" + address
+ "]";
}
}
Address class (used inside Person class) :
public class Address {
private String line1;
private String line2;
//getters and setters
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((line1 == null) ? 0 : line1.hashCode());
result = prime * result + ((line2 == null) ? 0 : line2.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Address other = (Address) obj;
if (line1 == null) {
if (other.line1 != null)
return false;
} else if (!line1.equals(other.line1))
return false;
if (line2 == null) {
if (other.line2 != null)
return false;
} else if (!line2.equals(other.line2))
return false;
return true;
}
@Override
public String toString() {
return "Address [line1=" + line1 + ", line2=" + line2 + "]";
}
}
Now in the main class :
Person person1 = new Person();
person1.setAge(20);
Person person2 = new Person();
Person person3 = new Person();
if(person1.equals(person2)) --> this will be false
if(person2.equals(person3)) --> this will be true
I hope this is the best way instead of putting if conditions on each and every member variables.
Let me know !
If you are using python 3 or above,
>>> list(bytes(b'test'))
[116, 101, 115, 116]
Here is the answer for those of you who need a Boostrap 3 solution.
In bootstrap 3 use 'shown.bs.tab' instead of 'shown' in the next line
// tab
$('#rowTab a:first').tab('show');
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
//show selected tab / active
console.log ( $(e.target).attr('id') );
});
$data = json_decode($json, true);
echo $data[0]["c_name"]; // "John"
$data = json_decode($json);
echo $data[0]->c_name; // "John"
Check that userInteractionEnabled
is YES
on the UIImageView
. Then you can add a gesture recognizer.
imageView.userInteractionEnabled = YES;
UIPinchGestureRecognizer *pgr = [[UIPinchGestureRecognizer alloc]
initWithTarget:self action:@selector(handlePinch:)];
pgr.delegate = self;
[imageView addGestureRecognizer:pgr];
[pgr release];
:
:
- (void)handlePinch:(UIPinchGestureRecognizer *)pinchGestureRecognizer
{
//handle pinch...
}
<span>
will allow you to style text, but it adds no semantic content.
As you're emphasizing some text, it sounds like you'd be better served by wrapping the text in <em></em>
and using CSS to change the color of the <em>
element. For example:
.description {
color: #fff;
}
.description em {
color: #ffa500;
}
<p class="description">Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Sed hendrerit mollis varius. Etiam ornare placerat
massa, <em>eget vulputate tellus fermentum.</em></p>
In fact, I'd go to great pains to avoid the <span>
element, as it's completely meaningless to everything that doesn't render your style sheet (bots, screen readers, luddites who disable styles, parsers, etc.) or renders it in unexpected ways (personal style sheets). In many ways, it's no better than using the <font>
element.
.description {_x000D_
color: #000;_x000D_
}_x000D_
_x000D_
.description em {_x000D_
color: #ffa500;_x000D_
}
_x000D_
<p class="description">Lorem ipsum dolor sit amet, consectetur _x000D_
adipiscing elit. Sed hendrerit mollis varius. Etiam ornare placerat _x000D_
massa, <em>eget vulputate tellus fermentum.</em></p>
_x000D_
Use:
sudo DEBIAN_FRONTEND=noninteractive apt-get install -y mysql-server
sudo mysql -h127.0.0.1 -P3306 -uroot -e"UPDATE mysql.user SET password = PASSWORD('yourpassword') WHERE user = 'root'"
It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:
[...] when looping through the
Iterable
value list, each Object instance is re-used, so it only keeps one instance around at a given time.
System.currentTimeMillis()
is obviously the most efficient since it does not even create an object, but new Date()
is really just a thin wrapper about a long, so it is not far behind. Calendar
, on the other hand, is relatively slow and very complex, since it has to deal with the considerably complexity and all the oddities that are inherent to dates and times (leap years, daylight savings, timezones, etc.).
It's generally a good idea to deal only with long timestamps or Date
objects within your application, and only use Calendar
when you actually need to perform date/time calculations, or to format dates for displaying them to the user. If you have to do a lot of this, using Joda Time is probably a good idea, for the cleaner interface and better performance.
I suppose that Chrome's behavior is more consistent with the CSS specification (though it's less intuitive). According to Flexbox specification, the default stretch
value of align-self
property changes only the used value of the element's "cross size property" (height
, in this case). And, as I understand the CSS 2.1 specification, the percentage heights are calculated from the specified value of the parent's height
, not its used value. The specified value of the parent's height
isn't affected by any flex properties and is still auto
.
Setting an explicit height: 100%
makes it formally possible to calculate the percentage height of the child, just like setting height: 100%
to html
makes it possible to calculate the percentage height of body
in CSS 2.1.
Remove if
from if @item.rigged ? "Yes" : "No"
Ternary operator has form condition ? if_true : if_false
@Autowired
private EntityManager entityManager;
@RequestMapping("/authors/{fname}/{lname}")
public List actionAutherMulti(@PathVariable("fname") String fname, @PathVariable("lname") String lname) {
return entityManager.createQuery("select A from Auther A WHERE A.firstName = ?1 AND A.lastName=?2")
.setParameter(1, fname)
.setParameter(2, lname)
.getResultList();
}
Works the best. If you want to use it sitewide, without having to add this syntax to every class or ID, add the following CSS to your css body:
body {
-webkit-font-smoothing: antialiased;
text-shadow: 1px 1px 1px rgba(0,0,0,0.004);
background: url('./images/background.png');
text-align: left;
margin: auto;
}
$key = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion'
(Get-ItemProperty -Path $key -Name ProgramFilesDir).ProgramFilesDir
I've never liked how this was provider was implemented like this : /
Basically, it makes every registry value a PSCustomObject
object with PsPath
, PsParentPath
, PsChildname
, PSDrive
and PSProvider
properties and then a property for its actual value. So even though you asked for the item by name, to get its value you have to use the name once more.
Yes there is a difference.
The Runtime.exec(String)
method takes a single command string that it splits into a command and a sequence of arguments.
The ProcessBuilder
constructor takes a (varargs) array of strings. The first string is the command name and the rest of them are the arguments. (There is an alternative constructor that takes a list of strings, but none that takes a single string consisting of the command and arguments.)
So what you are telling ProcessBuilder to do is to execute a "command" whose name has spaces and other junk in it. Of course, the operating system can't find a command with that name, and the command execution fails.
if using logging.config.fileConfig with a configuration file use something like:
[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=%Y-%m-%d %H:%M:%S
you can try this:"Filename.txt" file will be created automatically in the bin->debug folder everytime you run this code or you can specify path of the file like: @"C:/...". you can check ëxistance of "Hello" by going to the bin -->debug folder
P.S dont forget to add Console.Readline() after this code snippet else console will not appear.
TextWriter tw = new StreamWriter("filename.txt");
String text = "Hello";
tw.WriteLine(text);
tw.Close();
TextReader tr = new StreamReader("filename.txt");
Console.WriteLine(tr.ReadLine());
tr.Close();
Try this:
<select id="sel">
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
<input type="button" value="Change option to 2" onclick="changeOpt()"/>
<script>
function changeOpt(){
document.getElementById("sel").options[1].selected = true;
alert("changed")
}
</script>
you can saperate string using the below code
String thisString="Hello world";
String[] parts = theString.split(" ");
String first = parts[0];//"hello"
String second = parts[1];//"World"
Based on @Ross's answer answer for Chart.js 2.0 and up, I had to include a little tweak to guard against the case when the bar's heights comes too chose to the scale boundary.
The animation
attribute of the bar chart's option:
animation: {
duration: 500,
easing: "easeOutQuart",
onComplete: function () {
var ctx = this.chart.ctx;
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function (dataset) {
for (var i = 0; i < dataset.data.length; i++) {
var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model,
scale_max = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._yScale.maxHeight;
ctx.fillStyle = '#444';
var y_pos = model.y - 5;
// Make sure data value does not get overflown and hidden
// when the bar's value is too close to max value of scale
// Note: The y value is reverse, it counts from top down
if ((scale_max - model.y) / scale_max >= 0.93)
y_pos = model.y + 20;
ctx.fillText(dataset.data[i], model.x, y_pos);
}
});
}
}
The version of ruby version which phusion passenger was used is differenced with your rails app.
<IfModule mod_passenger.c>
PassengerRoot /usr/local/rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/passenger-6.0.2
PassengerDefaultRuby /usr/local/rbenv/versions/2.5.3/bin/ruby
</IfModule>
Make sure the version on httpd config is the same with rails app.
To support both Python 2 and Python 3, use explicit relative imports as below. They are relative to the current module. They have been supported starting from 2.5.
from .sister import foo
from . import brother
from ..aunt import bar
from .. import uncle
One thing that you need to be aware of when reflecting on private members is that if your application is running in medium trust (as, for instance, when you are running on a shared hosting environment), it won't find them -- the BindingFlags.NonPublic option will simply be ignored.
Just change the url to http://localhost
instead of localhost
. If you open the html file from local, you should create a local server to serve that html file, the simplest way is using Web Server for Chrome
. That will fix the issue.
Append the line useUnicode=true&characterEncoding=UTF-8
to your jdbc url.
In your case the data is not being send using UTF-8
encoding.
There are a few details missing from the previous explanations. To better understand how partitioning and bucketing works, you should look at how data is stored in hive. Let's say you have a table
CREATE TABLE mytable (
name string,
city string,
employee_id int )
PARTITIONED BY (year STRING, month STRING, day STRING)
CLUSTERED BY (employee_id) INTO 256 BUCKETS
then hive will store data in a directory hierarchy like
/user/hive/warehouse/mytable/y=2015/m=12/d=02
So, you have to be careful when partitioning, because if you for instance partition by employee_id and you have millions of employees, you'll end up having millions of directories in your file system. The term 'cardinality' refers to the number of possible value a field can have. For instance, if you have a 'country' field, the countries in the world are about 300, so cardinality would be ~300. For a field like 'timestamp_ms', which changes every millisecond, cardinality can be billions. In general, when choosing a field for partitioning, it should not have a high cardinality, because you'll end up with way too many directories in your file system.
Clustering aka bucketing on the other hand, will result with a fixed number of files, since you do specify the number of buckets. What hive will do is to take the field, calculate a hash and assign a record to that bucket. But what happens if you use let's say 256 buckets and the field you're bucketing on has a low cardinality (for instance, it's a US state, so can be only 50 different values) ? You'll have 50 buckets with data, and 206 buckets with no data.
Someone already mentioned how partitions can dramatically cut the amount of data you're querying. So in my example table, if you want to query only from a certain date forward, the partitioning by year/month/day is going to dramatically cut the amount of IO. I think that somebody also mentioned how bucketing can speed up joins with other tables that have exactly the same bucketing, so in my example, if you're joining two tables on the same employee_id, hive can do the join bucket by bucket (even better if they're already sorted by employee_id since it's going to mergesort parts that are already sorted, which works in linear time aka O(n) ).
So, bucketing works well when the field has high cardinality and data is evenly distributed among buckets. Partitioning works best when the cardinality of the partitioning field is not too high.
Also, you can partition on multiple fields, with an order (year/month/day is a good example), while you can bucket on only one field.
import time
current = time.time()
...job...
end = time.time()
diff = end - current
would that work for you?
The main question was to remove the CR/LF. Using the replace and char functions works for me:
Select replace(replace(Name,char(10),''),char(13),'')
For Postgres or Oracle SQL, use the CHR function instead:
replace(replace(Name,CHR(10),''),CHR(13),'')
If you have an array, a
of say 210 rows by 8 columns:
a = numpy.empty([210,8])
and want to add a ninth column of zeros you can do this:
b = numpy.append(a,numpy.zeros([len(a),1]),1)
I use the code provided by @Colin MacKenzie - III. Thanks a lot!
For someone who are looking for a replacement of 'deprecated' managedQuery:
1st, assuming using v4 support lib:
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
2nd:
your_(activity)_class implements LoaderManager.LoaderCallbacks<Cursor>
3rd,
// temporarily store the 'data.getData()' from onActivityResult
private Uri tmp_url;
4th, override callbacks:
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// create the loader here!
CursorLoader cursorLoader = new CursorLoader(this, tmp_url, null, null, null, null);
return cursorLoader;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
getContactInfo(cursor); // here it is!
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
5th:
public void initLoader(Uri data){
// will be used in onCreateLoader callback
this.tmp_url = data;
// 'this' is an Activity instance, implementing those callbacks
this.getSupportLoaderManager().initLoader(0, null, this);
}
6th, the code above, except that I change the signature param from Intent to Cursor:
protected void getContactInfo(Cursor cursor)
{
// Cursor cursor = managedQuery(intent.getData(), null, null, null, null);
while (cursor.moveToNext())
{
// same above ...
}
7th, call initLoader:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (PICK_CONTACT == requestCode) {
this.initLoader(data.getData(), this);
}
}
8th, don't forget this piece of code
Intent intentContact = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
this.act.startActivityForResult(intentContact, PICK_CONTACT);
References:
I accidentally encoded a file in UTF-7 and had a similar issue. When I typed file -i name.file
I would get charset=us-ascii
.
iconv -f us-ascii -t utf-9//translit name.file
would not work since I've gathered UTF-7 is a subset of US ASCII, as is UTF-8.
To solve this, I entered
iconv -f UTF-7 -t UTF-8//TRANSLIT name.file -o output.file
I'm not sure how to determine the encoding other than what others have suggested here.
Slightly modified from: Python Pandas Dataframe: Normalize data between 0.01 and 0.99? but from some of the comments thought it was relevant (sorry if considered a repost though...)
I wanted customized normalization in that regular percentile of datum or z-score was not adequate. Sometimes I knew what the feasible max and min of the population were, and therefore wanted to define it other than my sample, or a different midpoint, or whatever! This can often be useful for rescaling and normalizing data for neural nets where you may want all inputs between 0 and 1, but some of your data may need to be scaled in a more customized way... because percentiles and stdevs assumes your sample covers the population, but sometimes we know this isn't true. It was also very useful for me when visualizing data in heatmaps. So i built a custom function (used extra steps in the code here to make it as readable as possible):
def NormData(s,low='min',center='mid',hi='max',insideout=False,shrinkfactor=0.):
if low=='min':
low=min(s)
elif low=='abs':
low=max(abs(min(s)),abs(max(s)))*-1.#sign(min(s))
if hi=='max':
hi=max(s)
elif hi=='abs':
hi=max(abs(min(s)),abs(max(s)))*1.#sign(max(s))
if center=='mid':
center=(max(s)+min(s))/2
elif center=='avg':
center=mean(s)
elif center=='median':
center=median(s)
s2=[x-center for x in s]
hi=hi-center
low=low-center
center=0.
r=[]
for x in s2:
if x<low:
r.append(0.)
elif x>hi:
r.append(1.)
else:
if x>=center:
r.append((x-center)/(hi-center)*0.5+0.5)
else:
r.append((x-low)/(center-low)*0.5+0.)
if insideout==True:
ir=[(1.-abs(z-0.5)*2.) for z in r]
r=ir
rr =[x-(x-0.5)*shrinkfactor for x in r]
return rr
This will take in a pandas series, or even just a list and normalize it to your specified low, center, and high points. also there is a shrink factor! to allow you to scale down the data away from endpoints 0 and 1 (I had to do this when combining colormaps in matplotlib:Single pcolormesh with more than one colormap using Matplotlib) So you can likely see how the code works, but basically say you have values [-5,1,10] in a sample, but want to normalize based on a range of -7 to 7 (so anything above 7, our "10" is treated as a 7 effectively) with a midpoint of 2, but shrink it to fit a 256 RGB colormap:
#In[1]
NormData([-5,2,10],low=-7,center=1,hi=7,shrinkfactor=2./256)
#Out[1]
[0.1279296875, 0.5826822916666667, 0.99609375]
It can also turn your data inside out... this may seem odd, but I found it useful for heatmapping. Say you want a darker color for values closer to 0 rather than hi/low. You could heatmap based on normalized data where insideout=True:
#In[2]
NormData([-5,2,10],low=-7,center=1,hi=7,insideout=True,shrinkfactor=2./256)
#Out[2]
[0.251953125, 0.8307291666666666, 0.00390625]
So now "2" which is closest to the center, defined as "1" is the highest value.
Anyways, I thought my application was relevant if you're looking to rescale data in other ways that could have useful applications to you.
wget -S -i *file*
will get you the headers from each url in a file.
Filter though grep
for the status code specifically.
You can store the output of another query in a variable and latter you can use the same in your code:
set var=select count(*) from My_table;
${hiveconf:var};
In my case it was also with serialization. I need to add
[KnownType(typeof(...)]
for all the classes that could appear in the serialization.
Use a variable and call clearInterval
to stop it.
var interval;
$(document).on('ready',function()
interval = setInterval(updateDiv,3000);
});
function updateDiv(){
$.ajax({
url: 'getContent.php',
success: function(data){
$('.square').html(data);
},
error: function(){
$.playSound('oneday.wav');
$('.square').html('<span style="color:red">Connection problems</span>');
// I want to stop it here
clearInterval(interval);
}
});
}
Don't call write.close()
in writeToFile()
.
private void CreateShortcut(string executablePath, string name)
{
CMDexec("echo Set oWS = WScript.CreateObject('WScript.Shell') > CreateShortcut.vbs");
CMDexec("echo sLinkFile = '" + Environment.GetEnvironmentVariable("homedrive") + "\\users\\" + Environment.GetEnvironmentVariable("username") + "\\desktop\\" + name + ".ink' >> CreateShortcut.vbs");
CMDexec("echo Set oLink = oWS.CreateShortcut(sLinkFile) >> CreateShortcut.vbs");
CMDexec("echo oLink.TargetPath = '" + executablePath + "' >> CreateShortcut.vbs");
CMDexec("echo oLink.Save >> CreateShortcut.vbs");
CMDexec("cscript CreateShortcut.vbs");
CMDexec("del CreateShortcut.vbs");
}
Just single if conditions
<select name="category_type[]" id="category_type" class="select2 m-b-10 select2-multiple" style="width: 100%" multiple="multiple" data-placeholder="Choose" tooltip="Select Category Type">
@foreach ($categoryTypes as $categoryType)
<option value="{{ $categoryType->id }}"
**@if(in_array($categoryType->id,
request()->get('category_type')??[]))selected="selected"
@endif**>
{{ ucfirst($categoryType->title) }}</option>
@endforeach
</select>
Use of finalize() methods should be avoided. They are not a reliable mechanism for resource clean up and it is possible to cause problems in the garbage collector by abusing them.
If you require a deallocation call in your object, say to release resources, use an explicit method call. This convention can be seen in existing APIs (e.g. Closeable, Graphics.dispose(), Widget.dispose()) and is usually called via try/finally.
Resource r = new Resource();
try {
//work
} finally {
r.dispose();
}
Attempts to use a disposed object should throw a runtime exception (see IllegalStateException).
EDIT:
I was thinking, if all I did was just to dereference the data and wait for the garbage collector to collect them, wouldn't there be a memory leak if my user repeatedly entered data and pressed the reset button?
Generally, all you need to do is dereference the objects - at least, this is the way it is supposed to work. If you are worried about garbage collection, check out Java SE 6 HotSpot[tm] Virtual Machine Garbage Collection Tuning (or the equivalent document for your JVM version).
@doc_180 had the right concept, except he is focused on numbers, whereas the original poster had issues with strings.
The solution is to change the mx.rpc.xml.XMLEncoder
file. This is line 121:
if (content != null)
result += content;
(I looked at Flex 4.5.1 SDK; line numbers may differ in other versions.)
Basically, the validation fails because 'content is null' and therefore your argument is not added to the outgoing SOAP Packet; thus causing the missing parameter error.
You have to extend this class to remove the validation. Then there is a big snowball up the chain, modifying SOAPEncoder to use your modified XMLEncoder, and then modifying Operation to use your modified SOAPEncoder, and then moidfying WebService to use your alternate Operation class.
I spent a few hours on it, but I need to move on. It'll probably take a day or two.
You may be able to just fix the XMLEncoder line and do some monkey patching to use your own class.
I'll also add that if you switch to using RemoteObject/AMF with ColdFusion, the null is passed without problems.
11/16/2013 update:
I have one more recent addition to my last comment about RemoteObject/AMF. If you are using ColdFusion 10; then properties with a null value on an object are removed from the server-side object. So, you have to check for the properties existence before accessing it or you will get a runtime error.
Check like this:
<cfif (structKeyExists(arguments.myObject,'propertyName')>
<!--- no property code --->
<cfelse>
<!--- handle property normally --->
</cfif>
This is a change in behavior from ColdFusion 9; where the null properties would turn into empty strings.
Edit 12/6/2013
Since there was a question about how nulls are treated, here is a quick sample application to demonstrate how a string "null" will relate to the reserved word null.
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" initialize="application1_initializeHandler(event)">
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
protected function application1_initializeHandler(event:FlexEvent):void
{
var s :String = "null";
if(s != null){
trace('null string is not equal to null reserved word using the != condition');
} else {
trace('null string is equal to null reserved word using the != condition');
}
if(s == null){
trace('null string is equal to null reserved word using the == condition');
} else {
trace('null string is not equal to null reserved word using the == condition');
}
if(s === null){
trace('null string is equal to null reserved word using the === condition');
} else {
trace('null string is not equal to null reserved word using the === condition');
}
}
]]>
</fx:Script>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
</s:Application>
The trace output is:
null string is not equal to null reserved word using the != condition
null string is not equal to null reserved word using the == condition
null string is not equal to null reserved word using the === condition
I faced this problem a few days ago - the solution for me was to use .bind() to bind the required function to the dynamically created link.
var catLink = $('<a href="#" id="' + i + '" class="lnkCat">' + category.category + '</a>');
catLink.bind("click", function(){
$.categories.getSubCategories(this);
});
getSubCategories : function(obj) {
//do something
}
I hope this helps.
This is because of the proxy settings.
I also had the same problem, under which I could not use any of the modules which were fetching data from the internet.
There are simple steps to follow:
1. open the control panel
2. open internet options
3. under connection tab open LAN settings
4. go to advance settings and unmark everything, delete every proxy in there. Or u can just unmark the checkbox in proxy server this will also do the same
5. save all the settings by clicking ok.
you are done.
try to run the programme again, it must work
it worked for me at least
Some compilers have different sizes for int on different platforms (not C# specific)
Some coding standards (MISRA C) requires that all types used are size specified (i.e. Int32 and not int).
It is also good to specify prefixes for different type variables (e.g. b for 8 bit byte, w for 16 bit word, and l for 32 bit long word => Int32 lMyVariable)
You should care because it makes your code more portable and more maintainable.
Portable may not be applicable to C# if you are always going to use C# and the C# specification will never change in this regard.
Maintainable ihmo will always be applicable, because the person maintaining your code may not be aware of this particular C# specification, and miss a bug were the int occasionaly becomes more than 2147483647.
In a simple for-loop that counts for example the months of the year, you won't care, but when you use the variable in a context where it could possibly owerflow, you should care.
You should also care if you are going to do bit-wise operations on it.
A more general solution is the following extension, which works with Swift 2 & iOS 9:
extension Double {
/// Rounds the double to decimal places value
func roundToPlaces(places:Int) -> Double {
let divisor = pow(10.0, Double(places))
return round(self * divisor) / divisor
}
}
In Swift 3 round
is replaced by rounded
:
extension Double {
/// Rounds the double to decimal places value
func rounded(toPlaces places:Int) -> Double {
let divisor = pow(10.0, Double(places))
return (self * divisor).rounded() / divisor
}
}
Example which returns Double rounded to 4 decimal places:
let x = Double(0.123456789).roundToPlaces(4) // x becomes 0.1235 under Swift 2
let x = Double(0.123456789).rounded(toPlaces: 4) // Swift 3 version
conftest
solutionThe least invasive solution is adding an empty file named conftest.py
in the repo/
directory:
$ touch repo/conftest.py
That's it. No need to write custom code for mangling the sys.path
or remember to drag PYTHONPATH
along, or placing __init__.py
into dirs where it doesn't belong (using python -m pytest
as suggested in Apteryx's answer is a good solution though!).
The project directory afterwards:
repo
+-- conftest.py
+-- app.py
+-- settings.py
+-- models.py
+-- tests
+-- test_app.py
pytest
looks for the conftest
modules on test collection to gather custom hooks and fixtures, and in order to import the custom objects from them, pytest
adds the parent directory of the conftest.py
to the sys.path
(in this case the repo
directory).
If you have other project structure, place the conftest.py
in the package root dir (the one that contains packages but is not a package itself, so does not contain an __init__.py
), for example:
repo
+-- conftest.py
+-- spam
¦ +-- __init__.py
¦ +-- bacon.py
¦ +-- egg.py
+-- eggs
¦ +-- __init__.py
¦ +-- sausage.py
+-- tests
+-- test_bacon.py
+-- test_egg.py
src
layoutAlthough this approach can be used with the src
layout (place conftest.py
in the src
dir):
repo
+-- src
¦ +-- conftest.py
¦ +-- spam
¦ ¦ +-- __init__.py
¦ ¦ +-- bacon.py
¦ ¦ +-- egg.py
¦ +-- eggs
¦ +-- __init__.py
¦ +-- sausage.py
+-- tests
+-- test_bacon.py
+-- test_egg.py
beware that adding src
to PYTHONPATH
mitigates the meaning and benefits of the src
layout! You will end up with testing the code from repository and not the installed package. If you need to do it, maybe you don't need the src
dir at all.
Of course, conftest
modules are not just some files to help the source code discovery; it's where all the project-specific enhancements of the pytest
framework and the customization of your test suite happen. pytest
has a lot of information on conftest
modules scattered throughout their docs; start with conftest.py
: local per-directory plugins
Also, SO has an excellent question on conftest
modules: In py.test, what is the use of conftest.py files?
Use sed's substitution: sed 's/"//g'
s/X/Y/
replaces X with Y.
g
means all occurrences should be replaced, not just the first one.
You can reset settings for eclipse by deleting .metadata folder from your current workspace.
This will however remove all projects from your project explorer NOT workspace. So dont worry your projects have not gone anywhere.
You can import projects from your workspace like this : just make sure that you uncheck "Copy project into workspace".
You can't follow the cursor with a DIV
, but you can draw a DIV
when moving the cursor!
$(document).on('mousemove', function(e){
$('#your_div_id').css({
left: e.pageX,
top: e.pageY
});
});
That div must be off the float, so position: absolute
should be set.
Outstream is not closed ... close the stream so that response goes back to test client. Hope this helps.
Your function would work like this:
CREATE OR REPLACE FUNCTION prc_tst_bulk(sql text)
RETURNS TABLE (name text, rowcount integer) AS
$$
BEGIN
RETURN QUERY EXECUTE '
WITH v_tb_person AS (' || sql || $x$)
SELECT name, count(*)::int FROM v_tb_person WHERE nome LIKE '%a%' GROUP BY name
UNION
SELECT name, count(*)::int FROM v_tb_person WHERE gender = 1 GROUP BY name$x$;
END
$$ LANGUAGE plpgsql;
Call:
SELECT * FROM prc_tst_bulk($$SELECT a AS name, b AS nome, c AS gender FROM tbl$$)
You cannot mix plain and dynamic SQL the way you tried to do it. The whole statement is either all dynamic or all plain SQL. So I am building one dynamic statement to make this work. You may be interested in the chapter about executing dynamic commands in the manual.
The aggregate function count()
returns bigint
, but you had rowcount
defined as integer
, so you need an explicit cast ::int
to make this work
I use dollar quoting to avoid quoting hell.
However, is this supposed to be a honeypot for SQL injection attacks or are you seriously going to use it? For your very private and secure use, it might be ok-ish - though I wouldn't even trust myself with a function like that. If there is any possible access for untrusted users, such a function is a loaded footgun. It's impossible to make this secure.
Craig (a sworn enemy of SQL injection!) might get a light stroke, when he sees what you forged from his piece of code in the answer to your preceding question. :)
The query itself seems rather odd, btw. But that's beside the point here.
I don't think there's any one right answer to this question, but my advice would be to stick with SWT unless you are encountering severe limitations that require such a massive overhaul.
Also, SWT is actually newer and more actively maintained than Swing. (It was originally developed as a replacement for Swing using native components).
The best solution is onsubmit call any function whatever you want and return false after it.
onsubmit="xxx_xxx(); return false;"
By default, Valgrind writes its output to stderr. So you need to do something like:
valgrind a.out > log.txt 2>&1
Alternatively, you can tell Valgrind to write somewhere else; see http://valgrind.org/docs/manual/manual-core.html#manual-core.comment (but I've never tried this).
This command brew install maven30
didn't work for me. Was complaining about a missing FORMULA. But the following command did work. I've got maven-3.0.5 installed.
brew install homebrew/versions/maven30
This is for Mac OS X 10.9 aka Mavericks.
I was facing the same issue, I was adding
"types": ["node"]
to tsconfig.json of root folder.
There was one more tsconfig.app.json under src folder and I got solved this by adding
"types": ["node"]
to tsconfig.app.json file under compilerOptions
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"types": ["node"] ----------------------< added node to the array
},
"exclude": [
"test.ts",
"**/*.spec.ts"
]
}
$("#myinput").attr('type') == 'checkbox'
You can use a real like in Link to Entities quite easily
Add
<Function Name="String_Like" ReturnType="Edm.Boolean">
<Parameter Name="searchingIn" Type="Edm.String" />
<Parameter Name="lookingFor" Type="Edm.String" />
<DefiningExpression>
searchingIn LIKE lookingFor
</DefiningExpression>
</Function>
to your EDMX in this tag:
edmx:Edmx/edmx:Runtime/edmx:ConceptualModels/Schema
Also remember the namespace in the <schema namespace="" />
attribute
Then add an extension class in the above namespace:
public static class Extensions
{
[EdmFunction("DocTrails3.Net.Database.Models", "String_Like")]
public static Boolean Like(this String searchingIn, String lookingFor)
{
throw new Exception("Not implemented");
}
}
This extension method will now map to the EDMX function.
More info here: http://jendaperl.blogspot.be/2011/02/like-in-linq-to-entities.html
To install the GPL version of PyQt5, run (see PyQt5 Project):
pip3 install pyqt5
This will install the Python wheel for your platform and your version of Python (assuming both are supported).
(The wheel will be automatically downloaded from the Python Package Index.)
The PyQt5 wheel includes the necessary parts of the LGPL version of Qt. There is no need to install Qt yourself.
(The required sip
is packaged as a separate wheel and will be downloaded and installed automatically.)
Note:
If you get an error message saying something as
No downloads could be found that satisfy the requirement
then you are probably using an unsupported version of Python.
You can use git-del-br
tool.
git-del-br -a
You can install it via pip
using
pip install git-del-br
P.S: I am the author of the tool. Any suggestions/feedback are welcome.
Try this method for uploading Image file from camera
package com.example.imageupload;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.message.BasicHeader;
public class MultipartEntity implements HttpEntity {
private String boundary = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean isSetLast = false;
boolean isSetFirst = false;
public MultipartEntity() {
this.boundary = System.currentTimeMillis() + "";
}
public void writeFirstBoundaryIfNeeds() {
if (!isSetFirst) {
try {
out.write(("--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
}
}
isSetFirst = true;
}
public void writeLastBoundaryIfNeeds() {
if (isSetLast) {
return;
}
try {
out.write(("\r\n--" + boundary + "--\r\n").getBytes());
} catch (final IOException e) {
}
isSetLast = true;
}
public void addPart(final String key, final String value) {
writeFirstBoundaryIfNeeds();
try {
out.write(("Content-Disposition: form-data; name=\"" + key + "\"\r\n")
.getBytes());
out.write("Content-Type: text/plain; charset=UTF-8\r\n".getBytes());
out.write("Content-Transfer-Encoding: 8bit\r\n\r\n".getBytes());
out.write(value.getBytes());
out.write(("\r\n--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
}
}
public void addPart(final String key, final String fileName,
final InputStream fin) {
addPart(key, fileName, fin, "application/octet-stream");
}
public void addPart(final String key, final String fileName,
final InputStream fin, String type) {
writeFirstBoundaryIfNeeds();
try {
type = "Content-Type: " + type + "\r\n";
out.write(("Content-Disposition: form-data; name=\"" + key
+ "\"; filename=\"" + fileName + "\"\r\n").getBytes());
out.write(type.getBytes());
out.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes());
final byte[] tmp = new byte[4096];
int l = 0;
while ((l = fin.read(tmp)) != -1) {
out.write(tmp, 0, l);
}
out.flush();
} catch (final IOException e) {
} finally {
try {
fin.close();
} catch (final IOException e) {
}
}
}
public void addPart(final String key, final File value) {
try {
addPart(key, value.getName(), new FileInputStream(value));
} catch (final FileNotFoundException e) {
}
}
public long getContentLength() {
writeLastBoundaryIfNeeds();
return out.toByteArray().length;
}
public Header getContentType() {
return new BasicHeader("Content-Type", "multipart/form-data; boundary="
+ boundary);
}
public boolean isChunked() {
return false;
}
public boolean isRepeatable() {
return false;
}
public boolean isStreaming() {
return false;
}
public void writeTo(final OutputStream outstream) throws IOException {
outstream.write(out.toByteArray());
}
public Header getContentEncoding() {
return null;
}
public void consumeContent() throws IOException,
UnsupportedOperationException {
if (isStreaming()) {
throw new UnsupportedOperationException(
"Streaming entity does not implement #consumeContent()");
}
}
public InputStream getContent() throws IOException,
UnsupportedOperationException {
return new ByteArrayInputStream(out.toByteArray());
}
}
Use of class for uploading
private void doFileUpload(File file_path) {
Log.d("Uri", "Do file path" + file_path);
try {
HttpClient client = new DefaultHttpClient();
//use your server path of php file
HttpPost post = new HttpPost(ServerUploadPath);
Log.d("ServerPath", "Path" + ServerUploadPath);
FileBody bin1 = new FileBody(file_path);
Log.d("Enter", "Filebody complete " + bin1);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("uploaded_file", bin1);
reqEntity.addPart("email", new StringBody(useremail));
post.setEntity(reqEntity);
Log.d("Enter", "Image send complete");
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
Log.d("Enter", "Get Response");
try {
final String response_str = EntityUtils.toString(resEntity);
if (resEntity != null) {
Log.i("RESPONSE", response_str);
JSONObject jobj = new JSONObject(response_str);
result = jobj.getString("ResponseCode");
Log.e("Result", "...." + result);
}
} catch (Exception ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
} catch (Exception e) {
Log.e("Upload Exception", "");
e.printStackTrace();
}
}
Service for uploading
<?php
$image_name = $_FILES["uploaded_file"]["name"];
$tmp_arr = explode(".",$image_name);
$img_extn = end($tmp_arr);
$new_image_name = 'image_'. uniqid() .'.'.$img_extn;
$flag=0;
if (file_exists("Images/".$new_image_name))
{
$msg=$new_image_name . " already exists."
header('Content-type: application/json');
echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=>$msg));
}else{
move_uploaded_file($_FILES["uploaded_file"]["tmp_name"],"Images/". $new_image_name);
$flag = 1;
}
if($flag == 1){
require 'db.php';
$static_url =$new_image_name;
$conn=mysql_connect($db_host,$db_username,$db_password) or die("unable to connect localhost".mysql_error());
$db=mysql_select_db($db_database,$conn) or die("unable to select message_app");
$email = "";
if((isset($_REQUEST['email'])))
{
$email = $_REQUEST['email'];
}
$sql ="insert into alert(images) values('$static_url')";
$result=mysql_query($sql);
if($result){
echo json_encode(array("ResponseCode"=>"1","ResponseMsg"=> "Insert data successfully.","Result"=>"True","ImageName"=>$static_url,"email"=>$email));
} else
{
echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=> "Could not insert data.","Result"=>"False","email"=>$email));
}
}
else{
echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=> "Erroe While Inserting Image.","Result"=>"False"));
}
?>
I fixed this problem using apt-cyg (a great installer similar to apt-get) to easily download the ca-certificates (including Git and many more):
apt-cyg install ca-certificates
Note: apt-cyg should be first installed. You can do this from Windows command line:
cd c:\cygwin
setup.exe -q -P wget,tar,qawk,bzip2,subversion,vim
Close Windows cmd, and open Cygwin Bash:
wget rawgit.com/transcode-open/apt-cyg/master/apt-cyg
install apt-cyg /bin
I made this simple Notification wrapper. It works on Chrome, Safari and Firefox.
Probably on Opera, IE and Edge as well but I haven't tested it yet.
Just get the notify.js file from here https://github.com/gravmatt/js-notify and put it into your page.
Get it on Bower
$ bower install js-notify
This is how it works:
notify('title', {
body: 'Notification Text',
icon: 'path/to/image.png',
onclick: function(e) {}, // e -> Notification object
onclose: function(e) {},
ondenied: function(e) {}
});
You have to set the title but the json object as the second argument is optional.
Use the modern version of the Fisher–Yates shuffle algorithm:
/**
* Shuffles array in place.
* @param {Array} a items An array containing the items.
*/
function shuffle(a) {
var j, x, i;
for (i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = a[i];
a[i] = a[j];
a[j] = x;
}
return a;
}
/**
* Shuffles array in place. ES6 version
* @param {Array} a items An array containing the items.
*/
function shuffle(a) {
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
Note however, that swapping variables with destructuring assignment causes significant performance loss, as of October 2017.
var myArray = ['1','2','3','4','5','6','7','8','9'];
shuffle(myArray);
Using Object.defineProperty
(method taken from this SO answer) we can also implement this function as a prototype method for arrays, without having it show up in loops such as for (i in arr)
. The following will allow you to call arr.shuffle()
to shuffle the array arr
:
Object.defineProperty(Array.prototype, 'shuffle', {
value: function() {
for (let i = this.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[this[i], this[j]] = [this[j], this[i]];
}
return this;
}
});
I was able to get @yeeking example to work by not using FormData but using javascript object to transfer the blob. Works with a sound blob created using recorder.js. Tested in Chrome version 32.0.1700.107
function uploadAudio( blob ) {
var reader = new FileReader();
reader.onload = function(event){
var fd = {};
fd["fname"] = "test.wav";
fd["data"] = event.target.result;
$.ajax({
type: 'POST',
url: 'upload.php',
data: fd,
dataType: 'text'
}).done(function(data) {
console.log(data);
});
};
reader.readAsDataURL(blob);
}
Contents of upload.php
<?
// pull the raw binary data from the POST array
$data = substr($_POST['data'], strpos($_POST['data'], ",") + 1);
// decode it
$decodedData = base64_decode($data);
// print out the raw data,
$filename = $_POST['fname'];
echo $filename;
// write the data out to the file
$fp = fopen($filename, 'wb');
fwrite($fp, $decodedData);
fclose($fp);
?>
Creating colnames with iterating
df = pd.DataFrame(columns=['colname_' + str(i) for i in range(5)])
print(df)
# Empty DataFrame
# Columns: [colname_0, colname_1, colname_2, colname_3, colname_4]
# Index: []
to_html()
operations
print(df.to_html())
# <table border="1" class="dataframe">
# <thead>
# <tr style="text-align: right;">
# <th></th>
# <th>colname_0</th>
# <th>colname_1</th>
# <th>colname_2</th>
# <th>colname_3</th>
# <th>colname_4</th>
# </tr>
# </thead>
# <tbody>
# </tbody>
# </table>
this seems working
print(type(df.to_html()))
# <class 'str'>
when you create df like this
df = pd.DataFrame(columns=COLUMN_NAMES)
it has 0 rows × n columns
, you need to create at least one row index by
df = pd.DataFrame(columns=COLUMN_NAMES, index=[0])
now it has 1 rows × n columns
. You are be able to add data. Otherwise its df that only consist colnames object(like a string list).
I think it depends on the compiler and is hard to give a general answer.
You can also use inline assembly like this:
int i;
__asm {
mov eax, 00000000000000000000000000000000b
mov i, eax
}
std::cout << i;
Okay, it might be somewhat overkill, but it works.
Jquery has trim() function which basically turns something like this " FOo Bar " into "FOo Bar".
var string = " My String with Multiple lines ";
string.trim(); // output "My String with Multiple lines"
It is much more usefull because it is automatically removes empty spaces at the beginning and at the end of string as well. No regex needed.
Why not just use the literal characters?
fig.gca().set_xlabel("wavelength, (Å)")
fig.gca().set_ylabel("?")
You might have to add this to the file if you are using python 2:
# -*- coding: utf-8 -*-
from __future__ import unicode literals # or use u"unicode strings"
It might be easier to define constants for characters that are not easy to type on your keyboard.
ANGSTROM, LAMDBA = "Å?"
Then you can reuse them elsewhere.
fig.gca().set_xlabel("wavelength, (%s)" % ANGSTROM)
fig.gca().set_ylabel(LAMBDA)
Your code has lots of errors.
dm$Day
and dm$day
. Probably not the same thingDate
and Visits
. So you would access them (I'm guessing) as dm$Date
and dm$Visits
%Y-%m-%d
this should be %m/%d/%Y
The following code should plot what you want:
dm$newday = as.Date(dm$Date, "%m/%d/%Y")
plot(dm$newday, dm$Visits)
I am going to Necro this topic.
Starting around ms-access-2016, you can execute Data Definition Queries (DDQ) through Macro's
ALTER TABLE <Table> ALTER COLUMN <ID_Field> COUNTER(1,1);
Open Query
actionQuery Name
field; View
and Data Mode
settings are not relevant and can leave the default valuesYou can do this easily manually for each column like this:
df['A_perc'] = df['A']/df['sum']
If you want to do this in one step for all columns, you can use the div
method (http://pandas.pydata.org/pandas-docs/stable/basics.html#matching-broadcasting-behavior):
ds.div(ds['sum'], axis=0)
And if you want this in one step added to the same dataframe:
>>> ds.join(ds.div(ds['sum'], axis=0), rsuffix='_perc')
A B C D sum A_perc B_perc \
1 0.151722 0.935917 1.033526 0.941962 3.063127 0.049532 0.305543
2 0.033761 1.087302 1.110695 1.401260 3.633017 0.009293 0.299283
3 0.761368 0.484268 0.026837 1.276130 2.548603 0.298739 0.190013
C_perc D_perc sum_perc
1 0.337409 0.307517 1
2 0.305722 0.385701 1
3 0.010530 0.500718 1
You should try removing the following code from your fragments
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
The interface/listener is a default created so that your activity and fragments can communicate easier
Use the retainAll()
method of Set
:
Set<String> s1;
Set<String> s2;
s1.retainAll(s2); // s1 now contains only elements in both sets
If you want to preserve the sets, create a new set to hold the intersection:
Set<String> intersection = new HashSet<String>(s1); // use the copy constructor
intersection.retainAll(s2);
The javadoc of retainAll()
says it's exactly what you want:
Retains only the elements in this set that are contained in the specified collection (optional operation). In other words, removes from this set all of its elements that are not contained in the specified collection. If the specified collection is also a set, this operation effectively modifies this set so that its value is the intersection of the two sets.
Use match
to return your desired vector, then cbind
it to your matrix
cbind(t, z[, "symbol"][match(rownames(t), rownames(z))])
[,1] [,2] [,3] [,4]
GO.ID "GO:0002009" "GO:0030334" "GO:0015674" NA
LEVEL "8" "6" "7" NA
Annotated "342" "343" "350" NA
Significant "1" "1" "1" NA
Expected "0.07" "0.07" "0.07" NA
resultFisher "0.679" "0.065" "0.065" NA
ILMN_1652464 "0" "0" "1" "PLAC8"
ILMN_1651838 "0" "0" "0" "RND1"
ILMN_1711311 "1" "1" "0" NA
ILMN_1653026 "0" "0" "0" "GRA"
PS. Be warned that t
is base R function that is used to transpose matrices. By creating a variable called t, it can lead to confusion in your downstream code.
http://incubator.apache.org/hama/ is a distributed scientific package on Hadoop for massive matrix and graph data.
There is no need to include a bulky library such as Moment.js to fix such a simple issue.
The issue you are facing is not with formatting, but with parsing.
As John Shammas mentions in another answer, the Date
constructor (and Date.parse
) are picky about the input. Your 2016-01-04 10:34:23
may work in one JavaScript implementation, but not necessarily in the other.
According to the specification of ECMAScript 5.1, Date.parse
supports (a simplification of) ISO 8601. That's good news, because your date is already very ISO 8601-like.
All you have to do is change the input format just a little. Swap the space for a T
: 2016-01-04T10:34:23
; and optionally add a time zone (2016-01-04T10:34:23+01:00
), otherwise UTC is assumed.
The Linq extension method Any could work for you...
buildingStatus.Any(item => item.GetCharValue() == v.Status)
DECLARE @start [datetime] = 2010/4/1;
Should be...
DECLARE @start [datetime] = '2010-04-01';
The one you have is dividing 2010 by 4, then by 1, then converting to a date. Which is the 57.5th day from 1900-01-01.
Try SELECT @start
after your initialisation to check if this is correct.
Instead of manually adding a line break somehow, you can do implement border-bottom: 1px solid #ff0000
which will take the element's border and only render border-<side>
of whichever side you specify.
This could be done in newer versions of selenium in JS( but all supporting stalenessOf will work):
const { until } = require('selenium-webdriver');
driver.wait(
until.stalenessOf(
driver.findElement(
By.css(SQLQueriesByPhpMyAdminSelectors.sqlQueryArea)
)
),
5 * 1000
)
.then( driver.findElement(By.css(SQLQueriesByPhpMyAdminSelectors.sqlQueryArea))
.sendKeys(sqlString)
);
Making your queryable lists to .ToList() and it should work fine.
Same thing happened to me. Eventually my solution was to navigate to the repository using terminal (on mac) and create a new js file with a slightly different name. It linked immediately so i copied contents of original file to new one. You also might want to lose the first /
after src=
and use ""
.
As indicated here https://stackoverflow.com/a/1632004/330867, you can implement it by "filtering" what is originating the exit of this page.
As mentionned in the comments, here's a new version of the code in the other question, which also include the ajax request you make in your question :
var canExit = true;
// For every function that will call an ajax query, you need to set the var "canExit" to false, then set it to false once the ajax is finished.
function checkCart() {
canExit = false;
$.ajax({
url : 'index.php?route=module/cart/check',
type : 'POST',
dataType : 'json',
success : function (result) {
if (result) {
canExit = true;
}
}
})
}
$(document).on('click', 'a', function() {canExit = true;}); // can exit if it's a link
$(window).on('beforeunload', function() {
if (canExit) return null; // null will allow exit without a question
// Else, just return the message you want to display
return "Do you really want to close?";
});
Important: You shouldn't have a global variable defined (here canExit
), this is here for simpler version.
Note that you can't override completely the confirm message (at least in chrome). The message you return will only be prepended to the one given by Chrome. Here's the reason : How can I override the OnBeforeUnload dialog and replace it with my own?
Chances are that you've not included the header file that declares system()
.
In order to be able to compile C++ code that uses functions which you don't (manually) declare yourself, you have to pull in the declarations. These declarations are normally stored in so-called header files that you pull into the current translation unit using the #include
preprocessor directive. As the code does not #include
the header file in which system()
is declared, the compilation fails.
To fix this issue, find out which header file provides you with the declaration of system()
and include that. As mentioned in several other answers, you most likely want to add #include <cstdlib>
I really like @Angelin's answer. But if you're dealing with some legacy code where this is not practical, this technique might work for you.
At the top of the file
// Protect against resubmits
if (empty($_POST)) {
$_POST['last_pos_sub'] = time();
} else {
if (isset($_POST['last_pos_sub'])){
if ($_POST['last_pos_sub'] == $_SESSION['curr_pos_sub']) {
redirect back to the file so POST data is not preserved
}
$_SESSION['curr_pos_sub'] = $_POST['last_pos_sub'];
}
}
Then at the end of the form, stick in last_pos_sub
as follows:
<input type="hidden" name="last_pos_sub" value=<?php echo $_POST['last_pos_sub']; ?>>
As mentioned above, N4113 is the final solution to this matter, but we'll have to wait more than a year to see it coming out.
Meanwhile, if you want such feature, you'll need to resort to "simple" templates and some preprocessor magic.
template<typename T>
class Enum final
{
const char* m_name;
const T m_value;
static T m_counter;
public:
Enum(const char* str, T init = m_counter) : m_name(str), m_value(init) {m_counter = (init + 1);}
const T value() const {return m_value;}
const char* name() const {return m_name;}
};
template<typename T>
T Enum<T>::m_counter = 0;
#define ENUM_TYPE(x) using Enum = Enum<x>;
#define ENUM_DECL(x,...) x(#x,##__VA_ARGS__)
#define ENUM(...) const Enum ENUM_DECL(__VA_ARGS__);
#include <iostream>
//the initialization order should be correct in all scenarios
namespace Level
{
ENUM_TYPE(std::uint8)
ENUM(OFF)
ENUM(SEVERE)
ENUM(WARNING)
ENUM(INFO, 10)
ENUM(DEBUG)
ENUM(ALL)
}
namespace Example
{
ENUM_TYPE(long)
ENUM(A)
ENUM(B)
ENUM(C, 20)
ENUM(D)
ENUM(E)
ENUM(F)
}
int main(int argc, char** argv)
{
Level::Enum lvl = Level::WARNING;
Example::Enum ex = Example::C;
std::cout << lvl.value() << std::endl; //2
std::cout << ex.value() << std::endl; //20
}
Enum<T>::m_counter
is set to 0 inside each namespace declaration.
(Could someone point me out where ^^this behaviour^^ is mentioned on the standard?)
The preprocessor magic automates the declaration of enumerators.
enum
type, therefore not promotable to intThis one sacrifices line numbering (not really) but can be used on switch cases.
#define ENUM_TYPE(x) using type = Enum<x>
#define ENUM(x) constexpr type x{__LINE__,#x}
template<typename T>
struct Enum final
{
const T value;
const char* name;
constexpr operator const T() const noexcept {return value;}
constexpr const char* operator&() const noexcept {return name;}
};
#line 0
conflicts with -pedantic
on GCC and clang.
Either start at #line 1
and subtract 1 from __LINE__
.
Or, don't use -pedantic
.
And while we're at it, avoid VC++ at all costs, it has always been a joke of a compiler.
#include <iostream>
namespace Level
{
ENUM_TYPE(short);
#line 0
ENUM(OFF);
ENUM(SEVERE);
ENUM(WARNING);
#line 10
ENUM(INFO);
ENUM(DEBUG);
ENUM(ALL);
#line <next line number> //restore the line numbering
};
int main(int argc, char** argv)
{
std::cout << Level::OFF << std::endl; // 0
std::cout << &Level::OFF << std::endl; // OFF
std::cout << Level::INFO << std::endl; // 10
std::cout << &Level::INFO << std::endl; // INFO
switch(/* any integer or integer-convertible type */)
{
case Level::OFF:
//...
break;
case Level::SEVERE:
//...
break;
//...
}
return 0;
}
r3dVoxel - Enum
r3dVoxel - ELoggingLevel
You have to write as
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
Make sure you have jstl-1.0 & standard.jar BOTH files are placed in a classpath
As other people have mentioned, this issue is common when using adblock or similar extensions.
The source of my issues was my Privacy Badger extension.
You can use the ThenBy and ThenByDescending extension methods:
foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)
This has worked for me in both SQL Server 2005 and 2008:
SELECT * from TABLE
WHERE FIELDNAME > {ts '2013-02-01 15:00:00.001'}
AND FIELDNAME < {ts '2013-08-05 00:00:00.000'}
There is a very easy way to customize Bootstrap:
mysqli is provided by php-mysql-5.3.3-40.el6_6.x86_64
You may need to try the following
yum install php-mysql-5.3.3-40.el6_6.x86_64
In Word, it is possible to paste code that uses color to differentiate comments from code using "Paste Keep Source Formatting." However, if you use the pasted code to create a new style, Word automatically strips the color coded text and changes them to be black (or whatever the auto default color is). Since applying a style is the best way to ensure compliance with document format requirements, Word is not very useful for documenting software programs. Unfortunately, I don't recall Open Office being any better. The best work-around is to use the default simple text box.
Extension of Mumthezir's version that works better on iOS, based on Mathijs Segers' comment:
(Uses some AngularJS but hopefully you get the idea.)
<label style='position:relative'>
<input type="date"
name="dateField"
onfocus="(this.type='date')"
ng-focus="dateFocus=true" ng-blur="dateFocus=false" />
<span ng-if='!dateFocus && !form.date' class='date-placeholder'>
Enter date
</span>
</label>
Because it's all wrapped in a label
, clicking the span
automatically focuses the input
.
CSS:
.date-placeholder {
display: inline-block;
position: absolute;
text-align: left;
color: #aaa;
background-color: white;
cursor: text;
/* Customize this stuff based on your styles */
top: 4px;
left: 4px;
right: 4px;
bottom: 4px;
line-height: 32px;
padding-left: 12px;
}
Try :
<template>
<th :class="'initial '+ active" v-on="click: myFilter">
<span class="wkday">M</span>
</th>
</template>
<script lang="ts">
active:string=''
myFilter(){
this.active='active'
}
</script>
<style>
.active{
/***your action***/
}
</style>
Just to update the answer by parag and SpK to align with current SDK backward compatibility from deprecated methods:
int Measuredwidth = 0;
int Measuredheight = 0;
Point size = new Point();
WindowManager w = getWindowManager();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
w.getDefaultDisplay().getSize(size);
Measuredwidth = size.x;
Measuredheight = size.y;
}else{
Display d = w.getDefaultDisplay();
Measuredwidth = d.getWidth();
Measuredheight = d.getHeight();
}
% mysql --user=root mysql
CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' WITH GRANT OPTION;
CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' WITH GRANT OPTION;
CREATE USER 'admin'@'localhost';
GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
CREATE USER 'dummy'@'localhost';
FLUSH PRIVILEGES;
One difference is that the variables that you declare in the function are local, so they go away when you exit the function and they don't conflict with other variables in other or same code.
To read a line from a file, you should use the fgets
function: It reads a string from the specified file up to either a newline character or EOF
.
The use of sscanf
in your code would not work at all, as you use filename
as your format string for reading from line
into a constant string literal %s
.
The reason for SEGV is that you write into the non-allocated memory pointed to by line
.
you must write it in SQL not it C/PHP style
IF( action = 2 AND state = 0, 1, 0 ) AS state
for use in query
IF ( action = 2 AND state = 0 ) THEN SET state = 1
for use in stored procedures or functions
The zenity application appears to be what you are looking for.
To take input from zenity, you can specify a variable and have the output of zenity --entry saved to it. It looks something like this:
my_variable=$(zenity --entry)
If you look at the value in my_variable now, it will be whatever was typed in the zenity pop up entry dialog.
If you want to give some sort of prompt as to what the user (or you) should enter in the dialog, add the --text switch with the label that you want. It looks something like this:
my_variable=$(zenity --entry --text="What's my variable:")
Zenity has lot of other nice options that are for specific tasks, so you might want to check those out as well with zenity --help. One example is the --calendar option that let's you select a date from a graphical calendar.
my_date=$(zenity --calendar)
Which gives a nicely formatted date based on what the user clicked on:
echo ${my_date}
gives:
08/05/2009
There are also options for slider selectors, errors, lists and so on.
Hope this helps.
Finally in .NET 4.5, the CLR allows one to hint/suggest1 method inlining using MethodImplOptions.AggressiveInlining
value. It is also available in the Mono's trunk (committed today).
// The full attribute usage is in mscorlib.dll,
// so should not need to include extra references
using System.Runtime.CompilerServices;
...
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void MyMethod(...)
1. Previously "force" was used here. Since there were a few downvotes, I'll try to clarify the term. As in the comments and the documentation, The method should be inlined if possible.
Especially considering Mono (which is open), there are some mono-specific technical limitations considering inlining or more general one (like virtual functions). Overall, yes, this is a hint to compiler, but I guess that is what was asked for.
This is the tutorial I used to get to darrinm's answer. It's updated for ios5/6 and really easy. When I'm popular enough I'll delete this and add it as a comment to his answer.
http://www.raywenderlich.com/5492/working-with-json-in-ios-5
http://www.touch-code-magazine.com/tutorial-fetch-and-parse-json-in-ios6/
AUTO_INCREMENT
is part of the column's datatype, you have to define the complete datatype for the column again:
ALTER TABLE document
ALTER COLUMN document_id int AUTO_INCREMENT
(int
taken as an example, you should set it to the type the column had before)
The typical solution is to define the shape and use it as background but as the number of digits varies it's no more a perfect circle, it looks like a rectangle with round edges or Oval. So I have developed this solution, it's working great. Hope it will help someone.
Here is the code of custom TextView
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.TextView;
public class CircularTextView extends TextView
{
private float strokeWidth;
int strokeColor,solidColor;
public CircularTextView(Context context) {
super(context);
}
public CircularTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CircularTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public void draw(Canvas canvas) {
Paint circlePaint = new Paint();
circlePaint.setColor(solidColor);
circlePaint.setFlags(Paint.ANTI_ALIAS_FLAG);
Paint strokePaint = new Paint();
strokePaint.setColor(strokeColor);
strokePaint.setFlags(Paint.ANTI_ALIAS_FLAG);
int h = this.getHeight();
int w = this.getWidth();
int diameter = ((h > w) ? h : w);
int radius = diameter/2;
this.setHeight(diameter);
this.setWidth(diameter);
canvas.drawCircle(diameter / 2 , diameter / 2, radius, strokePaint);
canvas.drawCircle(diameter / 2, diameter / 2, radius-strokeWidth, circlePaint);
super.draw(canvas);
}
public void setStrokeWidth(int dp)
{
float scale = getContext().getResources().getDisplayMetrics().density;
strokeWidth = dp*scale;
}
public void setStrokeColor(String color)
{
strokeColor = Color.parseColor(color);
}
public void setSolidColor(String color)
{
solidColor = Color.parseColor(color);
}
}
Then in your XML, give some padding and make sure its gravity is center
<com.app.tot.customtextview.CircularTextView
android:id="@+id/circularTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="11"
android:gravity="center"
android:padding="3dp"/>
And you can set the stroke width
circularTextView.setStrokeWidth(1);
circularTextView.setStrokeColor("#ffffff");
circularTextView.setSolidColor("#000000");
SELECT LEFT(CONVERT(varchar, GetDate(),112),6)
This is the command that you need to execute on the mirror:
git remote update
Fiddled around with the Bakudan's code and other code in stackoverflow to get everything in one.
Update #1 : Added more options. Now Start, pause, resume, reset and restart. Mix the functions to get desired results.
Update #2 : Edited out previously used JQuery codes for pure JS and added as code snippet.
For previous Jquery based fiddle version : https://jsfiddle.net/wizajay/rro5pna3/305/
var Clock = {_x000D_
totalSeconds: 0,_x000D_
start: function () {_x000D_
if (!this.interval) {_x000D_
var self = this;_x000D_
function pad(val) { return val > 9 ? val : "0" + val; }_x000D_
this.interval = setInterval(function () {_x000D_
self.totalSeconds += 1;_x000D_
_x000D_
document.getElementById("min").innerHTML = pad(Math.floor(self.totalSeconds / 60 % 60));_x000D_
document.getElementById("sec").innerHTML = pad(parseInt(self.totalSeconds % 60));_x000D_
}, 1000);_x000D_
}_x000D_
},_x000D_
_x000D_
reset: function () {_x000D_
Clock.totalSeconds = null; _x000D_
clearInterval(this.interval);_x000D_
document.getElementById("min").innerHTML = "00";_x000D_
document.getElementById("sec").innerHTML = "00";_x000D_
delete this.interval;_x000D_
},_x000D_
pause: function () {_x000D_
clearInterval(this.interval);_x000D_
delete this.interval;_x000D_
},_x000D_
_x000D_
resume: function () {_x000D_
this.start();_x000D_
},_x000D_
_x000D_
restart: function () {_x000D_
this.reset();_x000D_
Clock.start();_x000D_
}_x000D_
};_x000D_
_x000D_
_x000D_
document.getElementById("startButton").addEventListener("click", function () { Clock.start(); });_x000D_
document.getElementById("pauseButton").addEventListener("click", function () { Clock.pause(); });_x000D_
document.getElementById("resumeButton").addEventListener("click", function () { Clock.resume(); });_x000D_
document.getElementById("resetButton").addEventListener("click", function () { Clock.reset(); });_x000D_
document.getElementById("restartButton").addEventListener("click", function () { Clock.restart(); });
_x000D_
<span id="min">00</span>:<span id="sec">00</span>_x000D_
_x000D_
<input id="startButton" type="button" value="Start">_x000D_
<input id="pauseButton" type="button" value="Pause">_x000D_
<input id="resumeButton" type="button" value="Resume">_x000D_
<input id="resetButton" type="button" value="Reset">_x000D_
<input id="restartButton" type="button" value="Restart">
_x000D_
When you are declaring a pointer variable or function parameter, use the *:
int *x = NULL;
int *y = malloc(sizeof(int)), *z = NULL;
int* f(int *x) {
...
}
NB: each declared variable needs its own *.
When you want to take the address of a value, use &. When you want to read or write the value in a pointer, use *.
int a;
int *b;
b = f(&a);
a = *b;
a = *f(&a);
Arrays are usually just treated like pointers. When you declare an array parameter in a function, you can just as easily declare it is a pointer (it means the same thing). When you pass an array to a function, you are actually passing a pointer to the first element.
Function pointers are the only things that don't quite follow the rules. You can take the address of a function without using &, and you can call a function pointer without using *.
Use off()
method after click event is triggered to disable element for the further click.
$('#clickElement').off('click');
Retrofit 2.0 solution
@Multipart
@POST(APIUtils.UPDATE_PROFILE_IMAGE_URL)
public Call<CommonResponse> requestUpdateImage(@PartMap Map<String, RequestBody> map);
and
Map<String, RequestBody> params = new HashMap<>();
params.put("newProfilePicture" + "\"; filename=\"" + FilenameUtils.getName(file.getAbsolutePath()), RequestBody.create(MediaType.parse("image/jpg"), file));
Call<CommonResponse> call = request.requestUpdateImage(params);
you can use
image/jpg
image/png
image/gif
Most windows users won't have that font on their computers. Also, you can't just submit it to your server and call it using font-face because this isn't a free font...
And last, but not least, answering the question that nobody mentioned yet, Helvetica and Helvetica Neue do not render well on screen unless they have a really big font-size
. You'll find a lot of pages using this font, and in all of them you'll see that the top border of a line of text looks wavy and that some letters look taller than others. In my opinion this is the main reason why you shouldn't use it. There are other options for you to use, like Open Sans.
Your formulation is almost correct. You want:
subset(dat, ID=="P1" | ID=="P3")
Where the |
('pipe') means 'or'. Your solution, ID=="P1 & P3"
, is looking for a case where ID is literally "P1 & P3"
You are floating the children which means they "float" in front of the container. In order to take the correct height, you must "clear" the float
The div style="clear: both" clears the floating an gives the correct height to the container. see http://css.maxdesign.com.au/floatutorial/clear.htm for more info on floats.
eg.
<div class="c">
<div class="l">
</div>
<div class="m">
World
</div>
<div style="clear: both" />
</div>
<VirtualHost *:80>
ServerAlias example.com
RedirectMatch permanent ^/(.*) http://www.example.com/$1
</VirtualHost>
This will redirect not only the domain name but also the inner
pages.like...
example.com/abcd.html ==> www.example.com/abcd.html
example.com/ab/cd.html?ef=gh ==> www.example.com/ab/cd.html?ef=gh
Cannot update first answer.
Anyway, after Go1 release, there are some breaking changes, so I updated as shown below:
package main
import (
"os"
"bufio"
"bytes"
"io"
"fmt"
"strings"
)
// Read a whole file into the memory and store it as array of lines
func readLines(path string) (lines []string, err error) {
var (
file *os.File
part []byte
prefix bool
)
if file, err = os.Open(path); err != nil {
return
}
defer file.Close()
reader := bufio.NewReader(file)
buffer := bytes.NewBuffer(make([]byte, 0))
for {
if part, prefix, err = reader.ReadLine(); err != nil {
break
}
buffer.Write(part)
if !prefix {
lines = append(lines, buffer.String())
buffer.Reset()
}
}
if err == io.EOF {
err = nil
}
return
}
func writeLines(lines []string, path string) (err error) {
var (
file *os.File
)
if file, err = os.Create(path); err != nil {
return
}
defer file.Close()
//writer := bufio.NewWriter(file)
for _,item := range lines {
//fmt.Println(item)
_, err := file.WriteString(strings.TrimSpace(item) + "\n");
//file.Write([]byte(item));
if err != nil {
//fmt.Println("debug")
fmt.Println(err)
break
}
}
/*content := strings.Join(lines, "\n")
_, err = writer.WriteString(content)*/
return
}
func main() {
lines, err := readLines("foo.txt")
if err != nil {
fmt.Println("Error: %s\n", err)
return
}
for _, line := range lines {
fmt.Println(line)
}
//array := []string{"7.0", "8.5", "9.1"}
err = writeLines(lines, "foo2.txt")
fmt.Println(err)
}
<?php
if (isset($_POST['birthdate'])) {
$timestamp = strtotime($_POST['birthdate']);
$date=date('d',$timestamp);
$month=date('m',$timestamp);
$year=date('Y',$timestamp);
}
?>
I tried your code and got a top rounded corner button. I gave the colors as @ffffff
and stroke I gave #C0C0C0
.
try
This should work:
ax1.plot(xtr, color='r', label='HHZ 1')
ax1.legend(loc="upper right")
ax2.plot(xtr, color='r', label='HHN')
ax2.legend(loc="upper right")
ax3.plot(xtr, color='r', label='HHE')
ax3.legend(loc="upper right")