There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.
Similarity::Similarity()
or Similarity::~Similarity()
are just missing and you have defined the others incorrectly,
void Similarity::readData(Scanner& inStream){
}
not
void readData(Scanner& inStream){
}
etc. etc.
The second one is a function called readData, only the first is the readData method of the Similarity class.
To be clear about this, in Similarity.h
void readData(Scanner& inStream);
but in Similarity.cpp
void Similarity::readData(Scanner& inStream){
}
This will happen if we use any of the in built classes in the php library. I used the class name as Directory and I got the same error. If you get error first make sure that the class name you use is not one of the in built classes.
In order to read or write to the standard input/output streams you need to include it.
int main( int argc, char * argv[] )
{
std::cout << "Hello World!" << std::endl;
return 0;
}
That program will not compile unless you add #include <iostream>
The second line isn't necessary
using namespace std;
What that does is tell the compiler that symbol names defined in the std
namespace are to be brought into your program's scope, so you can omit the namespace qualifier, and write for example
#include <iostream>
using namespace std;
int main( int argc, char * argv[] )
{
cout << "Hello World!" << endl;
return 0;
}
Notice you no longer need to refer to the output stream with the fully qualified name std::cout
and can use the shorter name cout
.
I personally don't like bringing in all symbols in the namespace of a header file... I'll individually select the symbols I want to be shorter... so I would do this:
#include <iostream>
using std::cout;
using std::endl;
int main( int argc, char * argv[] )
{
cout << "Hello World!" << endl;
return 0;
}
But that is a matter of personal preference.
This is the main difference between username variable and whoami command:
C:\Users\user.name>echo %username%
user.name
C:\Users\user.name>whoami
domain\user.name
DOMAIN = bios name of the domain (not fqdn)
You need to use ContextCompat.getColor(), which is part of the Support V4 Library (so it will work for all the previous API).
ContextCompat.getColor(context, R.color.my_color)
As specified in the documentation, "Starting in M, the returned color will be styled for the specified Context's theme". SO no need to worry about it.
You can add the Support V4 library by adding the following to the dependencies array inside your app build.gradle:
compile 'com.android.support:support-v4:23.0.1'
Function:
function appendArray(form_data, values, name){
if(!values && name)
form_data.append(name, '');
else{
if(typeof values == 'object'){
for(key in values){
if(typeof values[key] == 'object')
appendArray(form_data, values[key], name + '[' + key + ']');
else
form_data.append(name + '[' + key + ']', values[key]);
}
}else
form_data.append(name, values);
}
return form_data;
}
Use:
var form = document.createElement('form');// or document.getElementById('my_form_id');
var formdata = new FormData(form);
appendArray(formdata, {
sefgusyg: {
sujyfgsujyfsg: 'srkisgfisfsgsrg',
},
test1: 5,
test2: 6,
test3: 8,
test4: 3,
test5: [
'sejyfgjy',
'isdyfgusygf',
],
});
Step 1 : import android.*;
Step 2 : clean your project
Step 3 : Enjoy !!!
In here:
if (ValidationUtils.isNullOrEmpty(lastName)) {
registrationErrors.add(ValidationErrors.LAST_NAME);
}
if (!ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
you check for null or empty value on lastname, but in isEmailValid you don't check for empty value. Something like this should do
if (ValidationUtils.isNullOrEmpty(email) || !ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
or better yet, fix your ValidationUtils.isEmailValid() to cope with null email values. It shouldn't crash, it should just return false.
This example run ok
var currency = "$1,123,456.00";
var number = Number(currency.replace(/[^0-9\.]+/g,""));
console.log(number);
_x000D_
My solution to this issue in my spring boot application was to open the spring application context and adding the class for the missing autowired bean manually!
(access via Project Structure menu or spring tool window... edit "Spring Application Context")
So instead of SpringApplicationContext just containing my ExampleApplication spring configuration it also contains the missing Bean:
SpringApplicationContext:
et voilĂ : The error message disappeared!
ChDir "" was the solution for me. I use vba from WORD to launch a python3 script.
Use OpenFileDialog.SafeFileName
OpenFileDialog.SafeFileName
Gets the file name and extension for the file selected in the dialog box. The file name does not include the path.
So, __init__
is called when you are creating an instance of any class and initializing the instance variable also.
Example:
class User:
def __init__(self,first_n,last_n,age):
self.first_n = first_n
self.last_n = last_n
self.age = age
user1 = User("Jhone","Wrick","40")
And __call__
is called when you call the object like any other function.
Example:
class USER:
def __call__(self,arg):
"todo here"
print(f"I am in __call__ with arg : {arg} ")
user1=USER()
user1("One") #calling the object user1 and that's gonna call __call__ dunder functions
If you want every column and every row, then just pass in null
for the SQLiteDatabase
column
and selection
parameters.
Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null, null);
The other answers use rawQuery
, but you can use Android's built in SQLiteDatabase
. The documentation for query
says that you can just pass in null
to the selection
parameter to get all the rows.
selection
Passing null will return all rows for the given table.
And while you can also pass in null
for the column
parameter to get all of the columns (as in the one-liner above), it is better to only return the columns that you need. The documentation says
columns
Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.
Example
SQLiteDatabase db = mHelper.getReadableDatabase();
String[] columns = {
MyDatabaseHelper.COLUMN_1,
MyDatabaseHelper.COLUMN_2,
MyDatabaseHelper.COLUMN_3};
String selection = null; // this will select all rows
Cursor cursor = db.query(MyDatabaseHelper.MY_TABLE, columns, selection,
null, null, null, null, null);
You can do this more easy way. And 100% works that you want
<?php
$servername = "localhost";
$username = "root";
$password = ""; //your database password
$dbname = "demo"; //your database name
$con = new mysqli($servername, $username, $password, $dbname);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
else
{
//echo ("Connect Successfully");
}
$query = "SELECT Date_time, Tempout FROM alarm_value"; // select column
$aresult = $con->query($query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Massive Electronics</title>
<script type="text/javascript" src="loder.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
var data = new google.visualization.DataTable();
var data = google.visualization.arrayToDataTable([
['Date_time','Tempout'],
<?php
while($row = mysqli_fetch_assoc($aresult)){
echo "['".$row["Date_time"]."', ".$row["Tempout"]."],";
}
?>
]);
var options = {
title: 'Date_time Vs Room Out Temp',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.AreaChart(document.getElementById('areachart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="areachart" style="width: 900px; height: 400px"></div>
</body>
</html>
loder.js link here loder.js
Using org.apache.commons.io.FileUtils
File file = new File("F:/Lines");
Collection<File> files = FileUtils.listFiles(file, null, true);
for(File file2 : files){
System.out.println(file2.getName());
}
Use false if you do not want files from sub directories.
Edit: thought of something else.
You say you're creating a form dynamically - do you really mean a <form> and its contents 'cause asp.net takes issue with multiple forms on a page and it's already creating one uberform for you.
I just want to edit this for posterity that the tags for oracle weren't added when I answered this question. My response was more applicable to MS SQL.
Merge join is the best possible as it exploits the ordering, resulting in a single pass down the tables to do the join. IF you have two tables (or covering indexes) that have their ordering the same such as a primary key and an index of a table on that key then a merge join would result if you performed that action.
Hash join is the next best, as it's usually done when one table has a small number (relatively) of items, its effectively creating a temp table with hashes for each row which is then searched continuously to create the join.
Worst case is nested loop which is order (n * m) which means there is no ordering or size to exploit and the join is simply, for each row in table x, search table y for joins to do.
This is not possible, it will give you a compile time error,
You can use array for this type of requirement .
For your Reference :
http://msdn.microsoft.com/en-us/library/aa288453%28v=vs.71%29.aspx
> df <- data.frame(matrix(ncol = 300, nrow = 100))
> dim(df)
[1] 100 300
I would just query for the for
attribute instead of repetitively recursing the DOM tree.
$("input:checkbox").on("change", function() {
$("label[for='"+this.id+"']").text("TESTTTT");
});
You've instantiated text2 as an Optional (e.g. var text2: String?). This is why you receive Optional("5") in your string. take away the ? and replace with:
var text2: String = ""
As an addition to answers above: you probably might need to change ids in names/ids of input elements (pls note, you should not have digits in fields name):
<input name="someStuff.entry[2].fieldOne" id="someStuff_fdf_fieldOne_2" ..>
I have done this having some global variable by default set to 0:
var globalNewIndex = 0;
and in the add function after you've cloned and resetted the values in the new row:
var newIndex = globalNewIndex+1;
var changeIds = function(i, val) {
return val.replace(globalNewIndex,newIndex);
}
$('#mytable tbody>tr:last input').attr('name', changeIds ).attr('id', changeIds );
globalNewIndex++;
You may also want to look at some of the more specialised types, like ListIterator, NavigableSet and (if you're interested in maps) NavigableMap.
Lazy simple version for forgetfuls like me:
git rebase -i HEAD~3
or however many commits instead of 3.
Turn this
pick YourCommitMessageWhatever
pick YouGetThePoint
pick IdkManItsACommitMessage
into this
pick YourCommitMessageWhatever
s YouGetThePoint
s IdkManItsACommitMessage
and do some action where you hit esc
then enter
to save the changes. [1]
When the next screen comes up, get rid of those garbage # lines [2] and create a new commit message or something, and do the same escape
enter
action. [1]
Wowee, you have fewer commits. Or you just broke everything.
[1] - or whatever works with your git configuration. This is just a sequence that's efficient given my setup.
[2] - you'll see some stuff like # this is your n'th commit
a few times, with your original commits right below these message. You want to remove these lines, and create a commit message to reflect the intentions of the n commits that you're combining into 1.
In my activities onResume and onPause I write an isVisible boolean to SharedPrefences.
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = sharedPrefs.edit();
editor.putBoolean("visible", false);
editor.commit();
And read it elsewhere when needed via,
// Show a Toast Notification if App is not visible (ie in background. Not running, etc)
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
if(!sharedPrefs.getBoolean("visible", true)){...}
Maybe not elegant, but it works for me...
Here's another solution using the bin_data()
function from the mltools package.
library(mltools)
# Resulting bins have an equal number of observations in each group
das[, "wt2"] <- bin_data(das$wt, bins=3, binType = "quantile")
# Resulting bins are equally spaced from min to max
das[, "wt3"] <- bin_data(das$wt, bins=3, binType = "explicit")
# Or if you'd rather define the bins yourself
das[, "wt4"] <- bin_data(das$wt, bins=c(-Inf, 250, 322, Inf), binType = "explicit")
das
anim wt wt2 wt3 wt4
1 1 181.0 [179, 200.333333333333) [179, 250.666666666667) [-Inf, 250)
2 2 179.0 [179, 200.333333333333) [179, 250.666666666667) [-Inf, 250)
3 3 180.5 [179, 200.333333333333) [179, 250.666666666667) [-Inf, 250)
4 4 201.0 [200.333333333333, 245.466666666667) [179, 250.666666666667) [-Inf, 250)
5 5 201.5 [200.333333333333, 245.466666666667) [179, 250.666666666667) [-Inf, 250)
6 6 245.0 [200.333333333333, 245.466666666667) [179, 250.666666666667) [-Inf, 250)
7 7 246.4 [245.466666666667, 394] [179, 250.666666666667) [-Inf, 250)
8 8 189.3 [179, 200.333333333333) [179, 250.666666666667) [-Inf, 250)
9 9 301.0 [245.466666666667, 394] [250.666666666667, 322.333333333333) [250, 322)
10 10 354.0 [245.466666666667, 394] [322.333333333333, 394] [322, Inf]
11 11 369.0 [245.466666666667, 394] [322.333333333333, 394] [322, Inf]
12 12 205.0 [200.333333333333, 245.466666666667) [179, 250.666666666667) [-Inf, 250)
13 13 199.0 [179, 200.333333333333) [179, 250.666666666667) [-Inf, 250)
14 14 394.0 [245.466666666667, 394] [322.333333333333, 394] [322, Inf]
15 15 231.3 [200.333333333333, 245.466666666667) [179, 250.666666666667) [-Inf, 250)
If you don't want to use CSS try this one between your rows:
<tr>
<td class="divider"><hr /></td>
</tr>
Cheers!!
In Java, when you write:
Object objectA = new Object();
Object objectB = objectA;
objectA
and objectB
are the same and point to the same reference. Changing one will change the other. So if you change the state of objectA
(not its reference) objectB
will reflect that change too.
However, if you write:
objectA = new Object()
Then objectB
is still pointing to the first object you created (original objectA
) while objectA
is now pointing to a new Object.
Then just Select
:
var list = source.Select(s=>new { ID = s.ID, Name = s.Name }).ToList();
(edit) Actually - the names could be inferred in this case, so you could use:
var list = source.Select(s=>new { s.ID, s.Name }).ToList();
which saves a few electrons...
It is the version key.It gets updated whenever a new update is made. I personally don't like to disable it .
Read this solution if you want to know more [1]: Mongoose versioning: when is it safe to disable it?
I think your only option is to wrap java in a script that substitutes the environment variables into the command line
in python:
env = Environment(loader=FileSystemLoader("templates"))
env.globals["enumerate"] = enumerate
in template:
{% for k,v in enumerate(list) %}
{% endfor %}
Go to Tools|options|keymap. Search for 'zoom in text' and set your preferred key. I've set alt+plus and alt+minus.
You can run the sleep command before your ExecStart with ExecStartPre :
[Service]
ExecStartPre=/bin/sleep 30
Note that in Internet Explorer there are issues with dynamically created forms. A form created like this will not submit in IE (9):
var form = $('<form method="post" action="/test/Delete/">' +
'<input type="hidden" name="id" value="' + myid + '"></form>');
$(form).submit();
To get it working in IE create the form element and attach it before submitting like so:
var form = document.createElement("form");
$(form).attr("action", "/test/Delete")
.attr("method", "post");
$(form).html('<input type="hidden" name="id" value="' + myid + '" />');
document.body.appendChild(form);
$(form).submit();
document.body.removeChild(form);
Creating the form like in example 1 and then attaching it will not work - in IE9 it throws a JScript error DOM Exception: HIERARCHY_REQUEST_ERR (3)
Props to Tommy W @ https://stackoverflow.com/a/6694054/694325
Just make a rule for each case:
<div id="homePage" ng-class="{ 'center': page.isSelected(1) , 'left': !page.isSelected(1) }">
Or use the ternary operator:
<div id="homePage" ng-class="page.isSelected(1) ? 'center' : 'left'">
You can check Visual Studio Downloads for available Visual Studio Community
, Visual Studio Professional
, Visual Studio Enterprise
and Visual Studio Code
download links.
Update!
There is no direct links of Visual Studio 2015
at Visual Studio Downloads anymore. but the below links still works.
OR simply click on direct links below (for .iso/.exe file):
VSCode area:
app.js
let { func_name } = require('path_to_tools.js');
func_name(); //function calling
tools.js
let func_name = function() {
...
//function body
...
};
module.exports = { func_name };
MessageBox.Show(
"your message",
"window title",
MessageBoxButtons.OK,
MessageBoxIcon.Asterisk //For Info Asterisk
MessageBoxIcon.Exclamation //For triangle Warning
)
Class C {
int a;
int b;
C():b(1),a(2){} //warning, should be C():a(2),b(1)
}
the order is important because if a is initialized before b , and a is depend on b. undefined behavior will appear.
You don't need to use anything but plain React and ES6 to achieve what you want. As per Jim's answer, just define the constant in the right place. I like the idea of keeping the constant local to the component if not needed externally. The below is an example of possible usage.
import React from "react";
const sizeToLetterMap = {
small_square: 's',
large_square: 'q',
thumbnail: 't',
small_240: 'm',
small_320: 'n',
medium_640: 'z',
medium_800: 'c',
large_1024: 'b',
large_1600: 'h',
large_2048: 'k',
original: 'o'
};
class PhotoComponent extends React.Component {
constructor(args) {
super(args);
}
photoUrl(image, size_text) {
return (<span>
Image: {image}, Size Letter: {sizeToLetterMap[size_text]}
</span>);
}
render() {
return (
<div className="photo-wrapper">
The url is: {this.photoUrl(this.props.image, this.props.size_text)}
</div>
)
}
}
export default PhotoComponent;
// Call this with <PhotoComponent image="abc.png" size_text="thumbnail" />
// Of course the component must first be imported where used, example:
// import PhotoComponent from "./photo_component.jsx";
In Powershell 5 escaping double quotes can be done by backtick (`). But sometimes you need to provide your double quotes escaped which can be done by backslash + backtick (\`). Eg in this curl call:
C:\Windows\System32\curl.exe -s -k -H "Content-Type: application/json" -XPOST localhost:9200/index_name/inded_type -d"{\`"velocity\`":3.14}"
You can use stringstream's
int str2int (const string &str) {
stringstream ss(str);
int num;
ss >> num;
return num;
}
One option would be:
SET SERVEROUTPUT ON
EXEC DBMS_OUTPUT.PUT_LINE(your_fn_name(your_fn_arguments));
Definitely regex:
string CleanPhone(string phone)
{
Regex digitsOnly = new Regex(@"[^\d]");
return digitsOnly.Replace(phone, "");
}
or within a class to avoid re-creating the regex all the time:
private static Regex digitsOnly = new Regex(@"[^\d]");
public static string CleanPhone(string phone)
{
return digitsOnly.Replace(phone, "");
}
Depending on your real-world inputs, you may want some additional logic there to do things like strip out leading 1's (for long distance) or anything trailing an x or X (for extensions).
To disable inputting password:
sudo visudo
Then add a new line like below and save then:
# The user can run installer as root without inputting password
yourusername ALL=(root) NOPASSWD: /usr/sbin/installer
Then you run installer without password:
sudo installer -pkg ...
Thanks for your answers. I missed that my data is stored in a List<String>
which is passed to the tested method. The mistake was that I put the string into the first element of the ArrayList. That's why I thought the String consists of just one single line, because the debugger showed me only one entry.
It's hard to say without knowing the whole context of the problem, but I would not override __iter__
.
I would implement __what_goes_here__
on the class.
as_dict(self:
d = {...whatever you need...}
return d
//in Service
`
public List<DevicesPerCustomer> findDevicesPerCustomer() {
LOGGER.info(TAG_NAME + " :: inside findDevicesPerCustomer : ");
List<Object[]> list = iDeviceRegistrationRepo.findDevicesPerCustomer();
List<DevicesPerCustomer> out = new ArrayList<>();
if (list != null && !list.isEmpty()) {
DevicesPerCustomer mDevicesPerCustomer = null;
for (Object[] object : list) {
mDevicesPerCustomer = new DevicesPerCustomer();
mDevicesPerCustomer.setCustomerId(object[0].toString());
mDevicesPerCustomer.setCount(Integer.parseInt(object[1].toString()));
out.add(mDevicesPerCustomer);
}
}
return out;
}`
//In Repo
` @Query(value = "SELECT d.customerId,count(*) FROM senseer.DEVICE_REGISTRATION d where d.customerId is not null group by d.customerId", nativeQuery=true)
List<Object[]> findDevicesPerCustomer();`
See IdentityModel.EpochTimeExtensions
public static class EpochTimeExtensions
{
/// <summary>
/// Converts the given date value to epoch time.
/// </summary>
public static long ToEpochTime(this DateTime dateTime)
{
var date = dateTime.ToUniversalTime();
var ticks = date.Ticks - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).Ticks;
var ts = ticks / TimeSpan.TicksPerSecond;
return ts;
}
/// <summary>
/// Converts the given date value to epoch time.
/// </summary>
public static long ToEpochTime(this DateTimeOffset dateTime)
{
var date = dateTime.ToUniversalTime();
var ticks = date.Ticks - new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero).Ticks;
var ts = ticks / TimeSpan.TicksPerSecond;
return ts;
}
/// <summary>
/// Converts the given epoch time to a <see cref="DateTime"/> with <see cref="DateTimeKind.Utc"/> kind.
/// </summary>
public static DateTime ToDateTimeFromEpoch(this long intDate)
{
var timeInTicks = intDate * TimeSpan.TicksPerSecond;
return new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddTicks(timeInTicks);
}
/// <summary>
/// Converts the given epoch time to a UTC <see cref="DateTimeOffset"/>.
/// </summary>
public static DateTimeOffset ToDateTimeOffsetFromEpoch(this long intDate)
{
var timeInTicks = intDate * TimeSpan.TicksPerSecond;
return new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero).AddTicks(timeInTicks);
}
}
For Bootstrap (at least for version 3.1.1) and LESS, you can use this:
.btn-my-custom {
.button-variant(@color; @background; @border)
}
This is defined in bootstrap/less/buttons.less
.
IF
is a PL/SQL construct. If you are executing a query, you are using SQL not PL/SQL.
In SQL, you can use a CASE
statement in the query itself
SELECT DISTINCT a.item,
(CASE WHEN b.salesman = 'VIKKIE'
THEN 'ICKY'
ELSE b.salesman
END),
NVL(a.manufacturer,'Not Set') Manufacturer
FROM inv_items a,
arv_sales b
WHERE a.co = '100'
AND a.co = b.co
AND A.ITEM_KEY = b.item_key
AND a.item LIKE 'BX%'
AND b.salesman in ('01','15')
AND trans_date BETWEEN to_date('010113','mmddrr')
and to_date('011713','mmddrr')
ORDER BY a.item
Since you aren't doing any aggregation, you don't want a GROUP BY
in your query. Are you really sure that you need the DISTINCT
? People often throw that in haphazardly or add it when they are missing a join condition rather than considering whether it is really necessary to do the extra work to identify and remove duplicates.
I know there are already a lot of answers here - but this one is missing so far; a solution which also works with ajax generated content:
$(function (){
$(document).on("focus", "input:text", function() {
$(this).select();
});
});
$(document).ready(function () {
$("#txt1").attr("onfocus", "blur()");
});
$(document).ready(function () {_x000D_
$("#txt1").attr("onfocus", "blur()");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
_x000D_
<input id="txt1">
_x000D_
Check the LOB segment name from dba_lobs using the table name.
select TABLE_NAME,OWNER,COLUMN_NAME,SEGMENT_NAME from dba_lobs where TABLE_NAME='<<TABLE NAME>>';
Now use the segment name to find the bytes used in dba_segments.
select s.segment_name, s.partition_name, bytes/1048576 "Size (MB)"
from dba_segments s, dba_lobs l
where s.segment_name = l.segment_name
and s.owner = '<< OWNER >> ' order by s.segment_name, s.partition_name;
For those of us using non-ISO standard date formats, like civilian vernacular 01/01/2001 (mm/dd/YYYY), including time in a 12hour date format with am/pm marks, the following function will return a valid Date object:
function convertDate(date) {
// # valid js Date and time object format (YYYY-MM-DDTHH:MM:SS)
var dateTimeParts = date.split(' ');
// # this assumes time format has NO SPACE between time and am/pm marks.
if (dateTimeParts[1].indexOf(' ') == -1 && dateTimeParts[2] === undefined) {
var theTime = dateTimeParts[1];
// # strip out all except numbers and colon
var ampm = theTime.replace(/[0-9:]/g, '');
// # strip out all except letters (for AM/PM)
var time = theTime.replace(/[[^a-zA-Z]/g, '');
if (ampm == 'pm') {
time = time.split(':');
// # if time is 12:00, don't add 12
if (time[0] == 12) {
time = parseInt(time[0]) + ':' + time[1] + ':00';
} else {
time = parseInt(time[0]) + 12 + ':' + time[1] + ':00';
}
} else { // if AM
time = time.split(':');
// # if AM is less than 10 o'clock, add leading zero
if (time[0] < 10) {
time = '0' + time[0] + ':' + time[1] + ':00';
} else {
time = time[0] + ':' + time[1] + ':00';
}
}
}
// # create a new date object from only the date part
var dateObj = new Date(dateTimeParts[0]);
// # add leading zero to date of the month if less than 10
var dayOfMonth = (dateObj.getDate() < 10 ? ("0" + dateObj.getDate()) : dateObj.getDate());
// # parse each date object part and put all parts together
var yearMoDay = dateObj.getFullYear() + '-' + (dateObj.getMonth() + 1) + '-' + dayOfMonth;
// # finally combine re-formatted date and re-formatted time!
var date = new Date(yearMoDay + 'T' + time);
return date;
}
Usage:
date = convertDate('11/15/2016 2:00pm');
select * from test
where date between '03/19/2014' and '03/19/2014 23:59:59'
This is a realy bad answer. For two reasons.
1. What happens with times like 23.59.59.700 etc. There are times larger than 23:59:59 and the next day.
2. The behaviour depends on the datatype. The query behaves differently for datetime/date/datetime2 types.
Testing with 23:59:59.999 makes it even worse because depending on the datetype you get different roundings.
select convert (varchar(40),convert(date , '2014-03-19 23:59:59.999'))
select convert (varchar(40),convert(datetime , '2014-03-19 23:59:59.999'))
select convert (varchar(40),convert(datetime2 , '2014-03-19 23:59:59.999'))
-- For date the value is 'chopped'. -- For datetime the value is rounded up to the next date. (Nearest value). -- For datetime2 the value is precise.
You can open the DevTools in Chrome with CTRL+I on Windows (or CMD+I Mac), and Firefox with F12, then select the Console
tab), and check the XPath by typing $x("your_xpath_here")
.
This will return an array of matched values. If it is empty, you know there is no match on the page.
A workaround and a handy tool:
CSS3Pie uses .htc files and the behavior property to implement CSS3 into IE 6 - 8.
Modernizr is a bit of javascript that will put classes on your html element, allowing you to serve different style definitions to different browsers based on their capabilities.
Obviously, these both add more overhead, but with IE9 due to only run on Vista/7 we might be stuck for quite awhile. As of August 2010 Windows XP still accounts for 48% of web client OSes.
Well for me, having
git reset --hard
just reset the submodule to the state where it checked out, not necessary to the main's repo referenced commit/state. I'll still have "modified contents" like OP said. So, in order to get the submodule back to the corrects commit, I run:
git submodule update --init
Then when I do git status
, it's clean on the submodule.
You need to make it a generic method, like this:
public static T ConfigSetting<T>(string settingName)
{
return /* code to convert the setting to T... */
}
But the caller will have to specify the type they expect. You could then potentially use Convert.ChangeType
, assuming that all the relevant types are supported:
public static T ConfigSetting<T>(string settingName)
{
object value = ConfigurationManager.AppSettings[settingName];
return (T) Convert.ChangeType(value, typeof(T));
}
I'm not entirely convinced that all this is a good idea, mind you...
Here is a simple example I wrote to convert and convert back using the 2 convert methods, I also checked it with a fixed string
declare @VB1 VARBINARY(500),@VB2 VARBINARY(500),@VB3 VARBINARY(500)
declare @S1 VARCHAR(500)
SET @VB1=HASHBYTES('SHA1','Test')
SET @S1=CONVERT(varchar(500),@VB1,2)
SET @VB2=CONVERT(varbinary(500),@S1,2)
SET @VB3=CONVERT(varbinary(500),'640AB2BAE07BEDC4C163F679A746F7AB7FB5D1FA',2)
SELECT @VB1,@S1,@VB2,@VB3
IF @VB1=@VB2 PRINT 'They Match(2)'
IF @VB1=@VB3 PRINT 'They Match(3)'
PRINT str(Len(@VB1))
PRINT str(Len(@S1))
PRINT str(Len(@VB2))
SET @VB1=HASHBYTES('SHA1','Test')
SET @S1=CONVERT(varchar(500),@VB1,1)
SET @VB2=CONVERT(varbinary(500),@S1,1)
SELECT @VB1,@S1,@VB2
IF @VB1=@VB2 PRINT 'They Match(1)'
PRINT str(Len(@VB1))
PRINT str(Len(@S1))
PRINT str(Len(@VB2))
and the output
||| 0x640AB2BAE07BEDC4C163F679A746F7AB7FB5D1FA|640AB2BAE07BEDC4C163F679A746F7AB7FB5D1FA|0x640AB2BAE07BEDC4C163F679A746F7AB7FB5D1FA|0x640AB2BAE07BEDC4C163F679A746F7AB7FB5D1FA
(1 row(s) affected)
They Match(2)
They Match(3)
20
40
20
|| 0x640AB2BAE07BEDC4C163F679A746F7AB7FB5D1FA|0x640AB2BAE07BEDC4C163F679A746F7AB7FB5D1FA|0x640AB2BAE07BEDC4C163F679A746F7AB7FB5D1FA
(1 row(s) affected)
They Match(1)
20
42
20
You can use a CASE
statement.
SELECT
CASE WHEN currate.currentrate IS NULL THEN 1 ELSE currate.currentrate END
FROM ...
I believe the part regarding how to span rows has been answered thoroughly (i.e. by nesting rows), but I also ran into the issue of my nested rows not filling their container. While flexbox and negative margins are an option, a much easier solution is to use the predefined h-50
class on the row
containing boxes 2, 3, 4, and 5.
Note: I am using
Bootstrap-4
, I just wanted to share because I ran into the same problem and found this to be a more elegant solution :)
You have to set both layout_gravity and layout_columntWeight on your columns
<android.support.v7.widget.GridLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView android:text="??? ???"
app:layout_gravity="fill_horizontal"
app:layout_columnWeight="1"
/>
<TextView android:text="??? ???"
app:layout_gravity="fill_horizontal"
app:layout_columnWeight="1"
/>
<TextView android:text="??? ???"
app:layout_gravity="fill_horizontal"
app:layout_columnWeight="1"
/>
</android.support.v7.widget.GridLayout>
You can use the excellent jquery-Json plugin:
http://code.google.com/p/jquery-json/
Makes it easy to convert to and from Json objects.
let res = /^[a-zA-Z]+$/.test('sfjd');
console.log(res);
_x000D_
Note: If you have any punctuation marks or anything, those are all invalid too. Dashes and underscores are invalid. \w
covers a-zA-Z and some other word characters. It all depends on what you need specifically.
This may not be an option for you, but if you can use the Parallel Extension for .NET then you could use Task
s instead of raw threads and then use Task.WaitAll()
to wait for them to complete.
You can use a for
loop:
var found = false;
for (var i = 0; i < categories.length && !found; i++) {
if (categories[i] === "specialword") {
found = true;
break;
}
}
=begin
(some code here)
=end
and
# This code
# on multiple lines
# is commented out
are both correct. The advantage of the first type of comment is editability—it's easier to uncomment because fewer characters are deleted. The advantage of the second type of comment is readability—reading the code line by line, it's much easier to tell that a particular line has been commented out. Your call but think about who's coming after you and how easy it is for them to read and maintain.
I had a lot of fiddling around with this, and couldn't get it to work even with the variable defined with "="
in the scope. Here's three solutions depending on your situation.
I found that the variable was not evaluated by angular yet when it was passed to the directive. This means that you can access it and use it in the template, but not inside the link or app controller function unless we wait for it to be evaluated.
If your variable is changing, or is fetched through a request, you should use $observe
or $watch
:
app.directive('yourDirective', function () {
return {
restrict: 'A',
// NB: no isolated scope!!
link: function (scope, element, attrs) {
// observe changes in attribute - could also be scope.$watch
attrs.$observe('yourDirective', function (value) {
if (value) {
console.log(value);
// pass value to app controller
scope.variable = value;
}
});
},
// the variable is available in directive controller,
// and can be fetched as done in link function
controller: ['$scope', '$element', '$attrs',
function ($scope, $element, $attrs) {
// observe changes in attribute - could also be scope.$watch
$attrs.$observe('yourDirective', function (value) {
if (value) {
console.log(value);
// pass value to app controller
$scope.variable = value;
}
});
}
]
};
})
.controller('MyCtrl', ['$scope', function ($scope) {
// variable passed to app controller
$scope.$watch('variable', function (value) {
if (value) {
console.log(value);
}
});
}]);
And here's the html (remember the brackets!):
<div ng-controller="MyCtrl">
<div your-directive="{{ someObject.someVariable }}"></div>
<!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
<div ng-bind="variable"></div>
</div>
Note that you should not set the variable to "="
in the scope, if you are using the $observe
function. Also, I found that it passes objects as strings, so if you're passing objects use solution #2 or scope.$watch(attrs.yourDirective, fn)
(, or #3 if your variable is not changing).
If your variable is created in e.g. another controller, but just need to wait until angular has evaluated it before sending it to the app controller, we can use $timeout
to wait until the $apply
has run. Also we need to use $emit
to send it to the parent scope app controller (due to the isolated scope in the directive):
app.directive('yourDirective', ['$timeout', function ($timeout) {
return {
restrict: 'A',
// NB: isolated scope!!
scope: {
yourDirective: '='
},
link: function (scope, element, attrs) {
// wait until after $apply
$timeout(function(){
console.log(scope.yourDirective);
// use scope.$emit to pass it to controller
scope.$emit('notification', scope.yourDirective);
});
},
// the variable is available in directive controller,
// and can be fetched as done in link function
controller: [ '$scope', function ($scope) {
// wait until after $apply
$timeout(function(){
console.log($scope.yourDirective);
// use $scope.$emit to pass it to controller
$scope.$emit('notification', scope.yourDirective);
});
}]
};
}])
.controller('MyCtrl', ['$scope', function ($scope) {
// variable passed to app controller
$scope.$on('notification', function (evt, value) {
console.log(value);
$scope.variable = value;
});
}]);
And here's the html (no brackets!):
<div ng-controller="MyCtrl">
<div your-directive="someObject.someVariable"></div>
<!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
<div ng-bind="variable"></div>
</div>
If your variable is not changing and you need to evaluate it in your directive, you can use the $eval
function:
app.directive('yourDirective', function () {
return {
restrict: 'A',
// NB: no isolated scope!!
link: function (scope, element, attrs) {
// executes the expression on the current scope returning the result
// and adds it to the scope
scope.variable = scope.$eval(attrs.yourDirective);
console.log(scope.variable);
},
// the variable is available in directive controller,
// and can be fetched as done in link function
controller: ['$scope', '$element', '$attrs',
function ($scope, $element, $attrs) {
// executes the expression on the current scope returning the result
// and adds it to the scope
scope.variable = scope.$eval($attrs.yourDirective);
console.log($scope.variable);
}
]
};
})
.controller('MyCtrl', ['$scope', function ($scope) {
// variable passed to app controller
$scope.$watch('variable', function (value) {
if (value) {
console.log(value);
}
});
}]);
And here's the html (remember the brackets!):
<div ng-controller="MyCtrl">
<div your-directive="{{ someObject.someVariable }}"></div>
<!-- use ng-bind instead of {{ }}, when you can to avoids FOUC -->
<div ng-bind="variable"></div>
</div>
Also, have a look at this answer: https://stackoverflow.com/a/12372494/1008519
Reference for FOUC (flash of unstyled content) issue: http://deansofer.com/posts/view/14/AngularJs-Tips-and-Tricks-UPDATED
For the interested: here's an article on the angular life cycle
This problem arises when you have a custom class that extends a different class (in this case a view) and does not import all the constructors required by the class.
For eg : public class CustomTextView extends TextView{}
This class would have 4 constructors and if you miss out on any one it would crash. For the matter of fact I missed out the last one which was used by Lollipop added that constructor and worked fine.
I'm trying to give my 2 cents
0) QueryFirst https://marketplace.visualstudio.com/items?itemName=bbsimonbb.QueryFirst Query-first is a visual studio extension for working intelligently with SQL in C# projects. Use the provided .sql template to develop your queries. When you save the file, Query-first runs your query, retrieves the schema and generates two classes and an interface: a wrapper class with methods Execute(), ExecuteScalar(), ExecuteNonQuery() etc, its corresponding interface, and a POCO encapsulating a line of results.
1) Sql2Objects Creates the class starting from the result of a query (but not the DAL)
2) https://docs.microsoft.com/en-us/ef/ef6/resources/tools
3) https://visualstudiomagazine.com/articles/2012/12/11/sqlqueryresults-code-generation.aspx
xmltodict (full disclosure: I wrote it) can help you convert your XML to a dict+list+string structure, following this "standard". It is Expat-based, so it's very fast and doesn't need to load the whole XML tree in memory.
Once you have that data structure, you can serialize it to JSON:
import xmltodict, json
o = xmltodict.parse('<e> <a>text</a> <a>text</a> </e>')
json.dumps(o) # '{"e": {"a": ["text", "text"]}}'
This is the best way to implement Onclicklistener for many buttons in a row implement View.onclicklistener.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
This is a button in the MainActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt_submit = (Button) findViewById(R.id.submit);
bt_submit.setOnClickListener(this);
}
This is an override method
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.submit:
//action
break;
case R.id.secondbutton:
//action
break;
}
}
I was trying to install fancyimpute package for imputation but there was not luck. But when i tried below commands, it got installed: Commands:
conda update conda
conda update anaconda
pip install fancyimpute
(here i was trying to give command conda install fancyimpute which did't work)
You Can Try This
$("p:first").css("background-color", "#B2E0FF").css("border", "3px solid red");
Three years later, perhaps with the renewed emphasis on WebApi and xml data, I came across this question. Since codewise I am inclined to follow Skeet out of an airplane without a parachute, and seeing his initial code doubly corraborated by the MS Xml team article as well as an example in BOL Streaming Transform of Large Xml Docs, I very quickly overlooked the other comments, most specifically from 'pbz', who pointed out that if you have the same elements by name in succession, every other one is skipped because of the double read. And in fact, the BOL and MS blog articles both were parsing source documents with target elements nested deeper than second level, masking this side-effect.
The other answers address this problem. I just wanted to offer a slightly simpler revision that seems to work well so far, and takes into account that the xml might come from different sources, not just a uri, and so the extension works on the user managed XmlReader. The one assumption is that the reader is in its initial state, since otherwise the first 'Read()' might advance past a desired node:
public static IEnumerable<XElement> ElementsNamed(this XmlReader reader, string elementName)
{
reader.MoveToContent(); // will not advance reader if already on a content node; if successful, ReadState is Interactive
reader.Read(); // this is needed, even with MoveToContent and ReadState.Interactive
while(!reader.EOF && reader.ReadState == ReadState.Interactive)
{
// corrected for bug noted by Wes below...
if(reader.NodeType == XmlNodeType.Element && reader.Name.Equals(elementName))
{
// this advances the reader...so it's either XNode.ReadFrom() or reader.Read(), but not both
var matchedElement = XNode.ReadFrom(reader) as XElement;
if(matchedElement != null)
yield return matchedElement;
}
else
reader.Read();
}
}
public enum Direction {
NORTH, EAST, SOUTH, WEST;
public Direction getOppositeDirection(){
return Direction.values()[(this.ordinal() + 2) % 4];
}
}
Enums have a static values method that returns an array containing all of the values of the enum in the order they are declared. source
since NORTH gets 1, EAST gets 2, SOUTH gets 3, WEST gets 4; you can create a simple equation to get the opposite one:
(value + 2) % 4
I had a similar problem, but mine was related to unmanageable memory leak that I couldn't find on an app that has to run 24/7. With the customer I agreed that safe time to restart the app was 03:00AM if the memory consumption was over the defined value.
I tried Application.Restart
, but since it seems to use some mechanism that starts new instance while it is already running, I went for another scheme. I used the trick that file system handles persist until process that created them dies. So, from The Application, i dropped the file to the disk, and didn't Dispose()
the handle. I used the file to send 'myself' executable and starting directory also (to add flexibility).
Code:
_restartInProgress = true;
string dropFilename = Path.Combine(Application.StartupPath, "restart.dat");
StreamWriter sw = new StreamWriter(new FileStream(dropFilename, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite));
sw.WriteLine(Application.ExecutablePath);
sw.WriteLine(Application.StartupPath);
sw.Flush();
Process.Start(new ProcessStartInfo
{
FileName = Path.Combine(Application.StartupPath, "VideoPhill.Restarter.exe"),
WorkingDirectory = Application.StartupPath,
Arguments = string.Format("\"{0}\"", dropFilename)
});
Close();
Close()
at the end would initiate app shutdown, and file handle I used for StreamWriter
here would be held open until process really dies. Then...
Restarter.exe comes into action. It TRIES to read the file in exclusive mode, preventing it to gain access until main app wasn't dead, then starts main app, deletes the file and exists. I guess that it can't be simpler:
static void Main(string[] args)
{
string filename = args[0];
DateTime start = DateTime.Now;
bool done = false;
while ((DateTime.Now - start).TotalSeconds < 30 && !done)
{
try
{
StreamReader sr = new StreamReader(new FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite));
string[] runData = new string[2];
runData[0] = sr.ReadLine();
runData[1] = sr.ReadLine();
Thread.Sleep(1000);
Process.Start(new ProcessStartInfo { FileName = runData[0], WorkingDirectory = runData[1] });
sr.Dispose();
File.Delete(filename);
done = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Thread.Sleep(1000);
}
}
var datos = $("#id_formulario").serialize();
$.ajax({
url: "url.php",
type: "POST",
dataType: "html",
data: datos,
success: function (prueba) {
alert("funciona!");
}//FIN SUCCES
});//FIN AJAX
Setting git proxy on terminal
if
Set it globally once
git config --global http.proxy username:password@proxy_url:proxy_port
git config --global https.proxy username:password@proxy_url:proxy_port
if you want to set proxy for only one git project (there may be some situations where you may not want to use same proxy or any proxy at all for some git connections)
//go to project root
cd /bla_bla/project_root
//set proxy for both http and https
git config http.proxy username:password@proxy_url:proxy_port
git config https.proxy username:password@proxy_url:proxy_port
if you want to display current proxy settings
git config --list
if you want to remove proxy globally
git config --global --unset http.proxy
git config --global --unset https.proxy
if you want to remove proxy for only one git root
//go to project root
cd /bla-bla/project_root
git config --unset http.proxy
git config --unset https.proxy
The workaround is
(this will remove all the new lines and there should be whole one line)
now perform your replacements
search and replace thisismynewlineword to \r\n
(to undo the step 1)
Add 15 day to a select element (using "Alive to Die" suggestion)
<select id="date_list" class="form-control" style="width:100%;">
<?php
$max_dates = 15;
$countDates = 0;
while ($countDates < $max_dates) {
$NewDate=Date('F d, Y', strtotime("+".$countDates." days"));
echo "<option>" . $NewDate . "</option>";
$countDates += 1;
}
?>
One thing that I have to add is that there is no reference in C.
Secondly, this is the language syntax convention. & - is an address operator but it also mean a reference - all depends on usa case
If there was some "reference" keyword instead of & you could write
int CDummy::isitme (reference CDummy param)
but this is C++ and we should accept it advantages and disadvantages...
You can just inject the DOCUMENT token into the constructor and use the same functions on it
import { Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
@Component({...})
export class AppCmp {
constructor(@Inject(DOCUMENT) document) {
document.getElementById('el');
}
}
Or if the element you want to get is in that component, you can use template references.
If your div completely filled the webpage then you can fill up that div and so have a canvas that fills up the div.
You may find this interesting, as you may need to use a css to use percentage, but, it depends on which browser you are using, and how much it is in agreement with the spec: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#the-canvas-element
The intrinsic dimensions of the canvas element equal the size of the coordinate space, with the numbers interpreted in CSS pixels. However, the element can be sized arbitrarily by a style sheet. During rendering, the image is scaled to fit this layout size.
You may need to get the offsetWidth and height of the div, or get the window height/width and set that as the pixel value.
What about using computed properties?
class MyClass {
class var myConstant: String { return "What is Love? Baby don't hurt me" }
}
MyClass.myConstant
OAuth 2.0 defines a protocol, i.e. specifies how tokens are transferred, JWT defines a token format.
OAuth 2.0 and "JWT authentication" have similar appearance when it comes to the (2nd) stage where the Client presents the token to the Resource Server: the token is passed in a header.
But "JWT authentication" is not a standard and does not specify how the Client obtains the token in the first place (the 1st stage). That is where the perceived complexity of OAuth comes from: it also defines various ways in which the Client can obtain an access token from something that is called an Authorization Server.
So the real difference is that JWT is just a token format, OAuth 2.0 is a protocol (that may use a JWT as a token format).
Edit /etc/conf.apf
. Set DEVEL_MODE="0"
. DEVEL_MODE
set to 1
will add a cron job to stop apf after 5 minutes.
While looking at the same problem, I found an example
<style type="text/css">
#topright {
position: absolute;
right: 0;
top: 0;
display: block;
height: 125px;
width: 125px;
background: url(TRbanner.gif) no-repeat;
text-indent: -999em;
text-decoration: none;
}
</style>
<a id="topright" href="#" title="TopRight">Top Right Link Text</a>
The trick here is to create a small, (I used GIMP) a PNG (or GIF) that has a transparent background, (and then just delete the opposite bottom corner.)
$computer,$Speed,$Regcheck
will create an array, and run out-file
ones per variable = they get seperate lines. If you construct a single string using the variables first, it will show up a single line. Like this:
"$computer,$Speed,$Regcheck" | out-file -filepath C:\temp\scripts\pshell\dump.txt -append -width 200
if you have this kind of problem with ispconfig3 and got an error like this
open_basedir restriction in effect. File(/var/www/clients/client7/web15) is not within the allowed path(s):.........
To solve it (in my case) , just set PHP to SuPHP in the Website's panel of ispconfig3
Hope it helps someone :)
Try a \<Space>
before 12
, like so:
:set guifont=Monospace\ 12
Pretty much what others have put before, but as a one liner that can be put at the beginning of a batch command. (Well, usually after @echo off.)
net.exe session 1>NUL 2>NUL || (Echo This script requires elevated rights. & Exit /b 1)
Edit: This is a more complete version that shows more differences between [
(aka test
) and [[
.
The following table shows that whether a variable is quoted or not, whether you use single or double brackets and whether the variable contains only a space are the things that affect whether using a test with or without -n/-z
is suitable for checking a variable.
| 1a 2a 3a 4a 5a 6a | 1b 2b 3b 4b 5b 6b
| [ [" [-n [-n" [-z [-z" | [[ [[" [[-n [[-n" [[-z [[-z"
-----+------------------------------------+------------------------------------
unset| false false true false true true | false false false false true true
null | false false true false true true | false false false false true true
space| false true true true true false| true true true true false false
zero | true true true true false false| true true true true false false
digit| true true true true false false| true true true true false false
char | true true true true false false| true true true true false false
hyphn| true true true true false false| true true true true false false
two | -err- true -err- true -err- false| true true true true false false
part | -err- true -err- true -err- false| true true true true false false
Tstr | true true -err- true -err- false| true true true true false false
Fsym | false true -err- true -err- false| true true true true false false
T= | true true -err- true -err- false| true true true true false false
F= | false true -err- true -err- false| true true true true false false
T!= | true true -err- true -err- false| true true true true false false
F!= | false true -err- true -err- false| true true true true false false
Teq | true true -err- true -err- false| true true true true false false
Feq | false true -err- true -err- false| true true true true false false
Tne | true true -err- true -err- false| true true true true false false
Fne | false true -err- true -err- false| true true true true false false
If you want to know if a variable is non-zero length, do any of the following:
-n
and quote the variable in single brackets (column 4a)-n
(columns 1b - 4b)Notice in column 1a starting at the row labeled "two" that the result indicates that [
is evaluating the contents of the variable as if they were part of the conditional expression (the result matches the assertion implied by the "T" or "F" in the description column). When [[
is used (column 1b), the variable content is seen as a string and not evaluated.
The errors in columns 3a and 5a are caused by the fact that the variable value includes a space and the variable is unquoted. Again, as shown in columns 3b and 5b, [[
evaluates the variable's contents as a string.
Correspondingly, for tests for zero-length strings, columns 6a, 5b and 6b show the correct ways to do that. Also note that any of these tests can be negated if negating shows a clearer intent than using the opposite operation. For example: if ! [[ -n $var ]]
.
If you're using [
, the key to making sure that you don't get unexpected results is quoting the variable. Using [[
, it doesn't matter.
The error messages, which are being suppressed, are "unary operator expected" or "binary operator expected".
This is the script that produced the table above.
#!/bin/bash
# by Dennis Williamson
# 2010-10-06, revised 2010-11-10
# for http://stackoverflow.com/q/3869072
# designed to fit an 80 character terminal
dw=5 # description column width
w=6 # table column width
t () { printf '%-*s' "$w" " true"; }
f () { [[ $? == 1 ]] && printf '%-*s' "$w" " false" || printf '%-*s' "$w" " -err-"; }
o=/dev/null
echo ' | 1a 2a 3a 4a 5a 6a | 1b 2b 3b 4b 5b 6b'
echo ' | [ [" [-n [-n" [-z [-z" | [[ [[" [[-n [[-n" [[-z [[-z"'
echo '-----+------------------------------------+------------------------------------'
while read -r d t
do
printf '%-*s|' "$dw" "$d"
case $d in
unset) unset t ;;
space) t=' ' ;;
esac
[ $t ] 2>$o && t || f
[ "$t" ] && t || f
[ -n $t ] 2>$o && t || f
[ -n "$t" ] && t || f
[ -z $t ] 2>$o && t || f
[ -z "$t" ] && t || f
echo -n "|"
[[ $t ]] && t || f
[[ "$t" ]] && t || f
[[ -n $t ]] && t || f
[[ -n "$t" ]] && t || f
[[ -z $t ]] && t || f
[[ -z "$t" ]] && t || f
echo
done <<'EOF'
unset
null
space
zero 0
digit 1
char c
hyphn -z
two a b
part a -a
Tstr -n a
Fsym -h .
T= 1 = 1
F= 1 = 2
T!= 1 != 2
F!= 1 != 1
Teq 1 -eq 1
Feq 1 -eq 2
Tne 1 -ne 2
Fne 1 -ne 1
EOF
This is how you'd do it with re:
import re
p = re.compile('^hello$', re.I)
p.match('Hello')
p.match('hello')
p.match('HELLO')
If you are using gvim, you could just hit Ctrl + Home to go the first line. Similarly, Ctrl + End goes to the last line.
To define deadlock, first I would define process.
Process : As we know process is nothing but a program
in execution.
Resource : To execute a program process needs some resources. Resource categories may include memory, printers, CPUs, open files, tape drives, CD-ROMS, etc.
Deadlock : Deadlock is a situation or condition when two or more processes are holding some resources and trying to acquire some more resources, and they can not release the resources until they finish there execution.
Deadlock condition or situation
In the above diagram there are two process P1 and p2 and there are two resources R1 and R2.
Resource R1 is allocated to process P1 and resource R2 is allocated to process p2. To complete execution of process P1 needs resource R2, so P1 request for R2, but R2 is already allocated to P2.
In the same way Process P2 to complete its execution needs R1, but R1 is already allocated to P1.
both the processes can not release their resource until and unless they complete their execution. So both are waiting for another resources and they will wait forever. So this is a DEADLOCK Condition.
In order for deadlock to occur, four conditions must be true.
and all these condition are satisfied in above diagram.
See this MSDN article and an example usage here on Stack Overflow.
Let's say that you have the following Linq/POCO class:
public class Color
{
public int ColorId { get; set; }
public string Name { get; set; }
}
And let's say that you have the following model:
public class PageModel
{
public int MyColorId { get; set; }
}
And, finally, let's say that you have the following list of colors. They could come from a Linq query, from a static list, etc.:
public static IEnumerable<Color> Colors = new List<Color> {
new Color {
ColorId = 1,
Name = "Red"
},
new Color {
ColorId = 2,
Name = "Blue"
}
};
In your view, you can create a drop down list like so:
<%= Html.DropDownListFor(n => n.MyColorId,
new SelectList(Colors, "ColorId", "Name")) %>
Well, getting full path is not possible but we can have a temporary path.
Try This:
It'll give you a temporary path not the accurate path, you can use this script if you want to show selected images as in this jsfiddle example(Try it by selectng images as well as other files):-
Here is the code :-
HTML:-
<input type="file" id="i_file" value="">
<input type="button" id="i_submit" value="Submit">
<br>
<img src="" width="200" style="display:none;" />
<br>
<div id="disp_tmp_path"></div>
JS:-
$('#i_file').change( function(event) {
var tmppath = URL.createObjectURL(event.target.files[0]);
$("img").fadeIn("fast").attr('src',URL.createObjectURL(event.target.files[0]));
$("#disp_tmp_path").html("Temporary Path(Copy it and try pasting it in browser address bar) --> <strong>["+tmppath+"]</strong>");
});
Its not exactly what you were looking for, but may be it can help you somewhere.
As addition of good answers, You don't have to use [FromForm]
to get form data in controller. Framework automatically convert form data to model as you wish. You can implement like following.
[HttpPost]
public async Task<IActionResult> Submit(MyModel model)
{
//...
}
Trying to "transfer an amount larger than my bitcoin balance" is not an unexpected error. You could use Popen.communicate()
directly instead of check_output()
to avoid raising an exception unnecessarily:
from subprocess import Popen, PIPE
p = Popen(['bitcoin', 'sendtoaddress', ..], stdout=PIPE)
output = p.communicate()[0]
if p.returncode != 0:
print("bitcoin failed %d %s" % (p.returncode, output))
As of 3/10/2019, Anguar dropped the support of sass. No mater what option you passed to --style
when running ng new
, you always get .scss
files generated. It's a shame that sass support was dropped without any explanation.
You can include your header function wherever you like, as long as NO html and/or text has been printed to standard out.
For more information and usage: http://php.net/manual/en/function.header.php
I see in your code that you echo()
out some text in case of error or success. Don't do that: you can't. You can only redirect OR show the text. If you show the text you'll then fail to redirect.
Any class that is inherited publicly, polymorphic or not, should have a virtual destructor. To put another way, if it can be pointed to by a base class pointer, its base class should have a virtual destructor.
If virtual, the derived class destructor gets called, then the base class constructor. If not virtual, only the base class destructor gets called.
I had very similar issue, i was keeping the VSC window with powershell script all the time when running the schedule task manually. Just closed it and it started working as expected.
You can use this to disabled the Hyperlink of asp.net or link buttons in html.
$("td > a").attr("disabled", "disabled").on("click", function() {
return false;
});
See this example: https://jsfiddle.net/pqhdce2L/
function b64toBlob(b64Data, contentType, sliceSize) {_x000D_
contentType = contentType || '';_x000D_
sliceSize = sliceSize || 512;_x000D_
_x000D_
var byteCharacters = atob(b64Data);_x000D_
var byteArrays = [];_x000D_
_x000D_
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {_x000D_
var slice = byteCharacters.slice(offset, offset + sliceSize);_x000D_
_x000D_
var byteNumbers = new Array(slice.length);_x000D_
for (var i = 0; i < slice.length; i++) {_x000D_
byteNumbers[i] = slice.charCodeAt(i);_x000D_
}_x000D_
_x000D_
var byteArray = new Uint8Array(byteNumbers);_x000D_
_x000D_
byteArrays.push(byteArray);_x000D_
}_x000D_
_x000D_
var blob = new Blob(byteArrays, {type: contentType});_x000D_
return blob;_x000D_
}_x000D_
_x000D_
_x000D_
var contentType = 'image/png';_x000D_
var b64Data = Your Base64 encode;_x000D_
_x000D_
var blob = b64toBlob(b64Data, contentType);_x000D_
var blobUrl = URL.createObjectURL(blob);_x000D_
_x000D_
var img = document.createElement('img');_x000D_
img.src = blobUrl;_x000D_
document.body.appendChild(img);
_x000D_
<div class="author_">Lord Byron</div>
.author_ { font-family: 'Playfair Display', serif; font-size: 1.25em; font-weight: 700;letter-spacing: 0.25em; font-style: italic;_x000D_
position:relative;_x000D_
margin-top: -0.5em;_x000D_
color: black;_x000D_
z-index:1;_x000D_
overflow:hidden;_x000D_
text-align:center;_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
.author_:after{_x000D_
left:20px;_x000D_
margin:0 -100% 0 0;_x000D_
display: inline-block;_x000D_
height: 10px;_x000D_
content: url(data:image/svg+xml,%0A%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22120px%22%20height%3D%2220px%22%20viewBox%3D%220%200%201200%20200%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%3E%0A%20%20%3Cpath%20stroke%3D%22black%22%20stroke-width%3D%223%22%20fill%3D%22none%22%20d%3D%22M1145%2085c17%2C7%208%2C24%20-4%2C29%20-12%2C4%20-40%2C6%20-48%2C-8%20-9%2C-15%209%2C-34%2026%2C-42%2017%2C-7%2045%2C-6%2062%2C2%2017%2C9%2019%2C18%2020%2C27%201%2C9%200%2C29%20-27%2C52%20-28%2C23%20-52%2C34%20-102%2C33%20-49%2C0%20-130%2C-31%20-185%2C-50%20-56%2C-18%20-74%2C-21%20-96%2C-23%20-22%2C-2%20-29%2C-2%20-56%2C7%20-27%2C8%20-44%2C17%20-44%2C17%20-13%2C5%20-15%2C7%20-40%2C16%20-25%2C9%20-69%2C14%20-120%2C11%20-51%2C-3%20-126%2C-23%20-181%2C-32%20-54%2C-9%20-105%2C-20%20-148%2C-23%20-42%2C-3%20-71%2C1%20-104%2C5%20-34%2C5%20-65%2C15%20-98%2C22%22%2F%3E%0A%3C%2Fsvg%3E%0A);_x000D_
}_x000D_
.author_:before {_x000D_
right:20px;_x000D_
margin:0 0 0 -100%;_x000D_
display: inline-block;_x000D_
height: 10px;_x000D_
content: url(data:image/svg+xml,%0A%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22120px%22%20height%3D%2220px%22%20viewBox%3D%220%200%201200%20130%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%3E%0A%20%20%3Cpath%20stroke%3D%22black%22%20stroke-width%3D%223%22%20fill%3D%22none%22%20d%3D%22M55%2068c-17%2C6%20-8%2C23%204%2C28%2012%2C5%2040%2C7%2048%2C-8%209%2C-15%20-9%2C-34%20-26%2C-41%20-17%2C-8%20-45%2C-7%20-62%2C2%20-18%2C8%20-19%2C18%20-20%2C27%20-1%2C9%200%2C29%2027%2C52%2028%2C23%2052%2C33%20102%2C33%2049%2C-1%20130%2C-31%20185%2C-50%2056%2C-19%2074%2C-21%2096%2C-23%2022%2C-2%2029%2C-2%2056%2C6%2027%2C8%2043%2C17%2043%2C17%2014%2C6%2016%2C7%2041%2C16%2025%2C9%2069%2C15%20120%2C11%2051%2C-3%20126%2C-22%20181%2C-32%2054%2C-9%20105%2C-20%20148%2C-23%2042%2C-3%2071%2C1%20104%2C6%2034%2C4%2065%2C14%2098%2C22%22%2F%3E%0A%3C%2Fsvg%3E%0A);_x000D_
}
_x000D_
<div class="author_">Lord Byron</div>
_x000D_
Convenient tool for SVG encoding url-encoder
You may think about factories
class XyFactory {
public function createXyObject ($other) {
$new = new XyObject($other->someValue);
// Do other things, that let $new look like $other (except the used class)
return $new;
}
}
Otherwise user250120s solution is the only one, which comes close to class casting.
This is a method I use which uses macros instead of a typedef. I know that this is not the C++ way of doing things but it can be convenient when chaining iterators together through inheritance when only the base class furthest down the hierarchy is acting upon an inherited offset.
For example:
// some header.h
#define CLASS some_iterator
#define SUPER_CLASS some_const_iterator
#define SUPER static_cast<SUPER_CLASS&>(*this)
template<typename T>
class CLASS : SUPER_CLASS {
typedef CLASS<T> class_type;
class_type& operator++();
};
template<typename T>
typename CLASS<T>::class_type CLASS<T>::operator++(
int)
{
class_type copy = *this;
// Macro
++SUPER;
// vs
// Typedef
// super::operator++();
return copy;
}
#undef CLASS
#undef SUPER_CLASS
#undef SUPER
The generic setup I use makes it very easy to read and copy/paste between the inheritance tree which have duplicate code but must be overridden because the return type has to match the current class.
One could use a lower-case super
to replicate the behavior seen in Java but my coding style is to use all upper-case letters for macros.
If you want this to be highlighted depending upon the page your user is on then do this:
To auto-highlight your current navigation, first label your body tags with an ID or class that matches the section of the site (usually a directory) that the page is in.
<body class="ab">
We label all files in the "/about/" directory with the "ab" class. Note that we use a class here to label the body tags. We found that using an ID in the body did not work consistently in some older browsers. Next we label our menu items so we can target them individually thus:
<div id="n"> <a class="b" id="hm"
href="/">Home</a> ... <a class="b"
id="ab" href="/about/">About</a> ...
</div>
Note that we use the "b"utton class to label menu items as buttons and an ID ("ab") to label each unique menu item (in this case about). Now all we need is a CSS selector that matches up the body label with the appropriate menu label like this:
body.ab #n #ab, body.ab #n #ab
a{color:#333;background:#dcdcdc;text-decoration:none;}
This code effectively highlights the "About" menu item and makes it appear dark gray. When you label the rest of the site and menu items, you'll end up with a grouped selector that looks something like this:
body.hm #n #hm, body.hm #n #hm a,
body.sm #n #sm, body.sm #n #sm a,
body.is #n #is, body.is #n #is a,
body.ab #n #ab, body.ab #n #ab a,
body.ct #n #ct, body.ct #n #ct
a{color:#333;background:#dcdcdc;text-decoration:none;}
For example when the user navigates to the sitemap section the .sm classed body tag matches the #sm menu option and triggers the CSS highlight of the "Sitemap" in the navigation bar.
You can create extension method like:
public static IEnumerable<TResult> LeftOuterJoin<TSource, TInner, TKey, TResult>(this IEnumerable<TSource> source, IEnumerable<TInner> other, Func<TSource, TKey> func, Func<TInner, TKey> innerkey, Func<TSource, TInner, TResult> res)
{
return from f in source
join b in other on func.Invoke(f) equals innerkey.Invoke(b) into g
from result in g.DefaultIfEmpty()
select res.Invoke(f, result);
}
The problem is occurring when you run prediction on the array [0.58,0.76]
. Fix the problem by reshaping it before you call predict()
:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use("ggplot")
from sklearn import svm
x = [1, 5, 1.5, 8, 1, 9]
y = [2, 8, 1.8, 8, 0.6, 11]
plt.scatter(x,y)
plt.show()
X = np.array([[1,2],
[5,8],
[1.5,1.8],
[8,8],
[1,0.6],
[9,11]])
y = [0,1,0,1,0,1]
clf = svm.SVC(kernel='linear', C = 1.0)
clf.fit(X,y)
test = np.array([0.58, 0.76])
print test # Produces: [ 0.58 0.76]
print test.shape # Produces: (2,) meaning 2 rows, 1 col
test = test.reshape(1, -1)
print test # Produces: [[ 0.58 0.76]]
print test.shape # Produces (1, 2) meaning 1 row, 2 cols
print(clf.predict(test)) # Produces [0], as expected
#include <iostream>
#include <sys/time.h>
using namespace std;
int main ()
{
unsigned long int sec= time(NULL);
cout<<sec<<endl;
}
Bootstrap now has the following style for table cells:
.table tbody > tr > td{
vertical-align: top;
}
The way to go is to add your own class, adding more specificity to the previous selector:
.table tbody > tr > td.vert-aligned {
vertical-align: middle;
}
And then add the class to your td
s:
<tr>
<td class="vert-aligned"></td>
...
</tr>
There is no way to do this with Bootstrap.
When used in table cells, vertical-align does what most people expect it to, which is to mimic the (old, deprecated) valign attribute. In a modern, standards-compliant browser, the following three code snippets do the same thing:
<td valign="middle"> <!-- but you shouldn't ever use valign --> </td>
<td style="vertical-align:middle"> ... </td>
<div style="display:table-cell; vertical-align:middle"> ... </div>
Check your fiddle updated
Also, you can't refer to the td
class using .vert
because Bootstrap already has this class:
.table td {
padding: 8px;
line-height: 20px;
text-align: left;
vertical-align: top; // The problem!
border-top: 1px solid #dddddd;
}
And is overloading the vertical-align: middle
in '.vert' class, so you have to define this class as td.vert
.
For anyone else who stumbles on this make sure you're not attempting to modify the class rather than the instance! (unless you've declared the variable as static)
eg.
MyClass.variable = 'Foo' // WRONG! - Instance member 'variable' cannot be used on type 'MyClass'
instanceOfMyClass.variable = 'Foo' // Right!
you can use this:
if ("ABCDEFGHIJKLMNOPQRSTUVWXYZ".contains(String.valueOf(yourChar)))
note that you do not need to create a separate String with the letters A-Z.
On Yosemite OSX, use this command:
sed -e 's/^M$//' -i '' filename
where the ^M
sequence is achieved by pressing Ctrl+V then Enter.
I know this is not directly answering the question at hand but for anyone that comes upon this question who is using WSL running Docker for windows and cmder or conemu.
The trick is not to use Docker which is installed on windows at /mnt/c/Program Files/Docker/Docker/resources/bin/docker.exe but rather to install the ubuntu/linux Docker. It's worth pointing out that you can't run Docker itself from within WSL but you can connect to Docker for windows from the linux Docker client.
Install Docker on Linux
sudo apt-get install apt-transport-https ca-certificates curl software-properties-common
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
sudo apt-get update
sudo apt-get install docker-ce
Connect to Docker for windows on the port 2375 which needs to be enabled from the settings in docker for windows.
docker -H localhost:2375 run -it -v /mnt/c/code:/var/app -w "/var/app" centos:7
Or set the docker_host variable which will allow you to omit the -H switch
export DOCKER_HOST=tcp://localhost:2375
You should now be able to connect interactively with a tty terminal session.
Encapsulation is hiding information.
Abstraction is hiding the functionality details.
Encapsulation is performed by constructing the class. Abstraction is achieved by creating either Abstract Classes or Interfaces on top of your class.
In the example given in the question, we are using the class for its functionality and we don't care about how the device achieves that. So we can say the details of the phone are "abstracted" from us.
Encapsulation is hiding WHAT THE PHONE USES to achieve whatever it does; Abstraction is hiding HOW IT DOES it.-
after going through the HTML 5.1 ducumentation (1 November 2016):
part 4 (The elements of HTML)
chapter 2 (Document metadata)
section 4 (The link element) states that:
The destination of the link(s) is given by the
href
attribute, which must be present and must contain a valid non-empty URL potentially surrounded by spaces. If thehref
attribute is absent, then the element does not define a link.
does not contain the src
attribute ...
witch is logical because it is a link .
chapter 12 (Scripting)
section 1 (The script element) states that:
Classic scripts may either be embedded inline or may be imported from an external file using the
src
attribute, which if specified gives the URL of the external script resource to use. Ifsrc
is specified, it must be a valid non-empty URL potentially surrounded by spaces. The contents of inline script elements, or the external script resource, must conform with the requirements of the JavaScript specification’s Script production for classic scripts.
it doesn't even mention the href
attribute ...
this indicates that while using script tags always use the src
attribute !!!
chapter 7 (Embedded content)
section 5 (The img element)
The image given by the
src
andsrcset
attributes, and any previous sibling source element'ssrcset
attributes if the parent is apicture
element, is the embedded content.
also doesn't mention the href
attribute ...
this indicates that when using img
tags the src
attribute should be used aswell ...
I think your problem is that the match method is returning an array. The 0th item in the array is the original string, the 1st thru nth items correspond to the 1st through nth matched parenthesised items. Your "alert()" call is showing the entire array.
Remove the semicolon (;), backtick (``) etc. from inside a query
If you're wanting this as a script, the following Bash script should do what you want (plus tell you when the file already exists):
#!/bin/bash
if [ -e $1 ]; then
echo "File $1 already exists!"
else
echo >> $1
fi
If you don't want the "already exists" message, you can use:
#!/bin/bash
if [ ! -e $1 ]; then
echo >> $1
fi
Edit about using:
Save whichever version with a name you like, let's say "create_file" (quotes mine, you don't want them in the file name). Then, to make the file executatble, at a command prompt do:
chmod u+x create_file
Put the file in a directory in your path, then use it with:
create_file NAME_OF_NEW_FILE
The $1 is a special shell variable which takes the first argument on the command line after the program name; i.e. $1 will pick up NAME_OF_NEW_FILE in the above usage example.
In Microsoft Windows, you can go through by route -f command to delete your current Gateway, check route / ? for more advance option, like add / delete etc and also can write a batch to add route on specific time as well but if you need to delete IP cache, then you have the option to use arp command.
You should try and avoid jQuery in ReactJS. But if you really want to use it, you'd put it in componentDidMount() lifecycle function of the component.
e.g.
class App extends React.Component {
componentDidMount() {
// Jquery here $(...)...
}
// ...
}
Ideally, you'd want to create a reusable Accordion component. For this you could use Jquery, or just use plain javascript + CSS.
class Accordion extends React.Component {
constructor() {
super();
this._handleClick = this._handleClick.bind(this);
}
componentDidMount() {
this._handleClick();
}
_handleClick() {
const acc = this._acc.children;
for (let i = 0; i < acc.length; i++) {
let a = acc[i];
a.onclick = () => a.classList.toggle("active");
}
}
render() {
return (
<div
ref={a => this._acc = a}
onClick={this._handleClick}>
{this.props.children}
</div>
)
}
}
Then you can use it in any component like so:
class App extends React.Component {
render() {
return (
<div>
<Accordion>
<div className="accor">
<div className="head">Head 1</div>
<div className="body"></div>
</div>
</Accordion>
</div>
);
}
}
Codepen link here: https://codepen.io/jzmmm/pen/JKLwEA?editors=0110 (I changed this link to https ^)
The meta-programming behind responder registration (see Parched Squid's answer) also allows you to do nifty stuff like this:
def index
@posts = Post.all
respond_to do |format|
format.html # index.html.erb
format.json { render :json => @posts }
format.csv { render :csv => @posts }
format.js
end
end
The csv line will cause to_csv to be called on each post when you visit /posts.csv. This makes it easy to export data as CSV (or any other format) from your rails site.
The js line will cause a javascript file /posts.js (or /posts.js.coffee) to be rendered/executed. I've found that to be a light-weight way to create an Ajax enabled site using jQuery UI pop-ups.
Thanks to https://stackoverflow.com/users/1652962/cimmanon that gave me the answer.
The solution is setting a height to the vertical scrollable element. For example:
#container article {
flex: 1 1 auto;
overflow-y: auto;
height: 0px;
}
The element will have height because flexbox recalculates it unless you want a min-height so you can use height: 100px;
that it is exactly the same as: min-height: 100px;
#container article {
flex: 1 1 auto;
overflow-y: auto;
height: 100px; /* == min-height: 100px*/
}
So the best solution if you want a min-height
in the vertical scroll:
#container article {
flex: 1 1 auto;
overflow-y: auto;
min-height: 100px;
}
If you just want full vertical scroll in case there is no enough space to see the article:
#container article {
flex: 1 1 auto;
overflow-y: auto;
min-height: 0px;
}
The final code: http://jsfiddle.net/ch7n6/867/
Beware the elephant trap:
I saw no mention of this in this discussion. [Access 2010]
How ACCESS/VBA handles errors in CLASS objects is determined by a configurable option:
VBA Code Editor > Tools > Options > General > Error Trapping:
You can install SideBarEnhancements plugin, which among other things will give you ability to open file in browser just by clicking F12.
To open exactly in Chrome, you will need to fix up “Side Bar.sublime-settings” file and set "default_browser"
to be "chrome"
.
I also recommend to learn this video tutorial on Sublime Text 2.
If you need to resume an scp transfer from local to remote, try with rsync:
rsync --partial --progress --rsh=ssh local_file user@host:remote_file
Short version, as pointed out by @aurelijus-rozenas:
rsync -P -e ssh local_file user@host:remote_file
In general the order of args for rsync is
rsync [options] SRC DEST
It seems the docs/tool have been updated and you can now add the image
tag to your script. This was successful for me.
Example:
version: '2'
services:
baggins.api.rest:
image: my.image.name:rc2
build:
context: ../..
dockerfile: app/Docker/Dockerfile.release
ports:
...
You'll want to use the GetExtensionName method on the FileSystemObject object.
Set x = CreateObject("scripting.filesystemobject")
WScript.Echo x.GetExtensionName("foo.pdf")
In your example, try using this
For Each objFile in colFiles
If UCase(objFSO.GetExtensionName(objFile.name)) = "PDF" Then
Wscript.Echo objFile.Name
End If
Next
relative position
, inside this parent you can set the absolute position
of your divs<div> <------Relative
<div/> <------Absolute
<div/> <------Absolute
<div/> <------Absolute
<div/>
Final result:
https://codepen.io/hiteshsahu/pen/XWKYEYb?editors=0100
<div class="container">
<div class="header">TOP: I am at Top & above of body container</div>
<div class="center">CENTER: I am at Top & in Center of body container</div>
<div class="footer">BOTTOM: I am at Bottom & above of body container</div>
</div>
Set HTML Body full width
html, body {
overflow: hidden;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
After that, you can set a div with the relative position to take full width and height
.container {
position: relative;
background-color: blue;
height: 100%;
width: 100%;
border:1px solid;
color: white;
background-image: url("https://images.pexels.com/photos/5591663/pexels-photo-5591663.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260");
background-color: #cccccc;
}
Inside this div with the relative position you can put your div with absolute positions
On TOP above the container
.header {
position: absolute;
margin-top: -10px;
background-color: #d81b60 ;
left:0;
right:0;
margin:15px;
padding:10px;
font-size: large;
}
On BOTTOM above the container
.footer {
position: absolute;
background-color: #00bfa5;
left:0;
right:0;
bottom:0;
margin:15px;
padding:10px;
color: white;
font-size: large;
}
In CENTER above the container
.center {
position: absolute;
background-color: #00bfa5;
left: 30%;
right: 30%;
bottom:30%;
top: 30%;
margin:10px;
padding:10px;
color: white;
font-size: large;
}
We will look at how the contents of this array are constructed and can be manipulated to affect where the Perl interpreter will find the module files.
Default @INC
Perl interpreter is compiled with a specific @INC
default value. To find out this value, run env -i perl -V
command (env -i
ignores the PERL5LIB
environmental variable - see #2) and in the output you will see something like this:
$ env -i perl -V ... @INC: /usr/lib/perl5/site_perl/5.18.0/x86_64-linux-thread-multi-ld /usr/lib/perl5/site_perl/5.18.0 /usr/lib/perl5/5.18.0/x86_64-linux-thread-multi-ld /usr/lib/perl5/5.18.0 .
Note .
at the end; this is the current directory (which is not necessarily the same as the script's directory). It is missing in Perl 5.26+, and when Perl runs with -T
(taint checks enabled).
To change the default path when configuring Perl binary compilation, set the configuration option otherlibdirs
:
Configure -Dotherlibdirs=/usr/lib/perl5/site_perl/5.16.3
Environmental variable PERL5LIB
(or PERLLIB
)
Perl pre-pends @INC
with a list of directories (colon-separated) contained in PERL5LIB
(if it is not defined, PERLLIB
is used) environment variable of your shell. To see the contents of @INC
after PERL5LIB
and PERLLIB
environment variables have taken effect, run perl -V
.
$ perl -V ... %ENV: PERL5LIB="/home/myuser/test" @INC: /home/myuser/test /usr/lib/perl5/site_perl/5.18.0/x86_64-linux-thread-multi-ld /usr/lib/perl5/site_perl/5.18.0 /usr/lib/perl5/5.18.0/x86_64-linux-thread-multi-ld /usr/lib/perl5/5.18.0 .
-I
command-line option
Perl pre-pends @INC
with a list of directories (colon-separated) passed as value of the -I
command-line option. This can be done in three ways, as usual with Perl options:
Pass it on command line:
perl -I /my/moduledir your_script.pl
Pass it via the first line (shebang) of your Perl script:
#!/usr/local/bin/perl -w -I /my/moduledir
Pass it as part of PERL5OPT
(or PERLOPT
) environment variable (see chapter 19.02 in Programming Perl)
Pass it via the lib
pragma
Perl pre-pends @INC
with a list of directories passed in to it via use lib
.
In a program:
use lib ("/dir1", "/dir2");
On the command line:
perl -Mlib=/dir1,/dir2
You can also remove the directories from @INC
via no lib
.
You can directly manipulate @INC
as a regular Perl array.
Note: Since @INC
is used during the compilation phase, this must be done inside of a BEGIN {}
block, which precedes the use MyModule
statement.
Add directories to the beginning via unshift @INC, $dir
.
Add directories to the end via push @INC, $dir
.
Do anything else you can do with a Perl array.
Note: The directories are unshifted onto @INC
in the order listed in this answer, e.g. default @INC
is last in the list, preceded by PERL5LIB
, preceded by -I
, preceded by use lib
and direct @INC
manipulation, the latter two mixed in whichever order they are in Perl code.
@INC
?There does not seem to be a comprehensive @INC
FAQ-type post on Stack Overflow, so this question is intended as one.
If the modules in a directory need to be used by many/all scripts on your site, especially run by multiple users, that directory should be included in the default @INC
compiled into the Perl binary.
If the modules in the directory will be used exclusively by a specific user for all the scripts that user runs (or if recompiling Perl is not an option to change default @INC
in previous use case), set the users' PERL5LIB
, usually during user login.
Note: Please be aware of the usual Unix environment variable pitfalls - e.g. in certain cases running the scripts as a particular user does not guarantee running them with that user's environment set up, e.g. via su
.
If the modules in the directory need to be used only in specific circumstances (e.g. when the script(s) is executed in development/debug mode, you can either set PERL5LIB
manually, or pass the -I
option to perl.
If the modules need to be used only for specific scripts, by all users using them, use use lib
/no lib
pragmas in the program itself. It also should be used when the directory to be searched needs to be dynamically determined during runtime - e.g. from the script's command line parameters or script's path (see the FindBin module for very nice use case).
If the directories in @INC
need to be manipulated according to some complicated logic, either impossible to too unwieldy to implement by combination of use lib
/no lib
pragmas, then use direct @INC
manipulation inside BEGIN {}
block or inside a special purpose library designated for @INC
manipulation, which must be used by your script(s) before any other modules are used.
An example of this is automatically switching between libraries in prod/uat/dev directories, with waterfall library pickup in prod if it's missing from dev and/or UAT (the last condition makes the standard "use lib + FindBin" solution fairly complicated. A detailed illustration of this scenario is in How do I use beta Perl modules from beta Perl scripts?.
An additional use case for directly manipulating @INC
is to be able to add subroutine references or object references (yes, Virginia, @INC
can contain custom Perl code and not just directory names, as explained in When is a subroutine reference in @INC called?).
You're running the code before the DOM is loaded.
Try this:
Live example:
$(function() { // Makes sure the code contained doesn't run until
// all the DOM elements have loaded
$('#colorselector').change(function(){
$('.colors').hide();
$('#' + $(this).val()).show();
});
});
You can get a vertical space even though you have NO WHITESPACE whatsoever between your inline-block elements.
For me, this was caused by line-height
. The simple fix was:
div.container {
line-height: 0;
}
div.container > * {
line-height: normal;
}
This is another great change from Google ... The suggested modification: replace onAttach(Activity activity)
with onAttach(Context context)
crashed my apps on older APIs since onAttach(Context context)
will not be called on native fragments.
I am using the native fragments (android.app.Fragment) so I had to do the following to make it work again on older APIs (< 23).
Here is what I did:
@Override
public void onAttach(Context context) {
super.onAttach(context);
// Code here
}
@SuppressWarnings("deprecation")
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
// Code here
}
}
Please note that in upcoming version of C# which is 8, the answers are not true.
All the reference types are non-nullable by default
and you can actually do the following:
public string? MyNullableString;
this.MyNullableString = null; //Valid
However,
public string MyNonNullableString;
this.MyNonNullableString = null; //Not Valid and you'll receive compiler warning.
The important thing here is to show the intent of your code. If the "intent" is that the reference type can be null, then mark it so otherwise assigning null value to non-nullable would result in compiler warning.
To the moderator who is deleting all the answers, don't do it. I strongly believe this answer adds value and deleting would simply keep someone from knowing what is right at the time. Since you have deleted all the answers, I'm re-posting answer here. The link that was sent regarding "duplicates" is simply an opening of some people and I do not think it is an official recommendation.
For the 24-hour time, you need to use HH24
instead of HH
.
For the 12-hour time, the AM/PM indicator is written as A.M.
(if you want periods in the result) or AM
(if you don't). For example:
SELECT invoice_date,
TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
FROM invoices
;
For more information on the format models you can use with TO_CHAR
on a date, see http://docs.oracle.com/cd/E16655_01/server.121/e17750/ch4datetime.htm#NLSPG004.
On Windows 2012 R2, you can't install Visual Studio or SDK. You can use powershell to register assemblies into GAC. It didn't need any special installation for me.
Set-location "C:\Temp"
[System.Reflection.Assembly]::Load("System.EnterpriseServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
$publish = New-Object System.EnterpriseServices.Internal.Publish
$publish.GacInstall("C:\Temp\myGacLibrary.dll")
If you need to get the name and PublicKeyToken see this question.
Check this out:
XAML:
<DataGrid Name="DataGrid1">
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Click="ChangeText">Show/Hide</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
Method:
private void ChangeText(object sender, RoutedEventArgs e)
{
DemoModel model = (sender as Button).DataContext as DemoModel;
model.DynamicText = (new Random().Next(0, 100).ToString());
}
Class:
class DemoModel : INotifyPropertyChanged
{
protected String _text;
public String Text
{
get { return _text; }
set { _text = value; RaisePropertyChanged("Text"); }
}
protected String _dynamicText;
public String DynamicText
{
get { return _dynamicText; }
set { _dynamicText = value; RaisePropertyChanged("DynamicText"); }
}
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(String propertyName)
{
PropertyChangedEventHandler temp = PropertyChanged;
if (temp != null)
{
temp(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Initialization Code:
ObservableCollection<DemoModel> models = new ObservableCollection<DemoModel>();
models.Add(new DemoModel() { Text = "Some Text #1." });
models.Add(new DemoModel() { Text = "Some Text #2." });
models.Add(new DemoModel() { Text = "Some Text #3." });
models.Add(new DemoModel() { Text = "Some Text #4." });
models.Add(new DemoModel() { Text = "Some Text #5." });
DataGrid1.ItemsSource = models;
Sounds to me like at least one of those tables has defined UserID
as a uniqueidentifier
, not an int
. Did you check the data in each table? What does SELECT TOP 1 UserID FROM
each table yield? An int
or a GUID
?
EDIT
I think you have built a procedure based on all tables that contain a column named UserID. I think you should not have included the aspnet_Membership
table in your script, since it's not really one of "your" tables.
If you meant to design your tables around the aspnet_Membership
database, then why are the rest of the columns int
when that table clearly uses a uniqueidentifier
for the UserID
column?
Just try this:
DF %>% t %>% na.omit %>% t
It transposes the data frame and omits null rows which were 'columns' before transposition and then you transpose it back.
James Curran succinctly says: "Switches based on integers can be optimized to very efficent code. Switches based on other data type can only be compiled to a series of if() statements. For that reason C & C++ only allow switches on integer types, since it was pointless with other types."
My opinion, and it's only that, is that as soon as you start switching on non-primitives you need to start thinking about "equals" versus "==". Firstly comparing two strings can be a fairly lengthy procedure, adding to the performance problems that are mentioned above. Secondly if there is switching on strings there will be demand for switching on strings ignoring case, switching on strings considering/ignoring locale,switching on strings based on regex.... I would approve of a decision that saved a lot of time for the language developers at the cost of a small amount of time for programmers.
This limitation (of Windows) should be publicly announced! The issue for me is the combination of the following: Windows 10 + AMD CPU (with AMD-V/SMV) +/- Hyper Visor
I have no issues running: Intel (with VT-x) + Linux or AMD (with AMD-V) + Linux
Link to Android studio issue here:
https://developer.android.com/studio/run/emulator.html#accel-vm
Xamarin/Visual Studio seems to have a workaround, but I haven't tested it yet:
If you need to use Hyper-V for other emulators then I'd recommend using the Microsoft Android Emulator instead, which uses Hyper-V and can also be used with Xamarin Studio/Visual Studio. You can download it for free from here.
I will update this after I confirm it works. Wish I would have known this before purchasing a new machine.
UPDATE!! It does not work "Requires Intel ..." error message is shown
Final note:
*Must be revision F3 or grater or must be F2 with BIOS support. Presence or absence of SVM Disable or other virtualization options in the bios does not ensure presence of BIOS support. You should contact the OEM to ensure support of Hyper-V.
*Some AMD BIOS's have options to enable/disable SVM (virtualization assistance)
*Some BIOS's list this as SVM Disable and it's a double negative, i.e. you want to disable SVM disable to enable SVM.
*Some BIOS's list this as Secure Virtualization, thus enabling Secure Virtualization will enable SVM
*Must have No-Execute enabled in the BIOS, sometime this is referred to as NX or Execute Disable
*If you want to find CPU's that are F3 see AMD's guide http://products.amd.com/en-us/DesktopCPUFilter.aspx or http://products.amd.com/en-us/OpteronCPUFilter.aspx?f1=Second-Generation+AMD+Opteron%e2%84%a2
I always use the time-stamp - so its not possible, that the file exists already:
import os
import shutil
import datetime
now = str(datetime.datetime.now())[:19]
now = now.replace(":","_")
src_dir="C:\\Users\\Asus\\Desktop\\Versand Verwaltung\\Versand.xlsx"
dst_dir="C:\\Users\\Asus\\Desktop\\Versand Verwaltung\\Versand_"+str(now)+".xlsx"
shutil.copy(src_dir,dst_dir)
Even if no convention is specified about this, manual references are consistently named after the referenced collection in the Mongo documentation, for one-to-one relations. The name always follows the structure <document>_id
.
For example, in a dogs
collection, a document would have manual references to external documents named like this:
{
name: 'fido',
owner_id: '5358e4249611f4a65e3068ab',
race_id: '5358ee549611f4a65e3068ac',
colour: 'yellow'
...
}
This follows the Mongo convention of naming _id
the identifier for every document.
If you like to get a list of all values of checked checkboxes (e.g. to send them as a list in one AJAX call to the server), you could get that list with:
var list = $("input[name='bla[]']:checked").map(function () {
return this.value;
}).get();
While the current Answer is right in most cases, there are certain situations that it will not give you the correct answer. If you use inside your script functions then:
$MyInvocation.MyCommand.Name
Returns the name of the function instead name of the name of the script.
function test {
$MyInvocation.MyCommand.Name
}
Will give you "test" no matter how your script is named. The right command for getting the script name is always
$MyInvocation.ScriptName
this returns the full path of the script you are executing. If you need just the script filename than this code should help you:
split-path $MyInvocation.PSCommandPath -Leaf
Maybe not the most efficient way. But you could convert the list into a vector.
#include <list>
#include <vector>
list<Object> myList;
vector<Object> myVector(myList.begin(), myList.end());
Then access the vector using the [x] operator.
auto x = MyVector[0];
You could put that in a helper function:
#include <memory>
#include <vector>
#include <list>
template<class T>
shared_ptr<vector<T>>
ListToVector(list<T> List) {
shared_ptr<vector<T>> Vector {
new vector<string>(List.begin(), List.end()) }
return Vector;
}
Then use the helper funciton like this:
auto MyVector = ListToVector(Object);
auto x = MyVector[0];
package all.is.well;_x000D_
import java.io.IOException;_x000D_
import java.io.RandomAccessFile;_x000D_
import java.util.concurrent.ExecutorService;_x000D_
import java.util.concurrent.Executors;_x000D_
import junit.framework.TestCase;_x000D_
_x000D_
/**_x000D_
* @author Naresh Bhabat_x000D_
* _x000D_
Following implementation helps to deal with extra large files in java._x000D_
This program is tested for dealing with 2GB input file._x000D_
There are some points where extra logic can be added in future._x000D_
_x000D_
_x000D_
Pleasenote: if we want to deal with binary input file, then instead of reading line,we need to read bytes from read file object._x000D_
_x000D_
_x000D_
_x000D_
It uses random access file,which is almost like streaming API._x000D_
_x000D_
_x000D_
* ****************************************_x000D_
Notes regarding executor framework and its readings._x000D_
Please note :ExecutorService executor = Executors.newFixedThreadPool(10);_x000D_
_x000D_
* for 10 threads:Total time required for reading and writing the text in_x000D_
* :seconds 349.317_x000D_
* _x000D_
* For 100:Total time required for reading the text and writing : seconds 464.042_x000D_
* _x000D_
* For 1000 : Total time required for reading and writing text :466.538 _x000D_
* For 10000 Total time required for reading and writing in seconds 479.701_x000D_
*_x000D_
* _x000D_
*/_x000D_
public class DealWithHugeRecordsinFile extends TestCase {_x000D_
_x000D_
static final String FILEPATH = "C:\\springbatch\\bigfile1.txt.txt";_x000D_
static final String FILEPATH_WRITE = "C:\\springbatch\\writinghere.txt";_x000D_
static volatile RandomAccessFile fileToWrite;_x000D_
static volatile RandomAccessFile file;_x000D_
static volatile String fileContentsIter;_x000D_
static volatile int position = 0;_x000D_
_x000D_
public static void main(String[] args) throws IOException, InterruptedException {_x000D_
long currentTimeMillis = System.currentTimeMillis();_x000D_
_x000D_
try {_x000D_
fileToWrite = new RandomAccessFile(FILEPATH_WRITE, "rw");//for random write,independent of thread obstacles _x000D_
file = new RandomAccessFile(FILEPATH, "r");//for random read,independent of thread obstacles _x000D_
seriouslyReadProcessAndWriteAsynch();_x000D_
_x000D_
} catch (IOException e) {_x000D_
// TODO Auto-generated catch block_x000D_
e.printStackTrace();_x000D_
}_x000D_
Thread currentThread = Thread.currentThread();_x000D_
System.out.println(currentThread.getName());_x000D_
long currentTimeMillis2 = System.currentTimeMillis();_x000D_
double time_seconds = (currentTimeMillis2 - currentTimeMillis) / 1000.0;_x000D_
System.out.println("Total time required for reading the text in seconds " + time_seconds);_x000D_
_x000D_
}_x000D_
_x000D_
/**_x000D_
* @throws IOException_x000D_
* Something asynchronously serious_x000D_
*/_x000D_
public static void seriouslyReadProcessAndWriteAsynch() throws IOException {_x000D_
ExecutorService executor = Executors.newFixedThreadPool(10);//pls see for explanation in comments section of the class_x000D_
while (true) {_x000D_
String readLine = file.readLine();_x000D_
if (readLine == null) {_x000D_
break;_x000D_
}_x000D_
Runnable genuineWorker = new Runnable() {_x000D_
@Override_x000D_
public void run() {_x000D_
// do hard processing here in this thread,i have consumed_x000D_
// some time and eat some exception in write method._x000D_
writeToFile(FILEPATH_WRITE, readLine);_x000D_
// System.out.println(" :" +_x000D_
// Thread.currentThread().getName());_x000D_
_x000D_
}_x000D_
};_x000D_
executor.execute(genuineWorker);_x000D_
}_x000D_
executor.shutdown();_x000D_
while (!executor.isTerminated()) {_x000D_
}_x000D_
System.out.println("Finished all threads");_x000D_
file.close();_x000D_
fileToWrite.close();_x000D_
}_x000D_
_x000D_
/**_x000D_
* @param filePath_x000D_
* @param data_x000D_
* @param position_x000D_
*/_x000D_
private static void writeToFile(String filePath, String data) {_x000D_
try {_x000D_
// fileToWrite.seek(position);_x000D_
data = "\n" + data;_x000D_
if (!data.contains("Randomization")) {_x000D_
return;_x000D_
}_x000D_
System.out.println("Let us do something time consuming to make this thread busy"+(position++) + " :" + data);_x000D_
System.out.println("Lets consume through this loop");_x000D_
int i=1000;_x000D_
while(i>0){_x000D_
_x000D_
i--;_x000D_
}_x000D_
fileToWrite.write(data.getBytes());_x000D_
throw new Exception();_x000D_
} catch (Exception exception) {_x000D_
System.out.println("exception was thrown but still we are able to proceeed further"_x000D_
+ " \n This can be used for marking failure of the records");_x000D_
//exception.printStackTrace();_x000D_
_x000D_
}_x000D_
_x000D_
}_x000D_
}
_x000D_
I have the almost the same situation as yours; that if the screen width is less than the my specified width it should hide the div. This is the jquery code I used that worked for me.
$(window).resize(function() {
if ($(this).width() < 1024) {
$('.divIWantedToHide').hide();
} else {
$('.divIWantedToHide').show();
}
});
Here's a creative idea using box-shadow
:
#header {
background-image: url("apple.jpg");
box-shadow: inset 0 0 99999px rgba(0, 120, 255, 0.5);
}
The background
sets the background for your element.
The box-shadow
is the important bit. It basically sets a really big shadow on the inside of the element, on top of the background, that is semi-transparent
It is not possible in the current standard. I believe you'll be able to do this in C++0x using initializer lists (see A Brief Look at C++0x, by Bjarne Stroustrup, for more information about initializer lists and other nice C++0x features).
If you want to use a string key generated in your Node.js program, say, var v = 'HOME'
, you can use
process.env[v]
.
Otherwise, process.env.VARNAME
has to be hardcoded in your program.
For less
use -u
to display carriage returns (^M
) and backspaces (^H
), or -U
to show the previous and tabs (^I
) for example:
$ awk 'BEGIN{print "foo\bbar\tbaz\r\n"}' | less -U
foo^Hbar^Ibaz^M
(END)
Without the -U
switch the output would be:
fobar baz
(END)
See man less
for more exact description on the features.
Treb, Matthieu's problem was caused by using Excel in a non-English language. In many language versions ";" is the correct separator. Even functions are translated (SUM can be SOMMA, SUMME or whatever depending on what language you work in). Excel will generally understand these differences and if a French-created workbook is opened by a Brazilian they will normally not have any problem. But VBA speaks only US English so for those of us working in one (or more) foreign langauges, this can be a headache. You and CharlesB both gave answers that would have been OK for a US user but Mikko understod the REAL problem and gave the correct answer (which was also the correct one for me too - I'm a Brit working in Italy for a German-speaking company).
I think that your question is not defined well enough, for the following reason.
Answers relying on months_between have to deal with the following issue: that the function reports exactly one month between 2013-02-28 and 2013-03-31, and between 2013-01-28 and 2013-02-28, and between 2013-01-31 and 2013-02-28 (I suspect that some answerers have not used these functions in practice, or are now going to have to review some production code!)
This is documented behaviour, in which dates that are both the last in their respective months or which fall on the same day of the month are judged to be an integer number of months apart.
So, you get the same result of "1" when comparing 2013-02-28 with 2013-01-28 or with 2013-01-31, but comparing it with 2013-01-29 or 2013-01-30 gives 0.967741935484 and 0.935483870968 respectively -- so as one date approaches the other the difference reported by this function can increase.
If this is not an acceptable situation then you'll have to write a more complex function, or just rely on a calculation that assumes 30 (for example) days per month. In the latter case, how will you deal with 2013-02-28 and 2013-03-31?
Fixed by adding crossorigin to the script tag.
From: https://code.jquery.com/
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
The integrity and crossorigin attributes are used for Subresource Integrity (SRI) checking. This allows browsers to ensure that resources hosted on third-party servers have not been tampered with. Use of SRI is recommended as a best-practice, whenever libraries are loaded from a third-party source. Read more at srihash.org
I have seen most of the people saying explicit parent to child casting is not possible, that actually is not true. Let's take a revised start and try proving it by examples.
As we know in .net all castings have two broad categories.
Reference type has further three main situational cases in which any scenario can lie.
Case 1. Child to any direct or indirect parent
Employee e = new Employee();
Person p = (Person)e; //Allowed
Case 2. Parent variable holding parent object (Not allowed)
Person p = new Person(); // p is true Person object
Employee e = (Employee)p; //Runtime err : InvalidCastException <-------- Yours issue
Case 3. Parent variable holding child object (Always Successful)
Note: Because objects has polymorphic nature, it is possible for a variable of a parent class type to hold a child type.
Person p = new Employee(); // p actually is Employee
Employee e = (Employee)p; // Casting allowed
Conclusion : After reading above all, hope it will make sense now like how parent to child conversion is possible(Case 3).
Answer To The Question :
Your answer is in case 2.Where you can see such casting is not allowed by OOP and you are trying to violate one of OOP's basic rule.So always choose safe path.
Further more, to avoid such exceptional situations .net has recommended using is/as operators those will help you to take informed decisions and provide safe casting.
In our case, we receive an XML as a String
and need to get rid of the values that have some "special" characters, like &<>
etc. Basically someone can provide an XML to us in this form:
<notes>
<note>
<to>jenice & carl </to>
<from>your neighbor <; </from>
</note>
</notes>
So I need to find in that String
the values jenice & carl
and your neighbor <;
and properly escape &
and <
(otherwise this is an invalid xml if you later pass it to an engine that shall rename unnamed).
Doing this with regex is a rather dumb idea to begin with, but it's cheap and easy. So the brave ones that would like to do the same thing I did, here you go:
String xml = ...
Pattern p = Pattern.compile("<(.+)>(?!\\R<)(.+)</(\\1)>");
Matcher m = p.matcher(xml);
String result = m.replaceAll(mr -> {
if (mr.group(2).contains("&")) {
return "<" + m.group(1) + ">" + m.group(2) + "+ some change" + "</" + m.group(3) + ">";
}
return "<" + m.group(1) + ">" + mr.group(2) + "</" + m.group(3) + ">";
});
//@parram $data-array,$d-if true then die by default it is false
//@author Your name
function p($data,$d = false){
echo "<pre>";
print_r($data);
echo "</pre>";
if($d == TRUE){
die();
}
} // END OF FUNCTION
Use this function every time whenver you need to string or array it will wroks just GREAT.
There are 2 Patameters
1.$data - It can be Array or String
2.$d - By Default it is FALSE but if you set to true then it will execute die() function
In your case you can use in this way....
while($row = mysql_fetch_array($result)){
p($row); // Use this function if you use above function in your page.
}
All in all, I'd say that MD5 in addition to the file name is absolutely safe. SHA-256 would just be slower and harder to handle because of its size.
You could also use something less secure than MD5 without any problem. If nobody tries to hack your file integrity this is safe, too.
Problem was solved by myself using tutorial of weheartswift
Another solution would be to pass the textbox (or control you want to modify) into the method that will manipulate it as a parameter.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
TestClass test = new TestClass();
test.ModifyText(textBox1);
}
}
public class TestClass
{
public void ModifyText(TextBox textBox)
{
textBox.Text = "New text";
}
}
I am not quite sure why Martin R's answer in the comments for the question is so disregarded:
Make sure that you tried simply skipping import of the framework as it is already added with the bridging header.
Hope this helps
The "set_map
" function posted in both answers appears to no longer work in Google Maps v3 API.
I wonder what happened
Update:
It appears Google changed their API such that "set_map
" is not "setMap
".
http://code.google.com/apis/maps/documentation/v3/reference.html
You can install pip
(or any other package) with easy_install
almost as described in the first answer. However you will need a HTTPS
proxy, too. The full sequence of commands is:
set http_proxy=http://proxy.myproxy.com
set https_proxy=http://proxy.myproxy.com
easy_install pip
You might also want to add a port to the proxy, such as http{s}_proxy=http://proxy.myproxy.com:8080
You can say word.strip(" ")
to remove any leading/trailing spaces from the string - you should do that before your if
statement. That way if someone enters input such as " test "
your program will still work.
That said, if " " in word:
will determine if a string contains any spaces. If that does not working, can you please provide more information?
To create a new branch (locally):
With the commit hash (or part of it)
git checkout -b new_branch 6e559cb
or to go back 4 commits from HEAD
git checkout -b new_branch HEAD~4
Once your new branch is created (locally), you might want to replicate this change on a remote of the same name: How can I push my changes to a remote branch
For discarding the last three commits, see Lunaryorn's answer below.
For moving your current branch HEAD to the specified commit without creating a new branch, see Arpiagar's answer below.
This works reliably for me in my main sub.
Dim defDate1 As Date, defDate2 As Date
'** Set default date range to previous month
defDate1 = CDate(Month(Now) & "/1/" & Year(Now))
defDate1 = DateAdd("m", -1, defDate1)
defDate2 = DateAdd("d", -1, DateAdd("m", 1, defDate1))
why don't you try pip list
Remember I'm using pip version 19.1 on python version 3.7.3
You can try following way
<input type= "file" name="Upload" accept = "application/pdf,.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel">
OR (in asp.net mvc)
@Html.TextBoxFor(x => x.FileName, new { @id = "doc", @type = "file", @accept = "application/pdf,.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" })
Expanding on @gecco 's answer, the following is an example that'll show you the difference:
def foo(**kwargs):
for entry in kwargs.items():
print("Key: {}, value: {}".format(entry[0], entry[1]))
# call using normal keys:
foo(a=1, b=2, c=3)
# call using an unpacked dictionary:
foo(**{"a": 1, "b":2, "c":3})
# call using a dictionary fails because the function will think you are
# giving it a positional argument
foo({"a": 1, "b": 2, "c": 3})
# this yields the same error as any other positional argument
foo(3)
foo("string")
Here you can see how unpacking a dictionary works, and why sending an actual dictionary fails
In my case, I'm using http interceptor, thing is that by default my http interceptor sets content-type
header as application/json
, but for file uploading I'm using multer library.
So little bit changing my http.interceptor defines if request body is FormData it removes headers and doesn't touch access token.
Here is part of code, which made my day.
if (request.body instanceof FormData) {
request = request.clone({ headers: request.headers.delete('Content-Type', 'application/json') });
}
if (request.body instanceof FormData) {
request = request.clone({ headers: request.headers.delete('Accept', 'application/json')});
}
You can try using parentheses around the OR expressions to make sure your query is interpreted correctly, or more concisely, use IN:
SELECT ads.*, location.county
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1
AND ads.type = 13
AND ads.county_id IN (2,5,7,9)
If you want to use @Html.EditorFor() you have to use jQuery ui and update your Asp.net Mvc to 5.2.6.0 with NuGet Package Manager.
@Html.EditorFor(m => m.EntryDate, new { htmlAttributes = new { @class = "datepicker" } })
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script>
$(document).ready(function(){
$('.datepicker').datepicker();
});
</script>
}
I've several plugins (including Unicode Character Highlighter), but the only one which found the character that was hiding from me today was Highlighter.
You can test to see if it's working by pasting in the text from the readme.
For reference, the character causing me trouble was ?
.
For a sanity check, tap your right arrow key over a range of text containing an invisible character, and you'll need to right-arrow twice to move past the character.
I'm also using the following custom regex string (which I don't fully grok):
{
// there's an extra range in use [^\\x00-\\x7F]
// also, don't highlight spaces at the end of the line (my settings take care of that)
"highlighter_regex": "(\t+ +)|( +\t+)|[^\\x00-\\x7F]|[\u2026\u2018\u2019\u201c\u201d\u2013\u2014]"
}
A (MySQLdb/PyMySQL-specific) difference worth noting when using a DictCursor
is that list(cursor)
will always give you a list, while cursor.fetchall()
gives you a list unless the result set is empty, in which case it gives you an empty tuple. This was the case in MySQLdb and remains the case in the newer PyMySQL, where it will not be fixed for backwards-compatibility reasons. While this isn't a violation of Python Database API Specification, it's still surprising and can easily lead to a type error caused by wrongly assuming that the result is a list, rather than just a sequence.
Given the above, I suggest always favouring list(cursor)
over cursor.fetchall()
, to avoid ever getting caught out by a mysterious type error in the edge case where your result set is empty.
For Windows 7 and up, scheduled tasks are not run by cmd.exe
, but rather by MMC
(Microsoft Management Console). %SystemRoot%\Tasks
should work on any other Windows version though.
The only way is to modify the file src/http/ngx_http_header_filter_module.c . I changed nginx on line 48 to a different string.
What you can do in the nginx config file is to set server_tokens to off. This will prevent nginx from printing the version number.
To check things out, try curl -I http://vurbu.com/ | grep Server
It should return
Server: Hai
One option is, you can wrap the submit
button with a form
Something like this:
<form action="{% url path.to.request_page %}" method="POST">
<input id="submit" type="button" value="Click" />
</form>
(remove the onclick
and method
)
If you want to load a specific part of the page, without page reload - you can do
<input id="submit" type="button" value="Click" data_url/>
and on a submit
listener
$(function(){
$('form').on('submit', function(e){
e.preventDefault();
$.ajax({
url: $(this).attr('action'),
method: $(this).attr('method'),
success: function(data){ $('#target').html(data) }
});
});
});
At least in Python3 you also can do this:
import os, re, glob
path = '/home/my/path'
files = glob.glob(os.path.join(path, '*.png'))
files.sort(key=lambda x:[int(c) if c.isdigit() else c for c in re.split(r'(\d+)', x)])
for infile in files:
print(infile)
This should lexicographically order your input array of strings (e.g. respect numbers in strings while ordering).
The following lines are used to control the listen-port of a server, both are necessary:
<listen-port>7002</listen-port>
<listen-port-enabled>true</listen-port-enabled>
I used ColorDialog in my project. ColorDialog sometimess return "Red","Fhushia" and sometimes return "fff000". I solved this problem like this maybe help someone.
SolidBrush guideLineColor;
if (inputColor.Any(c => char.IsDigit(c)))
{
string colorcode = inputColor;
int argbInputColor = Int32.Parse(colorcode.Replace("#", ""), NumberStyles.HexNumber);
guideLineColor = new SolidBrush(Color.FromArgb(argbInputColor));
}
else
{
Color col = Color.FromName(inputColor);
guideLineColor = new SolidBrush(col);
}
InputColor is the return value from ColorDialog.
Thanks everyone for answer this question.It's big help to me.
Using fs-extra, which promises the async fs calls, and the new await async syntax:
const fs = require("fs-extra");
async function getDirectories(path){
let filesAndDirectories = await fs.readdir(path);
let directories = [];
await Promise.all(
filesAndDirectories.map(name =>{
return fs.stat(path + name)
.then(stat =>{
if(stat.isDirectory()) directories.push(name)
})
})
);
return directories;
}
let directories = await getDirectories("/")
Go to options->Advanced->Network->Settings->Automatic proxy configuration url and enter 8.8.8.8 All you Mozilla traffic uses Google dns now.
var=$((count7 + count1))
Arithmetic in bash uses $((...))
syntax.
You do not need to $
symbol within the $(( ))
Sounds to me like you don't have your web.config authorization section set up properly within . See below for an example.
<authentication mode="Forms">
<forms name="MyCookie" loginUrl="Login.aspx" protection="All" timeout="90" slidingExpiration="true"></forms>
</authentication>
<authorization>
<deny users="?" />
</authorization>
This is one of those instances where jquery actually makes it more complicated than what the DOM already provides.
let { top, bottom, height, width, //etc } = $('#bottom')[0].getBoundingClientRect();
return top;
Yes we can have an abstract class without Abstract Methods as both are independent concepts. Declaring a class abstract means that it can not be instantiated on its own and can only be sub classed. Declaring a method abstract means that Method will be defined in the subclass.
I used back.png image in the project menifest.xml file. it is fine working in project.
<activity
android:name=".YourActivity"
android:icon="@drawable/back"
android:label="@string/app_name" >
</activity>
add into angular-cli.json
"styles": [
"../node_modules/bootstrap/dist/css/bootstrap.min.css",
"styles.css"
],
"scripts": [
"../node_modules/bootstrap/dist/js/bootstrap.js"
],
It will be work, i checked it.