If you want to use substr()
, you can easily add the dashes or slashes like this..
$datetime = "20130409163705";
$yyyy = substr($datetime,0,4);
$mm = substr($datetime,4,6);
$dd = substr($datetime,6,8);
$hh = substr($datetime,8,10);
$MM = substr($datetime,10,12);
$ss = substr($datetime,12,14);
$dt_formatted = $mm."/".$dd."/".$yyyy." ".$hh.":".$MM.":".$ss;
You can figure out any further formatting from that point.
I wanted to point out that when using data from the server via Ajax, the solution is super simple, but may not be immediately obvious.
When returning the sort order array, Datatables will send (in the $_POST
) a 2 element array that would be equivalent to:
$_POST['order'][0] =array('column'=>'SortColumnName', 'dir'=>'asc');
// 2nd element is either 'asc' or 'desc'
Therefore, you may display the date in any format you want; just have your server return the sorting criteria based only upon the sortColumnName
.
For example, in PHP (with MySQL), I use the following:
if (isset($_POST['order'])) {
switch ($_POST['order'][0]['column']) {
case 0:// sort by Primary Key
$order = 'pkItemid';
break;
case 1:// Sort by reference number
$order = 'refNo';
break;
case 2://Date Started
$order = 'dOpen';
break;
default :
$order = 'pkItemid';
}
$orderdir = ($_POST['order'][0]['dir'] === 'desc') ? 'desc' : 'asc';
}
Note, that since nothing from the $_POST
is passed to $order
or $orderdir
, no cross-script attack is possible.
Now, just append to a MySQL query:
$sql ="SELECT pkItemid, refNo, DATE_FORMAT(dOpen,'%b %e, %Y') AS dateStarted
FROM tblReference
ORDER BY $order $orderdir;";
run the query, and return just the dateStarted
value to Datatables in json.
MongoDB query with an 'or' condition
db.getCollection('movie').find({$or:[{"type":"smartreply"},{"category":"small_talk"}]})
MongoDB query with an 'or', 'and', condition combined.
db.getCollection('movie').find({"applicationId":"2b5958d9629026491c30b42f2d5256fa8",$or:[{"type":"smartreply"},{"category":"small_talk"}]})
It'll be because response[0]
itself is undefined.
Wrong syntax. Here you are:
insert into user_by_category (game_category,customer_id) VALUES ('Goku','12');
or:
insert into user_by_category ("game_category","customer_id") VALUES ('Kakarot','12');
The second one is normally used for case-sensitive column names.
try this C# code to drop your database
public static void DropDatabases(string dataBase) {
string sql = "ALTER DATABASE " + dataBase + "SET SINGLE_USER WITH ROLLBACK IMMEDIATE" ;
using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["DBRestore"].ConnectionString))
{
connection.Open();
using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(sql, connection))
{
command.CommandType = CommandType.Text;
command.CommandTimeout = 7200;
command.ExecuteNonQuery();
}
sql = "DROP DATABASE " + dataBase;
using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(sql, connection))
{
command.CommandType = CommandType.Text;
command.CommandTimeout = 7200;
command.ExecuteNonQuery();
}
}
}
UNION removes duplicate records in other hand UNION ALL does not. But one need to check the bulk of data that is going to be processed and the column and data type must be same.
since union internally uses "distinct" behavior to select the rows hence it is more costly in terms of time and performance. like
select project_id from t_project
union
select project_id from t_project_contact
this gives me 2020 records
on other hand
select project_id from t_project
union all
select project_id from t_project_contact
gives me more than 17402 rows
on precedence perspective both has same precedence.
String s1 = "Welcome"; // Does not create a new instance
String s2 = new String("Welcome"); // Creates two objects and one reference variable
Regarding your responses, the CSS link is written akin to other head elements.
<head>
<link href="css.script " rel="stylesheet" />
</head>
1.Most popularly put in the head as it will augment compiling proficiency. 2.Placed in the body or later in the HTML text primarily for convenience.
Android needs to be compiled for every hardware plattform / every device model seperatly with the specific drivers etc. If you manage to do that you need also break the security arrangements every manufacturer implements to prevent the installation of other software - these are also different between each model / manufacturer. So it is possible at in theory, but only there :-)
git pull origin master
will pull changes from the origin
remote, master
branch and merge them to the local checked-out branch.
git pull origin/master
will pull changes from the locally stored branch origin/master
and merge that to the local checked-out branch. The origin/master
branch is essentially a "cached copy" of what was last pulled from origin
, which is why it's called a remote branch in git parlance. This might be somewhat confusing.
You can see what branches are available with git branch
and git branch -r
to see the "remote branches".
I had a similar error but with different context when I uploaded a *.p file to Google Drive. I tried to use it later in a Google Colab session, and got this error:
1 with open("/tmp/train.p", mode='rb') as training_data:
----> 2 train = pickle.load(training_data)
UnpicklingError: invalid load key, '<'.
I solved it by compressing the file, upload it and then unzip on the session. It looks like the pickle file is not saved correctly when you upload/download it so it gets corrupted.
As defined in APC Document:
To clear the cache run:
php -r 'function_exists("apc_clear_cache") ? apc_clear_cache() : null;'
infile = open('filename.txt', 'r')
firstLine = infile.readline()
I have the same error. Not sure why it happened. But I managed to upgrade by running:
pip install setuptools --upgrade --ignore-installed
After that, I used a PowerShell
or Command Prompt
- cmd in administrator mode to install the package:
pip install the-package
# or
easy_install the-package
Also, what they have already suggested: Installing packages using pip and virtual environments , which is the best practice for new projects.
If you want the whole GitHub repository name ('full name') - user/repository, and you want to do it in with Ruby...
git remote show origin -n | ruby -ne 'puts /^\s*Fetch.*:(.*).git/.match($_)[1] rescue nil'
window load will wait for all resources to be loaded.
document ready waits for the document to be initialized.
unload well, waits till the document is being unloaded.
the order is: document ready, window load, ... ... ... ... window unload.
always use document ready unless you need to wait for your images to load.
shorthand for document ready:
$(function(){
// yay!
});
Your requirements are all over the place, but this is the solution to my understanding of them:
To group by Reference property:
var refGroupQuery = (from m in context.Measurements
group m by m.Reference into refGroup
select refGroup);
Now you say you want to limit results by "most recent numOfEntries" - I take this to mean you want to limit the returned Measurements... in that case:
var limitedQuery = from g in refGroupQuery
select new
{
Reference = g.Key,
RecentMeasurements = g.OrderByDescending( p => p.CreationTime ).Take( numOfEntries )
}
To order groups by first Measurement creation time (note you should order the measurements; if you want the earliest CreationTime value, substitue "g.SomeProperty" with "g.CreationTime"):
var refGroupsOrderedByFirstCreationTimeQuery = limitedQuery.OrderBy( lq => lq.RecentMeasurements.OrderBy( g => g.SomeProperty ).First().CreationTime );
To order groups by average CreationTime, use the Ticks property of the DateTime struct:
var refGroupsOrderedByAvgCreationTimeQuery = limitedQuery.OrderBy( lq => lq.RecentMeasurements.Average( g => g.CreationTime.Ticks ) );
It will depend on your environment. If you're running a Swing UI via javaw
for example, then there isn't a console to display. If you're running within an IDE, it will very much depend on the specific IDE's handling of console IO.
From the command line, it should be fine though. Sample:
import java.io.Console;
public class Test {
public static void main(String[] args) throws Exception {
Console console = System.console();
if (console == null) {
System.out.println("Unable to fetch console");
return;
}
String line = console.readLine();
console.printf("I saw this line: %s", line);
}
}
Run this just with java
:
> javac Test.java
> java Test
Foo <---- entered by the user
I saw this line: Foo <---- program output
Another option is to use System.in
, which you may want to wrap in a BufferedReader
to read lines, or use Scanner
(again wrapping System.in
).
I'm still having problems figuring out exactly how I find out what a user is typing into a ckeditor textarea.
Ok, this is fairly easy. Assuming your editor is named "editor1", this will give you an alert with your its contents:
alert(CKEDITOR.instances.editor1.getData());
The harder part is detecting when the user types. From what I can tell, there isn't actually support to do that (and I'm not too impressed with the documentation btw). See this article: http://alfonsoml.blogspot.com/2011/03/onchange-event-for-ckeditor.html
Instead, I would suggest setting a timer that is going to continuously update your second div with the value of the textarea:
timer = setInterval(updateDiv,100);
function updateDiv(){
var editorText = CKEDITOR.instances.editor1.getData();
$('#trackingDiv').html(editorText);
}
This seems to work just fine. Here's the entire thing for clarity:
<textarea id="editor1" name="editor1">This is sample text</textarea>
<div id="trackingDiv" ></div>
<script type="text/javascript">
CKEDITOR.replace( 'editor1' );
timer = setInterval(updateDiv,100);
function updateDiv(){
var editorText = CKEDITOR.instances.editor1.getData();
$('#trackingDiv').html(editorText);
}
</script>
Another approach, which is clean and will keep the document valid, is to concatenate the data you want into another tag e.g. id, then use split to take what you want when you want it.
<html>
<script>
function demonstrate(){
var x = document.getElementById("example data").querySelectorAll("input");
console.log(x);
for(i=0;i<x.length;i++){
var line_to_illustrate = x[i].id + ":" + document.getElementById ( x[i].id ).value;
//concatenated values
console.log("this is all together: " + line_to_illustrate);
//split values
var split_line_to_illustrate = line_to_illustrate.split(":");
for(j=0;j<split_line_to_illustrate.length;j++){
console.log("item " + j+ " is: " + split_line_to_illustrate[j]);
}
}
}
</script>
<body>
<div id="example data">
<!-- consider the id values representing a 'from-to' relationship -->
<input id="1:2" type="number" name="quantity" min="0" max="9" value="2">
<input id="1:4" type="number" name="quantity" min="0" max="9" value="1">
<input id="3:6" type="number" name="quantity" min="0" max="9" value="5">
</div>
<input type="button" name="" id="?" value="show me" onclick="demonstrate()"/>
</body>
</html>
$(function(){
$('.modal-content').keypress(function(e){
debugger
var id = this.children[2].children[0].id;
if(e.which == 13) {
e.preventDefault();
$("#"+id).click();
}
})
});
Of course there is. Check out mysql_query
, and mysql_fetch_row
if you use MySQL.
Example from PHP manual:
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
from app import SQLAlchemyDB as db
Chance.query.filter(Chance.repo_id==repo_id,
Chance.status=="1",
db.func.date(Chance.apply_time)<=end,
db.func.date(Chance.apply_time)>=start).count()
it is equal to:
select
count(id)
from
Chance
where
repo_id=:repo_id
and status='1'
and date(apple_time) <= end
and date(apple_time) >= start
wish can help you.
Please add attribute useLegacyV2RuntimeActivationPolicy="true" in your applications app.config file.
Old Value
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1"/>
</startup>
New Value
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1"/>
</startup>
It will solve your problem.
Try this one:
Sub clear_sht
Dim sht As Worksheet
Set sht = Worksheets(GENERATOR_SHT_NAME)
col_cnt = sht.UsedRange.Columns.count
If col_cnt = 0 Then
col_cnt = 1
End If
sht.Range(sht.Cells(1, 1), sht.Cells(sht.UsedRange.Rows.count, col_cnt)).Clear
End Sub
In case that you have Ubuntu in your machine, the following steps will help you:
Open your terminal and paste: sudo apt-get install php-soap.
Restart your apache2 server in terminal : service apache2 restart.
To check use your php test file again to be seems like mine in step 1.
The answers provided by Bohzo and Brabster will obviously work, but you could also just use:
rs3.getInt(1);
to get the value in the first, and in your case, only column.
Simple solution not sure if this has been suggested or not. This also may not work for some things. That being said this is the simple solution below.
new SelectListItem { Value = "1", Text = "Waiting Invoices", Selected = true}
List<SelectListItem> InvoiceStatusDD = new List<SelectListItem>();
InvoiceStatusDD.Add(new SelectListItem { Value = "0", Text = "All Invoices" });
InvoiceStatusDD.Add(new SelectListItem { Value = "1", Text = "Waiting Invoices", Selected = true});
InvoiceStatusDD.Add(new SelectListItem { Value = "7", Text = "Client Approved Invoices" });
@Html.DropDownList("InvoiceStatus", InvoiceStatusDD)
You can also do something like this for a database driven select list. you will need to set selected in your controller
@Html.DropDownList("ApprovalProfile", (IEnumerable<SelectListItem>)ViewData["ApprovalProfiles"], "All Employees")
Something like this but better solutions exist this is just one method.
foreach (CountryModel item in CountryModel.GetCountryList())
{
if (item.CountryPhoneCode.Trim() != "974")
{
countries.Add(new SelectListItem { Text = item.CountryName + " +(" + item.CountryPhoneCode + ")", Value = item.CountryPhoneCode });
}
else {
countries.Add(new SelectListItem { Text = item.CountryName + " +(" + item.CountryPhoneCode + ")", Value = item.CountryPhoneCode,Selected=true });
}
}
for using git you have to be
root
if not then use sudo
for removing origin :
git remote remove origin
for adding origin :
git remote add origin http://giturl
Specify the type of the pointer to your comparison function as the 3rd type into the map, and provide the function pointer to the map constructor:
map<keyType, valueType, typeOfPointerToFunction> mapName(pointerToComparisonFunction);
Take a look at the example below for providing a comparison function to a map
, with vector
iterator as key and int
as value.
#include "headers.h"
bool int_vector_iter_comp(const vector<int>::iterator iter1, const vector<int>::iterator iter2) {
return *iter1 < *iter2;
}
int main() {
// Without providing custom comparison function
map<vector<int>::iterator, int> default_comparison;
// Providing custom comparison function
// Basic version
map<vector<int>::iterator, int,
bool (*)(const vector<int>::iterator iter1, const vector<int>::iterator iter2)>
basic(int_vector_iter_comp);
// use decltype
map<vector<int>::iterator, int, decltype(int_vector_iter_comp)*> with_decltype(&int_vector_iter_comp);
// Use type alias or using
typedef bool my_predicate(const vector<int>::iterator iter1, const vector<int>::iterator iter2);
map<vector<int>::iterator, int, my_predicate*> with_typedef(&int_vector_iter_comp);
using my_predicate_pointer_type = bool (*)(const vector<int>::iterator iter1, const vector<int>::iterator iter2);
map<vector<int>::iterator, int, my_predicate_pointer_type> with_using(&int_vector_iter_comp);
// Testing
vector<int> v = {1, 2, 3};
default_comparison.insert(pair<vector<int>::iterator, int>({v.end(), 0}));
default_comparison.insert(pair<vector<int>::iterator, int>({v.begin(), 0}));
default_comparison.insert(pair<vector<int>::iterator, int>({v.begin(), 1}));
default_comparison.insert(pair<vector<int>::iterator, int>({v.begin() + 1, 1}));
cout << "size: " << default_comparison.size() << endl;
for (auto& p : default_comparison) {
cout << *(p.first) << ": " << p.second << endl;
}
basic.insert(pair<vector<int>::iterator, int>({v.end(), 0}));
basic.insert(pair<vector<int>::iterator, int>({v.begin(), 0}));
basic.insert(pair<vector<int>::iterator, int>({v.begin(), 1}));
basic.insert(pair<vector<int>::iterator, int>({v.begin() + 1, 1}));
cout << "size: " << basic.size() << endl;
for (auto& p : basic) {
cout << *(p.first) << ": " << p.second << endl;
}
with_decltype.insert(pair<vector<int>::iterator, int>({v.end(), 0}));
with_decltype.insert(pair<vector<int>::iterator, int>({v.begin(), 0}));
with_decltype.insert(pair<vector<int>::iterator, int>({v.begin(), 1}));
with_decltype.insert(pair<vector<int>::iterator, int>({v.begin() + 1, 1}));
cout << "size: " << with_decltype.size() << endl;
for (auto& p : with_decltype) {
cout << *(p.first) << ": " << p.second << endl;
}
with_typedef.insert(pair<vector<int>::iterator, int>({v.end(), 0}));
with_typedef.insert(pair<vector<int>::iterator, int>({v.begin(), 0}));
with_typedef.insert(pair<vector<int>::iterator, int>({v.begin(), 1}));
with_typedef.insert(pair<vector<int>::iterator, int>({v.begin() + 1, 1}));
cout << "size: " << with_typedef.size() << endl;
for (auto& p : with_typedef) {
cout << *(p.first) << ": " << p.second << endl;
}
}
There still is the old C way of providing optional arguments: a pointer that can be NULL when not present:
void write( int *optional = 0 ) {
if (optional) *optional = 5;
}
New ways I: fetch
TL;DR I'd recommend this way as long as you don't have to send synchronous requests or support old browsers.
A long as your request is asynchronous you can use the Fetch API to send HTTP requests. The fetch API works with promises, which is a nice way to handle asynchronous workflows in JavaScript. With this approach you use fetch()
to send a request and ResponseBody.json()
to parse the response:
fetch(url)
.then(function(response) {
return response.json();
})
.then(function(jsonResponse) {
// do something with jsonResponse
});
Compatibility: The Fetch API is not supported by IE11 as well as Edge 12 & 13. However, there are polyfills.
New ways II: responseType
As Londeren has written in his answer, newer browsers allow you to use the responseType
property to define the expected format of the response. The parsed response data can then be accessed via the response
property:
var req = new XMLHttpRequest();
req.responseType = 'json';
req.open('GET', url, true);
req.onload = function() {
var jsonResponse = req.response;
// do something with jsonResponse
};
req.send(null);
Compatibility: responseType = 'json'
is not supported by IE11.
The classic way
The standard XMLHttpRequest has no responseJSON
property, just responseText
and responseXML
. As long as bitly really responds with some JSON to your request, responseText
should contain the JSON code as text, so all you've got to do is to parse it with JSON.parse()
:
var req = new XMLHttpRequest();
req.overrideMimeType("application/json");
req.open('GET', url, true);
req.onload = function() {
var jsonResponse = JSON.parse(req.responseText);
// do something with jsonResponse
};
req.send(null);
Compatibility: This approach should work with any browser that supports XMLHttpRequest
and JSON
.
JSONHttpRequest
If you prefer to use responseJSON
, but want a more lightweight solution than JQuery, you might want to check out my JSONHttpRequest. It works exactly like a normal XMLHttpRequest, but also provides the responseJSON
property. All you have to change in your code would be the first line:
var req = new JSONHttpRequest();
JSONHttpRequest also provides functionality to easily send JavaScript objects as JSON. More details and the code can be found here: http://pixelsvsbytes.com/2011/12/teach-your-xmlhttprequest-some-json/.
Full disclosure: I'm the owner of Pixels|Bytes. I thought that my script was a good solution for the original question, but it is rather outdated today. I do not recommend to use it anymore.
Use crosstab()
from the tablefunc module.
SELECT * FROM crosstab(
$$SELECT user_id, user_name, rn, email_address
FROM (
SELECT u.user_id, u.user_name, e.email_address
, row_number() OVER (PARTITION BY u.user_id
ORDER BY e.creation_date DESC NULLS LAST) AS rn
FROM usr u
LEFT JOIN email_tbl e USING (user_id)
) sub
WHERE rn < 4
ORDER BY user_id
$$
, 'VALUES (1),(2),(3)'
) AS t (user_id int, user_name text, email1 text, email2 text, email3 text);
I used dollar-quoting for the first parameter, which has no special meaning. It's just convenient if you have to escape single quotes in the query string which is a common case:
Detailed explanation and instructions here:
And in particular, for "extra columns":
The special difficulties here are:
The lack of key names.
-> We substitute with row_number()
in a subquery.
The varying number of emails.
-> We limit to a max. of three in the outer SELECT
and use crosstab()
with two parameters, providing a list of possible keys.
Pay attention to NULLS LAST
in the ORDER BY
.
You can try this:
return redirect()->back()->withInput(Input::all())->with('message', 'Something
went wrong!');
Since you explicitly asked for VB as well, let me just add that this verbatim string syntax doesn't exist in VB, only in C#. Rather, all strings are verbatim in VB (except for the fact that they cannot contain line breaks, unlike C# verbatim strings):
Dim path = "C:\My\Path"
Dim message = "She said, ""Hello, beautiful world."""
Escape sequences don't exist in VB (except for the doubling of the quote character, like in C# verbatim strings) which makes a few things more complicated. For example, to write the following code in VB you need to use concatenation (or any of the other ways to construct a string)
string x = "Foo\nbar";
In VB this would be written as follows:
Dim x = "Foo" & Environment.NewLine & "bar"
(&
is the VB string concatenation operator. +
could equally be used.)
For Django 2.0+ versions use:
if request.auth:
# Only for authenticated users.
For more info visit https://www.django-rest-framework.org/api-guide/requests/#auth
request.user.is_authenticated() has been removed in Django 2.0+ versions.
You have properly guarded your code block when you call wait()
method by using synchronized(this)
.
But you have not taken same precaution when you call notify()
method without using guarded block : synchronized(this)
or synchronized(someObject)
If you refer to oracle documentation page on Object class, which contains wait()
,notify()
, notifyAll()
methods, you can see below precaution in all these three methods
This method should only be called by a thread that is the owner of this object's monitor
Many things have been changed in last 7 years and let's have look into other alternatives to synchronized
in below SE questions:
You can try this:
$('#studentTypeCheck').is(":checked");
Edit
This answer is now deprecated. See the answer by apsillers.
Since this is for a Chrome extension, you might as well use the standard DOM event - DOMSubtreeModified
. See the support for this event across browsers. It has been supported in Chrome since 1.0.
$("#someDiv").bind("DOMSubtreeModified", function() {
alert("tree changed");
});
See a working example here.
for those who like me use a function to create several graphics and want to update them a block too, only the function .destroy() worked for me, I would have liked to make an .update(), which seems cleaner but ... here is a code snippet that may help.
var SNS_Chart = {};
// IF LABELS IS EMPTY (after update my datas)
if( labels.length != 0 ){
if( Object.entries(SNS_Chart).length != 0 ){
array_items_datas.forEach(function(for_item, k_arr){
SNS_Chart[''+for_item+''].destroy();
});
}
// LOOP OVER ARRAY_ITEMS
array_items_datas.forEach(function(for_item, k_arr){
// chart
OPTIONS.title.text = array_str[k_arr];
var elem = document.getElementById(for_item);
SNS_Chart[''+for_item+''] = new Chart(elem, {
type: 'doughnut',
data: {
labels: labels[''+for_item+''],
datasets: [{
// label: '',
backgroundColor: [
'#5b9aa0',
'#c6bcb6',
'#eeac99',
'#a79e84',
'#dbceb0',
'#8ca3a3',
'#82b74b',
'#454140',
'#c1502e',
'#bd5734'
],
borderColor: '#757575',
borderWidth : 2,
// hoverBackgroundColor : '#616161',
data: datas[''+for_item+''],
}]
},
options: OPTIONS
});
// chart
});
// END LOOP ARRAY_ITEMS
}
// END IF LABELS IS EMPTY ...
Non VBA Solution:
Use Conditional Formatting rule with formula: =ISNA(A1)
(to highlight cells with all errors - not only #N/A
, use =ISERROR(A1)
)
VBA Solution:
Your code loops through 50 mln cells. To reduce number of cells, I use .SpecialCells(xlCellTypeFormulas, 16)
and .SpecialCells(xlCellTypeConstants, 16)
to return only cells with errors (note, I'm using If cell.Text = "#N/A" Then
)
Sub ColorCells()
Dim Data As Range, Data2 As Range, cell As Range
Dim currentsheet As Worksheet
Set currentsheet = ActiveWorkbook.Sheets("Comparison")
With currentsheet.Range("A2:AW" & Rows.Count)
.Interior.Color = xlNone
On Error Resume Next
'select only cells with errors
Set Data = .SpecialCells(xlCellTypeFormulas, 16)
Set Data2 = .SpecialCells(xlCellTypeConstants, 16)
On Error GoTo 0
End With
If Not Data2 Is Nothing Then
If Not Data Is Nothing Then
Set Data = Union(Data, Data2)
Else
Set Data = Data2
End If
End If
If Not Data Is Nothing Then
For Each cell In Data
If cell.Text = "#N/A" Then
cell.Interior.ColorIndex = 4
End If
Next
End If
End Sub
Note, to highlight cells witn any error (not only "#N/A"
), replace following code
If Not Data Is Nothing Then
For Each cell In Data
If cell.Text = "#N/A" Then
cell.Interior.ColorIndex = 3
End If
Next
End If
with
If Not Data Is Nothing Then Data.Interior.ColorIndex = 3
UPD: (how to add CF rule through VBA)
Sub test()
With ActiveWorkbook.Sheets("Comparison").Range("A2:AW" & Rows.Count).FormatConditions
.Delete
.Add Type:=xlExpression, Formula1:="=ISNA(A1)"
.Item(1).Interior.ColorIndex = 3
End With
End Sub
The easiest way to accomplish this is to package the desired font(s) with your application. To do this, simply create an assets/ folder in the project root, and put your fonts (in TrueType, or TTF, form) in the assets. You might, for example, create assets/fonts/ and put your TTF files in there.
Then, you need to tell your widgets to use that font. Unfortunately, you can no longer use layout XML for this, since the XML does not know about any fonts you may have tucked away as an application asset. Instead, you need to make the change in Java code, by calling Typeface.createFromAsset(getAssets(), “fonts/HandmadeTypewriter.ttf”), then taking the created Typeface object and passing it to your TextView via setTypeface().
For more reference here is the tutorial where I got this:
these methods will help you-
public static Date getStartOfDay(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
and
public static Date getEndOfDay(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
return calendar.getTime();
}
array.map{ |i| %Q('#{i}') }.join(',')
OK, So I faced the same issue for my android app which have secured domain i.e. HTTPS,
These are the steps:
public class SSlUtilsw {
public static SSLContext getSslContextForCertificateFile(Context context, String fileName){
try {
KeyStore keyStore = SSlUtilsw.getKeyStore(context, fileName);
SSLContext sslContext = SSLContext.getInstance("SSL");
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
sslContext.init(null,trustManagerFactory.getTrustManagers(),new SecureRandom());
return sslContext;
}catch (Exception e){
String msg = "Error during creating SslContext for certificate from assets";
e.printStackTrace();
throw new RuntimeException(msg);
}
}
public static KeyStore getKeyStore(Context context,String fileName){
KeyStore keyStore = null;
try {
AssetManager assetManager=context.getAssets();
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream caInput=assetManager.open(fileName);
Certificate ca;
try {
ca=cf.generateCertificate(caInput);
}finally {
caInput.close();
}
String keyStoreType=KeyStore.getDefaultType();
keyStore=KeyStore.getInstance(keyStoreType);
keyStore.load(null,null);
keyStore.setCertificateEntry("ca",ca);
} catch (CertificateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return keyStore;
}}
In your http client class of retrofit, add this
val trustManagerFactory: TrustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
trustManagerFactory.init(null as KeyStore?)
val trustManagers: Array<TrustManager> = trustManagerFactory.trustManagers
if (trustManagers.size != 1 || trustManagers[0] !is X509TrustManager) {
throw IllegalStateException("Unexpected default trust managers:" + trustManagers.contentToString())
}
val trustManager = trustManagers[0] as X509TrustManager
httpClient.sslSocketFactory(SSlUtils.getSslContextForCertificateFile(
applicationContextHere, "yourcertificate.pem").socketFactory, trustManager)
And that's it.
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.
Most build systems use data time stamps to determine when rebuilds should happen - the date/time stamp of any output files is checked against the last modified time of the dependencies - if any of the dependencies are fresher, then the target is rebuilt.
This can cause problems if any of the dependencies somehow get an invalid data time stamp as it's difficult for the time stamp of any build output to ever exceed the timestamp of a file supposedly created in the future :P
You are opening the csv file in binary mode, it should be 'w'
import csv
# open csv file in write mode with utf-8 encoding
with open('output.csv','w',encoding='utf-8',newline='')as w:
fieldnames = ["SNo", "States", "Dist", "Population"]
writer = csv.DictWriter(w, fieldnames=fieldnames)
# write list of dicts
writer.writerows(list_of_dicts) #writerow(dict) if write one row at time
public static object CopyObject(object input)
{
if (input != null)
{
object result = Activator.CreateInstance(input.GetType());
foreach (FieldInfo field in input.GetType().GetFields(Consts.AppConsts.FullBindingList))
{
if (field.FieldType.GetInterface("IList", false) == null)
{
field.SetValue(result, field.GetValue(input));
}
else
{
IList listObject = (IList)field.GetValue(result);
if (listObject != null)
{
foreach (object item in ((IList)field.GetValue(input)))
{
listObject.Add(CopyObject(item));
}
}
}
}
return result;
}
else
{
return null;
}
}
This way is a few times faster than BinarySerialization
AND this does not require the [Serializable]
attribute.
In regards to your error and what's missing in your code. m
is a name which is not defined for getmd5()
function.
No offence, I know you are a beginner, but your code is all over the place. Let's look at your issues one by one :)
First, you are not using hashlib.md5.hexdigest()
method correctly. Please refer explanation on hashlib functions in Python Doc Library. The correct way to return MD5 for provided string is to do something like this:
>>> import hashlib
>>> hashlib.md5("filename.exe").hexdigest()
'2a53375ff139d9837e93a38a279d63e5'
However, you have a bigger problem here. You are calculating MD5 on a file name string, where in reality MD5 is calculated based on file contents. You will need to basically read file contents and pipe it though MD5. My next example is not very efficient, but something like this:
>>> import hashlib
>>> hashlib.md5(open('filename.exe','rb').read()).hexdigest()
'd41d8cd98f00b204e9800998ecf8427e'
As you can clearly see second MD5 hash is totally different from the first one. The reason for that is that we are pushing contents of the file through, not just file name.
A simple solution could be something like that:
# Import hashlib library (md5 method is part of it)
import hashlib
# File to check
file_name = 'filename.exe'
# Correct original md5 goes here
original_md5 = '5d41402abc4b2a76b9719d911017c592'
# Open,close, read file and calculate MD5 on its contents
with open(file_name) as file_to_check:
# read contents of the file
data = file_to_check.read()
# pipe contents of the file through
md5_returned = hashlib.md5(data).hexdigest()
# Finally compare original MD5 with freshly calculated
if original_md5 == md5_returned:
print "MD5 verified."
else:
print "MD5 verification failed!."
Please look at the post Python: Generating a MD5 checksum of a file. It explains in detail a couple of ways how it can be achieved efficiently.
Best of luck.
You can do the following:
Example using PHP (you can do this in any language of your choice):
Server:
<?php $years = range(1900, strftime("%Y", time())); ?>
HTML
<select>
<option>Select Year</option>
<?php foreach($years as $year) : ?>
<option value="<?php echo $year; ?>"><?php echo $year; ?></option>
<?php endforeach; ?>
</select>
As an added benefit, this works has a browser compatibility of a 100% ;-)
Try below code:
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));// set transparent in window background
View _v = inflater.inflate(R.layout.some_you_layout, container, false);
//load animation
//Animation transition_in_view = AnimationUtils.loadAnimation(getContext(), android.R.anim.fade_in);// system animation appearance
Animation transition_in_view = AnimationUtils.loadAnimation(getContext(), R.anim.customer_anim);//customer animation appearance
_v.setAnimation( transition_in_view );
_v.startAnimation( transition_in_view );
//really beautiful
return _v;
}
Create the custom Anim.: res/anim/customer_anim.xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:duration="500"
android:fromYDelta="100%"
android:toYDelta="-7%"/>
<translate
android:duration="300"
android:startOffset="500"
android:toYDelta="7%" />
<translate
android:duration="200"
android:startOffset="800"
android:toYDelta="0%" />
</set>
You can also use this code to get LayoutInflater:
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)
You can center a fixed
or absolute
positioned element setting right
and left
to 0
, and then margin-left
& margin-right
to auto
as if you were centering a static
positioned element.
#example {
position: fixed;
/* center the element */
right: 0;
left: 0;
margin-right: auto;
margin-left: auto;
/* give it dimensions */
min-height: 10em;
width: 90%;
}
List indexes of -x mean the xth item from the end of the list, so n[-1]
means the last item in the list n
. Any good Python tutorial should have told you this.
It's an unusual convention that only a few other languages besides Python have adopted, but it is extraordinarily useful; in any other language you'll spend a lot of time writing n[n.length-1]
to access the last item of a list.
awk works well if you your server has it
var="text,text,text,text"
num=$(echo "${var}" | awk -F, '{print NF-1}')
echo "${num}"
[label sizeToFit];
in viewDidLoadunnest
can be used as well.
It expands array to a set of rows and then simply checking a value exists or not is as simple as using IN
or NOT IN
.
e.g.
id => uuid
exception_list_ids => uuid[]
select * from table where id NOT IN (select unnest(exception_list_ids) from table2)
I'm using this kind of routine for programmatically chaining animations.
final Animation anim_out = AnimationUtils.loadAnimation(context, android.R.anim.fade_out);
final Animation anim_in = AnimationUtils.loadAnimation(context, android.R.anim.fade_in);
anim_out.setAnimationListener(new AnimationListener()
{
@Override
public void onAnimationStart(Animation animation) {}
@Override
public void onAnimationRepeat(Animation animation) {}
@Override
public void onAnimationEnd(Animation animation)
{
////////////////////////////////////////
// HERE YOU CHANGE YOUR IMAGE CONTENT //
////////////////////////////////////////
//ui_image.setImage...
anim_in.setAnimationListener(new AnimationListener()
{
@Override
public void onAnimationStart(Animation animation) {}
@Override
public void onAnimationRepeat(Animation animation) {}
@Override
public void onAnimationEnd(Animation animation) {}
});
ui_image.startAnimation(anim_in);
}
});
ui_image.startAnimation(anim_out);
if someones is interested you can delete the form node from the DOM after the submission and it won't be there using the inspector.
https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/remove
Java 8+ version:
Files.createDirectories(Paths.get("/Your/Path/Here"));
The Files.createDirectories()
creates a new directory and parent directories that do not exist. This method does not throw an exception if the directory already exists.
IO.Directory.Delete(HttpContext.Current.Server.MapPath(path), True)
You don't need more than that
Just put a space between your classes
.area1 .item
{
...
}
Here's a very good reference for CSS Selectors.
I have just used dompdf and the code was a little different but it worked.
Here it is:
require_once("./pdf/dompdf_config.inc.php");
$files = glob("./pdf/include/*.php");
foreach($files as $file) include_once($file);
$html =
'<html><body>'.
'<p>Put your html here, or generate it with your favourite '.
'templating system.</p>'.
'</body></html>';
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
$output = $dompdf->output();
file_put_contents('Brochure.pdf', $output);
Only difference here is that all of the files in the include directory are included.
Other than that my only suggestion would be to specify a full directory path for writing the file rather than just the filename.
The CSS standard enables some advanced formatting. There is a @page directive in CSS that enables some formatting that applies only to paged media (like paper). See http://www.w3.org/TR/1998/REC-CSS2-19980512/page.html.
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<title>Print Test</title>_x000D_
<style type="text/css" media="print">_x000D_
@page _x000D_
{_x000D_
size: auto; /* auto is the current printer page size */_x000D_
margin: 0mm; /* this affects the margin in the printer settings */_x000D_
}_x000D_
_x000D_
body _x000D_
{_x000D_
background-color:#FFFFFF; _x000D_
border: solid 1px black ;_x000D_
margin: 0px; /* the margin on the content before printing */_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
<div>Top line</div>_x000D_
<div>Line 2</div>_x000D_
</body>_x000D_
</html>
_x000D_
and for firefox use it
In Firefox, https://bug743252.bugzilla.mozilla.org/attachment.cgi?id=714383 (view page source :: tag HTML).
In your code, replace <html>
with <html moznomarginboxes mozdisallowselectionprint>.
I Found in OWASP
<session-config>
<cookie-config>
<http-only>true</http-only>
</cookie-config>
</session-config>
this is also fix for "httponlycookies in config" security issue
Try using WGET
:
WGET 'http://localhost/index.php?a=1&b=2&c=3'
Is it proper to "reach into" an object and use its dict property?
In general, I would say "no". However Namespace
has struck me as over-engineered, possibly from when classes couldn't inherit from built-in types.
On the other hand, Namespace
does present a task-oriented approach to argparse, and I can't think of a situation that would call for grabbing the __dict__
, but the limits of my imagination are not the same as yours.
$ if [ "$s1" == "$s2" ]; then echo match; fi
match
$ test "s1" = "s2" ;echo match
match
$
Try this:-
ALTER TABLE <TABLE NAME to be moved> MOVE TABLESPACE <destination TABLESPACE NAME>
Very nice suggestion from IVAN in comments so thought to add in my answer
Note: this will invalidate all table's indexes. So this command is usually followed by
alter index <owner>."<index_name>" rebuild;
It's not possible to achieve the required level of control over presentation in a regular textarea
.
If you're OK with that, try CodeMirror or Ace or Monaco (used in MS VSCode).
From the duplicate thread - an obligatory wikipedia link: Comparison of JavaScript-based source code editors
There are two methods you can use. Both require creating a user and a database.
By default psql connects to the database with the same name as the user. So there is a convention to make that the "user's database". And there is no reason to break that convention if your user only needs one database. We'll be using mydatabase
as the example database name.
Using createuser and createdb, we can be explicit about the database name,
$ sudo -u postgres createuser -s $USER
$ createdb mydatabase
$ psql -d mydatabase
You should probably be omitting that entirely and letting all the commands default to the user's name instead.
$ sudo -u postgres createuser -s $USER
$ createdb
$ psql
Using the SQL administration commands, and connecting with a password over TCP
$ sudo -u postgres psql postgres
And, then in the psql shell
CREATE ROLE myuser LOGIN PASSWORD 'mypass';
CREATE DATABASE mydatabase WITH OWNER = myuser;
Then you can login,
$ psql -h localhost -d mydatabase -U myuser -p <port>
If you don't know the port, you can always get it by running the following, as the postgres
user,
SHOW port;
Or,
$ grep "port =" /etc/postgresql/*/main/postgresql.conf
postgres
userI suggest NOT modifying the postgres
user.
postgres
. You're supposed to have root to get to authenticate as postgres
.postgres
which is the PostgreSQL equivalent of SQL Server's SA
, you have to have write-access to the underlying data files. And, that means that you could normally wreck havoc anyway.Not possible, per MSDN:
You can have the same code execute for multiple trigger types, but the syntax does not allow for multiple code blocks in one trigger:
Trigger on an INSERT, UPDATE, or DELETE statement to a table or view (DML Trigger)
CREATE TRIGGER [ schema_name . ]trigger_name ON { table | view } [ WITH <dml_trigger_option> [ ,...n ] ] { FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] } [ NOT FOR REPLICATION ] AS { sql_statement [ ; ] [ ,...n ] | EXTERNAL NAME <method specifier [ ; ] > }
You can use the following example:
<table id="purches">
<thead>
<tr>
<th>ID</th>
<th>Transaction Date</th>
<th>Category</th>
<th>Transaction Amount</th>
<th>Offer</th>
</tr>
</thead>
<!-- <tr th:each="person: ${list}" >
<td><li th:each="person: ${list}" th:text="|${person.description}|"></li></td>
<td><li th:each="person: ${list}" th:text="|${person.price}|"></li></td>
<td><li th:each="person: ${list}" th:text="|${person.available}|"></li></td>
<td><li th:each="person: ${list}" th:text="|${person.from}|"></li></td>
</tr>
-->
<tbody id="feedback">
</tbody>
</table>
JavaScript file:
$.ajax({
type: "POST",
contentType: "application/json",
url: "/search",
data: JSON.stringify(search),
dataType: 'json',
cache: false,
timeout: 600000,
success: function (data) {
// var json = "<h4>Ajax Response</h4><pre>" + JSON.stringify(data, null, 4) + "</pre>";
// $('#feedback').html(json);
//
console.log("SUCCESS: ", data);
//$("#btn-search").prop("disabled", false);
for (var i = 0; i < data.length; i++) {
//$("#feedback").append('<tr><td>' + data[i].accountNumber + '</td><td>' + data[i].category + '</td><td>' + data[i].ssn + '</td></tr>');
$('#feedback').append('<tr><td>' + data[i].accountNumber + '</td><td>' + data[i].category + '</td><td>' + data[i].ssn + '</td><td>' + data[i].ssn + '</td><td>' + data[i].ssn + '</td></tr>');
alert(data[i].accountNumber)
}
},
error: function (e) {
var json = "<h4>Ajax Response</h4><pre>" + e.responseText + "</pre>";
$('#feedback').html(json);
console.log("ERROR: ", e);
$("#btn-search").prop("disabled", false);
}
});
I found dfsq's answer its comments extremely useful. I made some minor modifications applicable to me (and I'm posting it here, in case it is of some use to others).
class
as hooks, instead of table elements tr
class
while showing/hiding parent$rows
text elements into an array only once (and avoiding $rows.length
times computation)var $rows = $('.wrapper');
var rowsTextArray = [];
var i = 0;
$.each($rows, function () {
rowsTextArray[i] = ($(this).find('.number').text() + $(this).find('.fruit').text())
.replace(/\s+/g, '')
.toLowerCase();
i++;
});
$('#search').keyup(function() {
var val = $.trim($(this).val()).replace(/\s+/g, '').toLowerCase();
$rows.show().filter(function(index) {
return (rowsTextArray[index].indexOf(val) === -1);
}).hide();
});
_x000D_
span {
margin-right: 0.2em;
}
_x000D_
<input type="text" id="search" placeholder="type to search" />
<div class="wrapper"><span class="number">one</span><span class="fruit">apple</span></div>
<div class="wrapper"><span class="number">two</span><span class="fruit">banana</span></div>
<div class="wrapper"><span class="number">three</span><span class="fruit">cherry</span></div>
<div class="wrapper"><span class="number">four</span><span class="fruit">date</span></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
This is because in this case the char
type is signed on your system*. When this happens, the data gets sign-extended during the default conversions while passing the data to the function with variable number of arguments. Since 212 is greater than 0x80, it's treated as negative, %u
interprets the number as a large positive number:
212 = 0xD4
When it is sign-extended, FF
s are pre-pended to your number, so it becomes
0xFFFFFFD4 = 4294967252
which is the number that gets printed.
Note that this behavior is specific to your implementation. According to C99 specification, all char
types are promoted to (signed) int
, because an int
can represent all values of a char
, signed or unsigned:
6.1.1.2: If an
int
can represent all values of the original type, the value is converted to anint
; otherwise, it is converted to anunsigned int
.
This results in passing an int
to a format specifier %u
, which expects an unsigned int
.
To avoid undefined behavior in your program, add explicit type casts as follows:
unsigned char ch = (unsigned char)212;
printf("%u", (unsigned int)ch);
char
up to the implementation. See this question for more details.
If the return
in the try
block is reached, it transfers control to the finally
block, and the function eventually returns normally (not a throw).
If an exception occurs, but then the code reaches a return
from the catch
block, control is transferred to the finally
block and the function eventually returns normally (not a throw).
In your example, you have a return
in the finally
, and so regardless of what happens, the function will return 34
, because finally
has the final (if you will) word.
Although not covered in your example, this would be true even if you didn't have the catch
and if an exception were thrown in the try
block and not caught. By doing a return
from the finally
block, you suppress the exception entirely. Consider:
public class FinallyReturn {
public static final void main(String[] args) {
System.out.println(foo(args));
}
private static int foo(String[] args) {
try {
int n = Integer.parseInt(args[0]);
return n;
}
finally {
return 42;
}
}
}
If you run that without supplying any arguments:
$ java FinallyReturn
...the code in foo
throws an ArrayIndexOutOfBoundsException
. But because the finally
block does a return
, that exception gets suppressed.
This is one reason why it's best to avoid using return
in finally
.
Another answer would be the NodeJS!
Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.
Using terminal you will be able to start it using node
command.
$ node
> 2 + 4
6
>
Note: If you want to exit just type
.exit
You can also run a JavaScript file like this:
node file.js
it's well documented here:
https://cwiki.apache.org/confluence/display/TOMCAT/Connectors#Connectors-Q6
How do I bind to a specific ip address? - "Each Connector element allows an address property. See the HTTP Connector docs or the AJP Connector docs". And HTTP Connectors docs:
http://tomcat.apache.org/tomcat-7.0-doc/config/http.html
Standard Implementation -> address
"For servers with more than one IP address, this attribute specifies which address will be used for listening on the specified port. By default, this port will be used on all IP addresses associated with the server."
Use the insort function of the bisect module:
import bisect
a = [1, 2, 4, 5]
bisect.insort(a, 3)
print(a)
Output
[1, 2, 3, 4, 5]
You could add the DLLs as embedded resources, and then have your program unpack them into the application directory on startup (after checking to see if they're there already).
Setup files are so easy to make, though, that I don't think this would be worth it.
EDIT: This technique would be easy with .NET assemblies. With non-.NET DLLs it would be a lot more work (you'd have to figure out where to unpack the files and register them and so on).
The :target
-pseudo selector is made for these type of situations: http://reference.sitepoint.com/css/pseudoclass-target
It is supported by all modern browsers. To get some IE versions to understand it you can use something like Selectivizr
Here is a tab example with :target
-pseudo selector.
This simple script allows you to uncheck an already checked radio button. Works on all javascript enabled browsers.
var allRadios = document.getElementsByName('re');_x000D_
var booRadio;_x000D_
var x = 0;_x000D_
for(x = 0; x < allRadios.length; x++){_x000D_
allRadios[x].onclick = function() {_x000D_
if(booRadio == this){_x000D_
this.checked = false;_x000D_
booRadio = null;_x000D_
} else {_x000D_
booRadio = this;_x000D_
}_x000D_
};_x000D_
}
_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>_x000D_
<input type='radio' class='radio-button' name='re'>
_x000D_
Maybe something like this:
First some test data:
DECLARE @tbl TABLE(Column1 VARCHAR(100))
INSERT INTO @tbl
SELECT '1/1' UNION ALL
SELECT '1/20' UNION ALL
SELECT '1/2'
Then like this:
SELECT
SUBSTRING(tbl.Column1,CHARINDEX('/',tbl.Column1)+1,LEN(tbl.Column1))
FROM
@tbl AS tbl
Count all td in table1:
console.log(_x000D_
table1.querySelectorAll("td").length_x000D_
)
_x000D_
<table id="table1">_x000D_
<tr>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
</tr>_x000D_
<table>
_x000D_
Count all td into each tr of table1.
table1.querySelectorAll("tr").forEach(function(e){_x000D_
console.log( e.querySelectorAll("td").length )_x000D_
})
_x000D_
<table id="table1">_x000D_
<tr>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
<td><input type="text" value="" /></td>_x000D_
</tr>_x000D_
<table>
_x000D_
Any Primitive data type like int,boolean, or float etc can't store the null(lateral),since java has provided Wrapper class for storing the same like int to Integer,boolean to Boolean.
Eg: Integer i=null;
I am using wildfly 10 for javaee container . I had experienced "Target Unreachable, 'entity' returned null" issue. Thanks for suggestions by BalusC but the my issue out of the solutions explained. Accidentally using "import com.sun.istack.logging.Logger;" instead of "import org.jboss.logging.Logger;" caused CDI implemented JSF EL. Hope it helps to improve solution .
If you don't want execute assembly goal on package, you can use next command:
mvn package assembly:single
Here package is keyword.
It can be done at easily like as:
<a id="send-thoughts" href="">Click</a>
<textarea id="message"></textarea>
$("a#send-thoughts").click(function() {
var thought = $("#message").val();
alert(thought);
});
Please see my comment here: Make a link in the Android browser start up my app?
We strongly discourage people from using their own schemes, unless they are defining a new world-wide internet scheme.
The automatic install of peer dependencies was explicitly removed with npm 3, as it cause more problems than it tried to solve. You can read about it here for example:
So no, for the reasons given, you cannot install them automatically with npm 3 upwards.
NPM V7
NPM v7 has reintroduced the automatic peerDependencies installation. They had made some changes to fix old problems as version compatibility across multiple dependants. You can see the discussion here and the announcement here
Now in V7, as in versions before V3, you only need to do an npm i
and all peerDependences should be automatically installed.
You could use the ROLLUP operator
SELECT CASE
WHEN (GROUPING([Type]) = 1) THEN 'Total'
ELSE [Type] END AS [TYPE]
,SUM([Total Sales]) as Total_Sales
From Before
GROUP BY
[Type] WITH ROLLUP
This was put together with some edited example cmd
@Echo off
Echo ********************************************************
Echo * ZIP Folder Backup using 7Zip *
Echo * Usage: Source Folder, Destination Drive Letter *
Echo * Source Folder will be Zipped to Destination\Backups *
Echo ********************************************************
Echo off
set year=%date:~-4,4%
set month=%date:~-10,2%
set day=%date:~-7,2%
set hour=%time:~-11,2%
set hour=%hour: =0%
set min=%time:~-8,2%
SET /P src=Source Folder to Backup:
SET source=%src%\*
call :file_name_from_path nam %src%
SET /P destination=Backup Drive Letter:
set zipfilename=%nam%.%year%.%month%.%day%.%hour%%min%.zip
set dest="%destination%:\Backups\%zipfilename%"
set AppExePath="%ProgramFiles(x86)%\7-Zip\7z.exe"
if not exist %AppExePath% set AppExePath="%ProgramFiles%\7-Zip\7z.exe"
if not exist %AppExePath% goto notInstalled
echo Backing up %source% to %dest%
%AppExePath% a -r -tzip %dest% %source%
echo %source% backed up to %dest% is complete!
TIMEOUT 5
exit;
:file_name_from_path <resultVar> <pathVar>
(
set "%~1=%~nx2"
exit /b
)
:notInstalled
echo Can not find 7-Zip, please install it from:
echo http://7-zip.org/
:end
PAUSE
I have this issue from time-to-time and often it's because the project wasn't marked as a java project. You can change this by going to the properties for the project > Project Facets > and selecting java. You may then need to properly configure that project, but this is probably part of the problem
This code works for me: check this link
This is my code when i stop and start service in activity
case R.id.buttonStart:
Log.d(TAG, "onClick: starting srvice");
startService(new Intent(this, MyService.class));
break;
case R.id.buttonStop:
Log.d(TAG, "onClick: stopping srvice");
stopService(new Intent(this, MyService.class));
break;
}
}
}
And in service class:
@Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
player = MediaPlayer.create(this, R.raw.braincandy);
player.setLooping(false); // Set looping
}
@Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
}
HAPPY CODING!
Yes, that code does exactly that.
You can also use:
if (@value is null or @value = '')
With the added information that @value
is an int
value, you need instead:
if (@value is null)
An int
value can never contain the value ''
.
Whevever you get a problem like this just go to the man page for the function in question and it will tell you what header you are missing, e.g.
$ man memset
MEMSET(3) BSD Library Functions Manual MEMSET(3)
NAME
memset -- fill a byte string with a byte value
LIBRARY
Standard C Library (libc, -lc)
SYNOPSIS
#include <string.h>
void *
memset(void *b, int c, size_t len);
Note that for C++ it's generally preferable to use the proper equivalent C++ headers, <cstring>
/<cstdio>
/<cstdlib>
/etc, rather than C's <string.h>
/<stdio.h>
/<stdlib.h>
/etc.
Reinstall JDK and set system variable JAVA_HOME on your JDK. (e.g. C:\tools\jdk7)
And add JAVA_HOME variable to your PATH system variable
Type in command line
echo %JAVA_HOME%
and
java -version
To verify whether your installation was done successfully.
This problem generally occurs in Windows when your "Java Runtime Environment" registry entry is missing or mismatched with the installed JDK. The mismatch can be due to multiple JDKs.
Steps to resolve:
Open the Run window:
Press windows+R
Open registry window:
Type regedit
and enter.
Go to: \HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\
If Java Runtime Environment is not present inside JavaSoft, then create a new Key and give the name Java Runtime Environment.
For Java Runtime Environment create "CurrentVersion" String Key and give appropriate version as value:
Create a new subkey of 1.8.
For 1.8 create a String Key with name JavaHome with the value of JRE home:
Ref: https://mybindirectory.blogspot.com/2019/05/error-could-not-find-javadll.html
If you keep track of the tail node, you don't need to loop through every element in the list.
Just update the tail to point to the new node:
AddValueToListEnd(value) {
var node = new Node(value);
if(!this.head) {
this.head = node;
this.tail = node;
} else {
this.tail.next = node; //point old tail to new node
}
this.tail = node; //now set the new node as the new tail
}
In plain English:
It's an indication that connection pooling is being used (which is a good thing).
Add --force to your command line if you are sure you want to push. E.g. use git push origin --force
(I recommend the command line as you will find much more support from other users with the command line. Also this may not be possible with SmartGit.) See this site for more information: http://help.github.com/remotes/
In the case of your fictional getattr
function, if the requested attribute always should be available but isn't then throw an error. If the attribute is optional then return None
.
The answer is yes, there is.
First you can easily install numpy use commands:
pip install numpy
Then you should install mkl, which is required by Scipy, and you can download it here
After download the file_name.whl you install it
C:\Users\****\Desktop\a> pip install mkl_service-1.1.2-cp35-cp35m-win32.whl
Processing c:\users\****\desktop\a\mkl_service-1.1.2-cp35-cp35m-win32.whl
Installing collected packages: mkl-service
Successfully installed mkl-service-1.1.2
Then at the same website you can download scipy-0.18.1-cp35-cp35m-win32.whl
Note:You should download the file_name.whl according to you python version, if you python version is 32bit python3.5 you should download this one, and the "win32" is about your python version, not your operating system version.
Then install file_name.whl like this:
C:\Users\****\Desktop\a>pip install scipy-0.18.1-cp35-cp35m-win32.whl
Processing c:\users\****\desktop\a\scipy-0.18.1-cp35-cp35m-win32.whl
Installing collected packages: scipy
Successfully installed scipy-0.18.1
Then there is only one more thing to do: comment out a specfic line or there will be error messages when you imput command "import scipy".
So comment out this line
from numpy._distributor_init import NUMPY_MKL # requires numpy+mkl
in this file: your_own_path\lib\site-packages\scipy__init__.py
Then you can use SciPy :)
Here tells you more about the last step.
Here is a similar anwser to a similar question.
I've simply managed to get dropzone and other plugin to work with this fix (angularjs + php backend)
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token , Authorization');
add this in your upload.php or where you would send your request (for example if you have upload.html and you need to attach the files to upload.php, then copy and paste these 4 lines). Also if you're using CORS plugins/addons in chrome/mozilla be sure to toggle them more than one time,in order for CORS to be enabled
$str = 'In My Cart : 11 12 items';
preg_match_all('!\d+!', $str, $matches);
print_r($matches);
For completely transparent color, use:
rbga(255,255,255,0)
A little more visible:
rbga(255,255,255,.3)
You could use :focus
which will remain the style as long as the user doesn't click elsewhere.
button:active {
border: 2px solid green;
}
button:focus {
border: 2px solid red;
}
In bootstrap 4, if you want to over-ride when navbar-expand-*, expands and collapses and shows and hides the hamburger (navbar-toggler) you have to find that style/definition in bootstrap.css, and redefine it in your own customstyle.css (or directly in bootstrap.css if you are so inclined).
Eg. I wanted the navbar-expand-lg to collapses and shows the navbar-toggler at 950px. In bootstrap.css I find:
@media (max-width: 991.98px) {
.navbar-expand-lg > .container,
.navbar-expand-lg > .container-fluid {
padding-right: 0;
padding-left: 0;
}
}
And below that ...
@media (min-width:992px) {
... lots of styling ...
}
I copied both @media queries and stuck them in my style.css, then modified the size to fit my needs. I my case I wanted it to collapse at 950px. The @media queries must need to be different sizes (I'm guessing), so I set container max-width to 949.98px and used the 950px for the other @media query and so the following code was appended to my style.css. This was not easy to detangle from twisted solutions I found on Stackoverflow and elsewhere. Hope this helps.
@media (max-width: 949.98px) {
.navbar-expand-lg > .container,
.navbar-expand-lg > .container-fluid {
padding-right: 0;
padding-left: 0;
}
}
@media (min-width: 950px) {
.navbar-expand-lg {
-webkit-box-orient: horizontal;
-webkit-box-direction: normal;
-ms-flex-flow: row nowrap;
flex-flow: row nowrap;
-webkit-box-pack: start;
-ms-flex-pack: start;
justify-content: flex-start;
}
.navbar-expand-lg .navbar-nav {
-webkit-box-orient: horizontal;
-webkit-box-direction: normal;
-ms-flex-direction: row;
flex-direction: row;
}
.navbar-expand-lg .navbar-nav .dropdown-menu {
position: absolute;
}
.navbar-expand-lg .navbar-nav .dropdown-menu-right {
right: 0;
left: auto;
}
.navbar-expand-lg .navbar-nav .nav-link {
padding-right: 0.5rem;
padding-left: 0.5rem;
}
.navbar-expand-lg > .container,
.navbar-expand-lg > .container-fluid {
-ms-flex-wrap: nowrap;
flex-wrap: nowrap;
}
.navbar-expand-lg .navbar-collapse {
display: -webkit-box !important;
display: -ms-flexbox !important;
display: flex !important;
-ms-flex-preferred-size: auto;
flex-basis: auto;
}
.navbar-expand-lg .navbar-toggler {
display: none;
}
.navbar-expand-lg .dropup .dropdown-menu {
top: auto;
bottom: 100%;
}
}
This is another option to write a pandas dataframe directly into a matplotlib table:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
# hide axes
fig.patch.set_visible(False)
ax.axis('off')
ax.axis('tight')
df = pd.DataFrame(np.random.randn(10, 4), columns=list('ABCD'))
ax.table(cellText=df.values, colLabels=df.columns, loc='center')
fig.tight_layout()
plt.show()
yes the best way to see what is modified is to save in file like that:
git stash show -p stash@{0} > stash.txt
You can check all the config settings using
git config --global --list
You can remove the setting for example username
git config --global --unset user.name
You can edit the configuration or remove the config setting manually by hand using:
git config --global --edit
Add an application launcher icon with automatic sizing.
(Android studio)
Go to menu File* ? New ? Image Assets ? select launcher icon ? choose image file.
It will automatically re-size.
Done!
For IDLE, select the lines, then open the "Format" menu. (Between "Edit" and "Run" if you're having trouble finding it.) This will also give you the keyboard shortcut, for me it turned out that dedent shortcut was "Ctrl+["
Refer below code for formatting date
long strDate1 = 1346524199000;
Date date=new Date(strDate1);
try {
SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yy");
date = df2.format(format.parse("yourdate");
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
export your C++ functions as extern "C" (aka C style symbols), or use the .def file format to define undecorated export symbols for the C++ linker when it creates the C++ library, then the C linker should have no troubles reading it
Usually, all you need to do is to "Add CORS Configuration" in your bucket properties.
The <CORSConfiguration>
comes with some default values. That's all I needed to solve your problem. Just click "Save" and try again to see if it worked. If it doesn't, you could also try the code below (from alxrb answer) which seems to have worked for most of the people.
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>HEAD</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>Authorization</AllowedHeader>
</CORSRule>
</CORSConfiguration>
For further info, you can read this article on Editing Bucket Permission.
Use jdbc:h2:mem:testdb as your path when logging into the H2 console.
Obviously if you have altered Spring Boot properties your datasource may be different, but it seems like you're struggling with how to find the default. That's all there is to it! You'll see your schema after logging in to H2.
For a start I would recommend wxglade. It is a rather easy to use tool that helps you build wxPython applications. wx is already cross platform and can be packaged with tools like py2exe or py2app.
i couldn't change the permissions on the sharepoint i'm using but got a round it by uploading .url files with the drag and drop multiple files uploader.
Using the normal upload didn't work because they are intepreted by the file open dialog when you try to open them singly so it just tries to open the target not the .url file.
.url files can be made by saving a favourite with internet exploiter.
I had a similar problem on a raspberry pi.
The problem was that http requires SSL and so I needed to force it to use https to get around this requirement.
sudo pip install --upgrade pip --index-url=https://pypi.python.org/simple
or
sudo pip-3.2 --upgrade pip --index-url=https://pypi.python.org/simple/
Brighams answer uses literal regexp
.
Solution with a Regex object.
var regex = new RegExp('\n', 'g');
text = text.replace(regex, '<br />');
TRY IT HERE : JSFiddle Working Example
If this is the problem then go to the place where the javac is present and then type
It will work for sure.
Here is the difference:
This sets the image to half of its original size.
<img src="#" width="173" height="206.5">
This sets the image to half of its available presentation area.
<img src="#" width="50%" height="50%">
For example, if you put this as the only element on the page, it would attempt to take up 50% of the width of the page, thus making it potentially larger than its original size - not half of its original size as you are expecting.
If it is being presented at larger than original size, the image will appear greatly pixelated.
this question shows up pretty high on a Google search and worked for the most part! I did find that Salman Zaidi's answer was partially correct for iOS 7.
You need to make a modification to the "reverting" code. I found that the following for reverting worked perfectly:
textField.layer.cornerRadius = 0.0f;
textField.layer.masksToBounds = YES;
textField.layer.borderColor = [[UIColor blackColor] CGColor];
textField.layer.borderWidth = 0.0f;
I understand that this is most likely due to changes in iOS 7.
This question is not specific to jQuery, but specific to JavaScript in general. The core problem is how to "channel" a variable in embedded functions. This is the example:
var abc = 1; // we want to use this variable in embedded functions
function xyz(){
console.log(abc); // it is available here!
function qwe(){
console.log(abc); // it is available here too!
}
...
};
This technique relies on using a closure. But it doesn't work with this
because this
is a pseudo variable that may change from scope to scope dynamically:
// we want to use "this" variable in embedded functions
function xyz(){
// "this" is different here!
console.log(this); // not what we wanted!
function qwe(){
// "this" is different here too!
console.log(this); // not what we wanted!
}
...
};
What can we do? Assign it to some variable and use it through the alias:
var abc = this; // we want to use this variable in embedded functions
function xyz(){
// "this" is different here! --- but we don't care!
console.log(abc); // now it is the right object!
function qwe(){
// "this" is different here too! --- but we don't care!
console.log(abc); // it is the right object here too!
}
...
};
this
is not unique in this respect: arguments
is the other pseudo variable that should be treated the same way — by aliasing.
You can also use OpenCV's inbuilt functions cv2.hconcat
and cv2.vconcat
which like their names suggest are used to join images horizontally and vertically respectively.
import cv2
img1 = cv2.imread('opencv/lena.jpg')
img2 = cv2.imread('opencv/baboon.jpg')
v_img = cv2.vconcat([img1, img2])
h_img = cv2.hconcat([img1, img2])
cv2.imshow('Horizontal', h_img)
cv2.imshow('Vertical', v_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Horizontal Concatenation
Vertical Concatenation
Anyone else stumbling upon this answer should note that jQuery now (>=1.3) has outerHeight
/outerWidth
functions to retrieve the width including padding/borders, e.g.
$(elem).outerWidth(); // Returns the width + padding + borders
To include the margin as well, simply pass true
:
$(elem).outerWidth( true ); // Returns the width + padding + borders + margins
Here is a workaround using a flag:
//outside your event or method, but inside your class
private bool IsExecuted = false;
private async Task MethodA()
{
//Do Stuff Here
IsExecuted = true;
}
.
.
.
//Inside your event or method
{
await MethodA();
while (!isExecuted) Thread.Sleep(200); // <-------
await MethodB();
}
jquery function is most important
<script>
$(function(){
var stickyHeaderTop = $('#stickytypeheader').offset().top;
$(window).scroll(function(){
if( $(window).scrollTop() > stickyHeaderTop ) {
$('#stickytypeheader').css({position: 'fixed', top: '0px'});
$('#sticky').css('display', 'block');
} else {
$('#stickytypeheader').css({position: 'static', top: '0px'});
$('#sticky').css('display', 'none');
}
});
});
</script>
Then use JQuery Lib...
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
Now use HTML
<div id="header">
<p>This text is non sticky</p>
<p>This text is non sticky</p>
<p>This text is non sticky</p>
<p>This text is non sticky</p>
</div>
<div id="stickytypeheader">
<table width="100%">
<tr>
<td><a href="http://growthpages.com/">Growth pages</a></td>
<td><a href="http://google.com/">Google</a></td>
<td><a href="http://yahoo.com/">Yahoo</a></td>
<td><a href="http://www.bing.com/">Bing</a></td>
<td><a href="#">Visitor</a></td>
</tr>
</table>
</div>
<div id="content">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis
aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.</p>
</div>
Check DEMO HERE
This is a good question I have seen people use Close() when they shouldn't. I looked in the source code for the Selenium Client & WebDriver C# Bindings and found the following.
webDriver.Close()
- Close the browser window that the driver has focus of webDriver.Quit()
- Calls Dispose() webDriver.Dispose()
Closes all browser windows and safely ends the sessionThe code below will dispose the driver object, ends the session and closes all browsers opened during a test whether the test fails or passes.
public IWebDriver Driver;
[SetUp]
public void SetupTest()
{
Driver = WebDriverFactory.GetDriver();
}
[TearDown]
public void TearDown()
{
if (Driver != null)
Driver.Quit();
}
In summary ensure that Quit() or Dispose() is called before exiting the program, and don't use the Close() method unless you're sure of what you're doing.
Note
I found this question when try to figure out a related problem why my VM's were running out of harddrive space. Turns out an exception was causing Quit() or Dispose() to not be called every run which then caused the appData folder to fill the hard drive. So we were using the Quit() method correctly but the code was unreachable. Summary make sure all code paths will clean up your unmanaged objects by using exception safe patterns or implement IDisposable
Also
In the case of RemoteDriver calling Quit() or Dispose() will also close the session on the Selenium Server. If the session isn't closed the log files for that session remain in memory.
I tried with strncpy()
and snprintf()
.
int ridx = 1;
strncpy(word2,word,ridx);
snprintf(word2+ridx,10-ridx,"%s",&word[ridx+1]);
Try dbForge Data Compare for SQL Server. It can compare and sync any databases, even very large ones. Quick, easy, always delivers a correct result. Try it on your database and comment upon the product.
We can recommend you a reliable SQL comparison tool that offer 3 time’s faster comparison and synchronization of table data in your SQL Server databases. It's dbForge Data Compare for SQL Server and dbForge Schema Compare for SQL Server
Main advantages:
Plus free 30-day trial and risk-free purchase with 30-day money back guarantee.
I didn't understand it until I played around with it myself, so I figured there would be others who were confused as well. Say you are working on the user whose id == 6
and whose no_of_logins == 30
when you start.
# 1 (bad)
user.no_of_logins += 1
# result: UPDATE user SET no_of_logins = 31 WHERE user.id = 6
# 2 (bad)
user.no_of_logins = user.no_of_logins + 1
# result: UPDATE user SET no_of_logins = 31 WHERE user.id = 6
# 3 (bad)
setattr(user, 'no_of_logins', user.no_of_logins + 1)
# result: UPDATE user SET no_of_logins = 31 WHERE user.id = 6
# 4 (ok)
user.no_of_logins = User.no_of_logins + 1
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6
# 5 (ok)
setattr(user, 'no_of_logins', User.no_of_logins + 1)
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6
By referencing the class instead of the instance, you can get SQLAlchemy to be smarter about incrementing, getting it to happen on the database side instead of the Python side. Doing it within the database is better since it's less vulnerable to data corruption (e.g. two clients attempt to increment at the same time with a net result of only one increment instead of two). I assume it's possible to do the incrementing in Python if you set locks or bump up the isolation level, but why bother if you don't have to?
If you are going to increment twice via code that produces SQL like SET no_of_logins = no_of_logins + 1
, then you will need to commit or at least flush in between increments, or else you will only get one increment in total:
# 6 (bad)
user.no_of_logins = User.no_of_logins + 1
user.no_of_logins = User.no_of_logins + 1
session.commit()
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6
# 7 (ok)
user.no_of_logins = User.no_of_logins + 1
session.flush()
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6
user.no_of_logins = User.no_of_logins + 1
session.commit()
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6
In case you use fastlane, additional flags can be passed with
gradle(
...
flags: "{your flags}"
)
More information here
TRUE
and FALSE
are keywords, and should not be quoted as strings:
INSERT INTO first VALUES (NULL, 'G22', TRUE);
INSERT INTO first VALUES (NULL, 'G23', FALSE);
By quoting them as strings, MySQL will then cast them to their integer equivalent (since booleans are really just a one-byte INT
in MySQL), which translates into zero for any non-numeric string. Thus, you get 0
for both values in your table.
mysql> SELECT CAST('TRUE' AS SIGNED), CAST('FALSE' AS SIGNED), CAST('12345' AS SIGNED);
+------------------------+-------------------------+-------------------------+
| CAST('TRUE' AS SIGNED) | CAST('FALSE' AS SIGNED) | CAST('12345' AS SIGNED) |
+------------------------+-------------------------+-------------------------+
| 0 | 0 | 12345 |
+------------------------+-------------------------+-------------------------+
INT
representation:mysql> SELECT TRUE, FALSE;
+------+-------+
| TRUE | FALSE |
+------+-------+
| 1 | 0 |
+------+-------+
Note also, that I have replaced your double-quotes with single quotes as are more standard SQL string enclosures. Finally, I have replaced your empty strings for id
with NULL
. The empty string may issue a warning.
This will convert an integer to a 2 digit hex string with the 0x prefix:
strHex = "0x%0.2X" % 255
If the methods above don't work, you can also tell Python to ignore portions of a string that it can't convert to utf-8:
stringnamehere.decode('utf-8', 'ignore')
from https://docs.angularjs.org/api/ng/function/angular.element
angular.element
wraps a raw DOM element or HTML string as a jQuery element (If jQuery is not available, angular.element delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite.")
So you simply could do:
angular.module('myApp.filters', []).
filter('htmlToPlaintext', function() {
return function(text) {
return angular.element(text).text();
}
}
);
Usage:
<div>{{myText | htmlToPlaintext}}</div>
private static void GCD(int a, int b) {
int temp;
// make a greater than b
if (b > a) {
temp = a;
a = b;
b = temp;
}
while (b !=0) {
// gcd of b and a%b
temp = a%b;
// always make a greater than bf
a =b;
b =temp;
}
System.out.println(a);
}
The most recent versions of hibernate JPA provider applies the bean validation constraints (JSR 303) like @NotNull
to DDL by default (thanks to hibernate.validator.apply_to_ddl property
defaults to true
). But there is no guarantee that other JPA providers do or even have the ability to do that.
You should use bean validation annotations like @NotNull
to ensure, that bean properties are set to a none-null value, when validating java beans in the JVM (this has nothing to do with database constraints, but in most situations should correspond to them).
You should additionally use the JPA annotation like @Column(nullable = false)
to give the jpa provider hints to generate the right DDL for creating table columns with the database constraints you want. If you can or want to rely on a JPA provider like Hibernate, which applies the bean validation constraints to DDL by default, then you can omit them.
You can use my simple solution to the problem. It is really straightforward, nothing fancy:
class MemCache(dict):
def __init__(self, fn):
dict.__init__(self)
self.__fn = fn
def __getitem__(self, item):
if item not in self:
dict.__setitem__(self, item, self.__fn(item))
return dict.__getitem__(self, item)
mc = MemCache(lambda x: x*x)
for x in xrange(10):
print mc[x]
for x in xrange(10):
print mc[x]
It indeed lacks expiration funcionality, but you can easily extend it with specifying a particular rule in MemCache c-tor.
Hope code is enough self-explanatory, but if not, just to mention, that cache is being passed a translation function as one of its c-tor params. It's used in turn to generate cached output regarding the input.
Hope it helps
By default .
(any character) does not match newline characters.
This means you can simply match zero or more of any character then append the end tag.
Find: <li><a href="#">.*
Replace: $0</a>
For general information: by default to ssh-connect you may simply use
user: vagrant
password: vagrant
https://www.vagrantup.com/docs/boxes/base.html#quot-vagrant-quot-user
First, try: to see what vagrant insecure_private_key
is in your machine config
$ vagrant ssh-config
Example:
$ vagrant ssh-config
Host default
HostName 127.0.0.1
User vagrant
Port 2222
UserKnownHostsFile /dev/null
StrictHostKeyChecking no
PasswordAuthentication no
IdentityFile C:/Users/konst/.vagrant.d/insecure_private_key
IdentitiesOnly yes
LogLevel FATAL
http://docs.vagrantup.com/v2/cli/ssh_config.html
Second, do:
Change the contents of file insecure_private_key
with the contents of your personal system private key
Or use: Add it to the Vagrantfile:
Vagrant.configure("2") do |config|
config.ssh.private_key_path = "~/.ssh/id_rsa"
config.ssh.forward_agent = true
end
config.ssh.private_key_path
is your local private keyssh-add -L
. If it's not listed, add it with ssh-add ~/.ssh/id_rsa
~/.ssh/authorized_keys
on the Vagrant VM. You can do it by copy-and-pasting or using a tool like ssh-copy-id (user: root
password: vagrant
port: 2222) ssh-copy-id '-p 2222 [email protected]'
If still does not work try this:
Remove insecure_private_key
file from c:\Users\USERNAME\.vagrant.d\insecure_private_key
Run vagrant up
(vagrant will be generate a new insecure_private_key
file)
In other cases, it is helpful to just set forward_agent in Vagrantfile
:
Vagrant::Config.run do |config|
config.ssh.forward_agent = true
end
Useful:
Configurating git may be with git-scm.com
After setup this program and creating personal system private key will be in yours profile path: c:\users\USERNAME\.ssh\id_rsa.pub
PS: Finally - suggest you look at Ubuntu on Windows 10
You can use the bootstrap grid system. as Yoann said
<div class="container">
<div class="row">
<form role="form">
<div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email">
</div>
<div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
<label for="exampleInputEmail1">Name</label>
<input type="text" class="form-control" id="exampleInputEmail1" placeholder="Enter Name">
</div>
<div class="clearfix"></div>
<div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
<div class="form-group col-xs-10 col-sm-4 col-md-4 col-lg-4">
<label for="exampleInputPassword1">Confirm Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Confirm Password">
</div>
</form>
<div class="clearfix">
</div>
</div>
</div>
Often our databases are really big and the take time to take dump directly from remote machine to other machine as our friends other have suggested above.
In such cases what you can do is to take the dump on remote machine using MYSQLDUMP Command
MYSQLDUMP -uuser -p --all-databases > file_name.sql
and than transfer that file from remote server to your machine using Linux SCP Command
scp user@remote_ip:~/mysql_dump_file_name.sql ./
You may also use the stringr
package
library(dplyr)
library(stringr)
My.Data %>% filter(str_detect(x, '^G45'))
You may not use '^'
(starts with) in this case, to obtain the results you need
My search for a similar solution for Visual Studio 2015/Xamarin lead me to this thread. While setting the EditText.InputType
to Android.Text.InputTypes.TextVariationVisiblePassword
properly hid the password during user entry, it did not 'hide' the password if it was visible before the EditText Layout was rendered (before the user submitted their password entry). In order to hide a visible password after the user submits their password and the EditText Layout is rendered, I used EditText.TransformationMethod = PasswordTransformationMethod.Instance
as suggested by LuxuryMode.
Object assign copies one or more source objects to the target object. So we could use Object.assign
here.
Syntax: Object.assign(target, ...sources)
var obj = {};_x000D_
_x000D_
Object.assign(obj, {"1":"aa", "2":"bb"})_x000D_
_x000D_
console.log(obj)
_x000D_
function decodeHTMLContent(htmlText) {
var txt = document.createElement("span");
txt.innerHTML = htmlText;
return txt.innerText;
}
var result = decodeHTMLContent('One & two & three');
console.log(result);
_x000D_
Assign the second variable for the $.each function()
as well, makes it lot easier as it'll provide you the data (so you won't have to work with the indicies).
$.each(json, function(arrayID,group) {
console.log('<a href="'+group.GROUP_ID+'">');
$.each(group.EVENTS, function(eventID,eventData) {
console.log('<p>'+eventData.SHORT_DESC+'</p>');
});
});
Should print out everything you were trying in your question.
http://jsfiddle.net/niklasvh/hZsQS/
edit renamed the variables to make it bit easier to understand what is what.
In oracle db there is a trick for casting int to float (I suppose, it should also work in mysql):
select myintfield + 0.0 as myfloatfield from mytable
While @Heximal's answer works, I don't personally recommend it.
This is because it uses implicit casting. Although you didn't type CAST
, either the SUM()
or the 0.0
need to be cast to be the same data-types, before the +
can happen. In this case the order of precedence is in your favour, and you get a float on both sides, and a float as a result of the +
. But SUM(aFloatField) + 0
does not yield an INT, because the 0
is being implicitly cast to a FLOAT.
I find that in most programming cases, it is much preferable to be explicit. Don't leave things to chance, confusion, or interpretation.
If you want to be explicit, I would use the following.
CAST(SUM(sl.parts) AS FLOAT) * cp.price
-- using MySQL CAST FLOAT requires 8.0
You can try the following to see what happens...
CAST(SUM(sl.parts) AS NUMERIC(10,4)) * CAST(cp.price AS NUMERIC(10,4))
It's very simple:
$(":button:contains('Authenticate')").prop("disabled", true).addClass("ui-state-disabled");
I. In your build.gradle add latest appcompat library, at the time 24.2.1
dependencies {
compile 'com.android.support:appcompat-v7:X.X.X'
// where X.X.X version
}
II. Make your activity extend android.support.v7.app.AppCompatActivity
and implement the DatePickerDialog.OnDateSetListener
interface.
public class MainActivity extends AppCompatActivity
implements DatePickerDialog.OnDateSetListener {
III. Create your DatePickerDialog
setting a context, the implementation of the listener and the start year, month and day of the date picker.
DatePickerDialog datePickerDialog = new DatePickerDialog(
context, MainActivity.this, startYear, starthMonth, startDay);
IV. Show your dialog on the click event listener of your button
((Button) findViewById(R.id.myButton))
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
datePickerDialog.show();
}
});
Are'nt you creating the pdf file but not actually writing the byte array back? Therefore you cannot open the PDF.
out = new FileOutputStream("D:/ABC_XYZ/1.pdf");
out.Write(b, 0, b.Length);
out.Position = 0;
out.Close();
This is in addition to correctly reading in the PDF to byte array.
You can open a new popup window by following code:
var myWindow = window.open("", "newWindow", "width=500,height=700");
//window.open('url','name','specs');
Afterwards, you can add HTML using both myWindow.document.write();
or myWindow.document.body.innerHTML = "HTML";
What I will recommend is that first you create a new html file with any name. In this example I am using
newFile.html
And make sure to add all content in that file such as bootstrap cdn or jquery, means all the links and scripts. Then make a div with some id or use your body and give that a id
. in this example I have given id="mainBody"
to my newFile.html <body>
tag
<body id="mainBody">
Then open this file using
<script>
var myWindow = window.open("newFile.html", "newWindow", "width=500,height=700");
</script>
And add whatever you want to add in your body tag. using following code
<script>
var myWindow = window.open("newFile.html","newWindow","width=500,height=700");
myWindow.onload = function(){
let content = "<button class='btn btn-primary' onclick='window.print();'>Confirm</button>";
myWindow.document.getElementById('mainBody').innerHTML = content;
}
myWindow.window.close();
</script>
it is as simple as that.
You can use print -p -- in the script to do this example :
#!/bin/ksh
mysql -u username -ppassword -D dbname -ss -n -q |&
print -p -- "select count(*) from some_table;"
read -p get_row_count1
print -p -- "select count(*) from some_other_table;"
read -p get_row_count2
print -p exit ;
#
echo $get_row_count1
echo $get_row_count2
#
exit
Solved!
I have had this error for several days. It was driving me crazy because it didnt allow me to use firefox firebug's script debugger. Finally, my error was solved when I removed an empty url in a "background-image: url()" style property.
This has been so much a pain than I really hope somebody can use this advice.
There is no way to retrieve localStorage, sessionStorage or cookie values via javascript in the browser after they've been deleted via javascript.
If what you're really asking is if there is some other way (from outside the browser) to recover that data, that's a different question and the answer will entirely depend upon the specific browser and how it implements the storage of each of those types of data.
For example, Firefox stores cookies as individual files. When a cookie is deleted, its file is deleted. That means that the cookie can no longer be accessed via the browser. But, we know that from outside the browser, using system tools, the contents of deleted files can sometimes be retrieved.
If you wanted to look into this further, you'd have to discover how each browser stores each data type on each platform of interest and then explore if that type of storage has any recovery strategy.
I don't know if this is still the recommended thing to use but the "Object Linking and Embedding" framework allows you to embed certain objects/controls directly into your application. This will probably only work for certain applications, I'm not sure if Notepad is one of them. For really simple things like notepad, you'll probably have an easier time just working with the text box controls provided by whatever medium you're using (e.g. WinForms).
Here's a link to OLE info to get started:
It got frustrating for me as well but I figured out my own answer. Restarting did help but I found why I ran into trouble: I'd copied and pasted an ASP Panel with controls I'd need to re-use. I only had those in the first Div tag working. All others needed to be set up, so I said "Aha ... let me comment out the remaining Div Tags that aren't set up ..." and sure enough, intellisense came right back on.
So not only will it fail to work if the cursor is below a code error but it can fail to work if you're a copy / paste type like me.
Under iOS8 and later use - (NSString *)base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)options
of NSData
Ok to answer this . I simply converted my <
and the >
to <
and >
. What was happening previously is i used to set the text <script>alert('1')</script>
but before setting the text in the input text browserconverts <
and >
as <
and the >
. So hence converting them again to <
and >
since browser will understand that as only tags and converts them , than executing the script inside <input type="text" />
Set a property for the current lesson: currentLesson
. It will hold, obviously, the 'number' of the choosen lesson. On each button click, set the currentLesson
value to 'number'/ order of the button, i.e. for the first button, it will be '1', for the second '2' and so on.
Each button now can be disabled with [disabled] attribute, if it the currentLesson
is not the same as it's order.
HTML
<button (click)="currentLesson = '1'"
[disabled]="currentLesson !== '1'" class="primair">
Start lesson</button>
<button (click)="currentLesson = '2'"
[disabled]="currentLesson !== '2'" class="primair">
Start lesson</button>
.....//so on
Typescript
currentLesson:string;
classes = [
{
name: 'string',
level: 'string',
code: 'number',
currentLesson: '1'
}]
constructor(){
this.currentLesson=this.classes[0].currentLesson
}
Putting everything in a loop:
HTML
<div *ngFor="let class of classes; let i = index">
<button [disabled]="currentLesson !== i + 1" class="primair">
Start lesson {{i + 1}}</button>
</div>
Typescript
currentLesson:string;
classes = [
{
name: 'Lesson1',
level: 1,
code: 1,
},{
name: 'Lesson2',
level: 1,
code: 2,
},
{
name: 'Lesson3',
level: 2,
code: 3,
}]
Accessing package variables in a Script Component (of a Data Flow Task) is not the same as accessing package variables in a Script Task. For a Script Component, you first need to open the Script Transformation Editor (right-click on the component and select "Edit..."). In the Custom Properties section of the Script tab, you can enter (or select) the properties you want to make available to the script, either on a read-only or read-write basis: Then, within the script itself, the variables will be available as strongly-typed properties of the Variables object:
// Modify as necessary
public override void PreExecute()
{
base.PreExecute();
string thePath = Variables.FilePath;
// Do something ...
}
public override void PostExecute()
{
base.PostExecute();
string theNewValue = "";
// Do something to figure out the new value...
Variables.FilePath = theNewValue;
}
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
string thePath = Variables.FilePath;
// Do whatever needs doing here ...
}
One important caveat: if you need to write to a package variable, you can only do so in the PostExecute() method.
Regarding the code snippet:
IDTSVariables100 varCollection = null;
this.VariableDispenser.LockForRead("User::FilePath");
string XlsFile;
XlsFile = varCollection["User::FilePath"].Value.ToString();
varCollection
is initialized to null and never set to a valid value. Thus, any attempt to dereference it will fail.
From the keytool man - it imports certificate chain, if input is given in PKCS#7 format, otherwise only the single certificate is imported. You should be able to convert certificates to PKCS#7 format with openssl, via openssl crl2pkcs7 command.
A tad bit late, but I think the OP was looking for something like:
curl -K myfile.txt --trace-asci output.txt
Solution for the code you posted:
.center{
position:absolute;
width:780px;
height:650px;
left:50%;
top:50%;
margin-left:-390px;
margin-top:-325px;
}
<table class="center" width="780" border="0" align="center" cellspacing="2" bordercolor="#000000" bgcolor="#FFCC66">
<tr>
<td>
<table width="100%" border="0">
<tr>
<td>
<table width="100%" border="0">
<tr>
<td width="150"><img src="images/banners/BAX Company.jpg" width="149" height="130" /></td>
<td width="150"><img src="images/banners/BAX Location.jpg" width="149" height="130" /></td>
<td width="300"><img src="images/banners/Closet.jpg" width="300" height="130" /></td>
<td width="150"><img src="images/banners/BAX Company.jpg" width="149" height="130" /></td>
<td width="150"><img src="images/banners/BAX Location.jpg" width="149" height="130" /></td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table width="100%" border="0">
<tr>
<td width="150"><img src="images/banners/BAX Company.jpg" width="149" height="130" /></td>
<td width="150"><img src="images/banners/BAX Location.jpg" width="149" height="130" /></td>
<td width="300"><img src="images/banners/Closet.jpg" width="300" height="130" /></td>
<td width="150"><img src="images/banners/BAX Company.jpg" width="149" height="130" /></td>
<td width="150"><img src="images/banners/BAX Location.jpg" width="149" height="130" /></td>
</tr>
</table>
</td>
</tr>
</table>
--
How this works?
Example: http://jsfiddle.net/953Yj/
<div class="center">
Lorem ipsum
</div>
.center{
position:absolute;
height: X px;
width: Y px;
left:50%;
top:50%;
margin-top:- X/2 px;
margin-left:- Y/2 px;
}
To position the div
vertically and horizontally, divide X and Y by 2.
You can set visibility to false of other views.
view1.setVisibility(View.GONE);
view2.setVisibility(View.GONE);
...
or
view1.setVisibility(View.INVISIBLE);
view2.setVisibility(View.INVISIBLE);
...
and set
viewN.setVisibility(View.VISIBLE);
You can't pass an anonymous type to a non generic function, unless the parameter type is object
.
public void LogEmployees (object obj)
{
var list = obj as IEnumerable();
if (list == null)
return;
foreach (var item in list)
{
}
}
Anonymous types are intended for short term usage within a method.
From MSDN - Anonymous Types:
You cannot declare a field, a property, an event, or the return type of a method as having an anonymous type. Similarly, you cannot declare a formal parameter of a method, property, constructor, or indexer as having an anonymous type. To pass an anonymous type, or a collection that contains anonymous types, as an argument to a method, you can declare the parameter as type object. However, doing this defeats the purpose of strong typing.
(emphasis mine)
Update
You can use generics to achieve what you want:
public void LogEmployees<T>(IEnumerable<T> list)
{
foreach (T item in list)
{
}
}
@Gabe Martin-Dempesy's answer is helped to me. And I wrote a small script related to it. The usage is very simple.
Install a certificate from host:
> sudo ./java-cert-importer.sh example.com
Remove the certificate that installed already.
> sudo ./java-cert-importer.sh example.com --delete
java-cert-importer.sh
#!/usr/bin/env bash
# Exit on error
set -e
# Ensure script is running as root
if [ "$EUID" -ne 0 ]
then echo "WARN: Please run as root (sudo)"
exit 1
fi
# Check required commands
command -v openssl >/dev/null 2>&1 || { echo "Required command 'openssl' not installed. Aborting." >&2; exit 1; }
command -v keytool >/dev/null 2>&1 || { echo "Required command 'keytool' not installed. Aborting." >&2; exit 1; }
# Get command line args
host=$1; port=${2:-443}; deleteCmd=${3:-${2}}
# Check host argument
if [ ! ${host} ]; then
cat << EOF
Please enter required parameter(s)
usage: ./java-cert-importer.sh <host> [ <port> | default=443 ] [ -d | --delete ]
EOF
exit 1
fi;
if [ "$JAVA_HOME" ]; then
javahome=${JAVA_HOME}
elif [[ "$OSTYPE" == "linux-gnu" ]]; then # Linux
javahome=$(readlink -f $(which java) | sed "s:bin/java::")
elif [[ "$OSTYPE" == "darwin"* ]]; then # Mac OS X
javahome="$(/usr/libexec/java_home)/jre"
fi
if [ ! "$javahome" ]; then
echo "WARN: Java home cannot be found."
exit 1
elif [ ! -d "$javahome" ]; then
echo "WARN: Detected Java home does not exists: $javahome"
exit 1
fi
echo "Detected Java Home: $javahome"
# Set cacerts file path
cacertspath=${javahome}/lib/security/cacerts
cacertsbackup="${cacertspath}.$$.backup"
if ( [ "$deleteCmd" == "-d" ] || [ "$deleteCmd" == "--delete" ] ); then
sudo keytool -delete -alias ${host} -keystore ${cacertspath} -storepass changeit
echo "Certificate is deleted for ${host}"
exit 0
fi
# Get host info from user
#read -p "Enter server host (E.g. example.com) : " host
#read -p "Enter server port (Default 443) : " port
# create temp file
tmpfile="/tmp/${host}.$$.crt"
# Create java cacerts backup file
cp ${cacertspath} ${cacertsbackup}
echo "Java CaCerts Backup: ${cacertsbackup}"
# Get certificate from speficied host
openssl x509 -in <(openssl s_client -connect ${host}:${port} -prexit 2>/dev/null) -out ${tmpfile}
# Import certificate into java cacerts file
sudo keytool -importcert -file ${tmpfile} -alias ${host} -keystore ${cacertspath} -storepass changeit
# Remove temp certificate file
rm ${tmpfile}
# Check certificate alias name (same with host) that imported successfully
result=$(keytool -list -v -keystore ${cacertspath} -storepass changeit | grep "Alias name: ${host}")
# Show results to user
if [ "$result" ]; then
echo "Success: Certificate is imported to java cacerts for ${host}";
else
echo "Error: Something went wrong";
fi;
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Intent intent = new Intent(Activity1.this,Activity2.class);
startActivity(intent);
}
I went through all of these answers and none of them worked for me unfortunately. However, I found this extremely simple way, after about an hour of searching : )
myView.layer.backgroundColor = CGColorCreateGenericRGB(0, 0, 0, 0.9);
In your database what is the type of "IDNO"? You may need to escape the sql here:
$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']);
You can even say:
FollowHyperlink "www.google.com"
If you get Automation Error then use http://
:
ThisWorkbook.FollowHyperlink("http://www.google.com")
When your code does the following:
You run the risk that the permissions change between 1 and 2 because you can't predict what else will be happening on the system at runtime. Therefore, your code should handle the situation where an UnauthorisedAccessException is thrown even if you have previously checked permissions.
Note that the SecurityManager class is used to check CAS permissions and doesn't actually check with the OS whether the current user has write access to the specified location (through ACLs and ACEs). As such, IsGranted will always return true for locally running applications.
Example (derived from Josh's example):
//1. Provide early notification that the user does not have permission to write.
FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename);
if(!SecurityManager.IsGranted(writePermission))
{
//No permission.
//Either throw an exception so this can be handled by a calling function
//or inform the user that they do not have permission to write to the folder and return.
}
//2. Attempt the action but handle permission changes.
try
{
using (FileStream fstream = new FileStream(filename, FileMode.Create))
using (TextWriter writer = new StreamWriter(fstream))
{
writer.WriteLine("sometext");
}
}
catch (UnauthorizedAccessException ex)
{
//No permission.
//Either throw an exception so this can be handled by a calling function
//or inform the user that they do not have permission to write to the folder and return.
}
It's tricky and not recommended to try to programatically calculate the effective permissions from the folder based on the raw ACLs (which are all that are available through the System.Security.AccessControl classes). Other answers on Stack Overflow and the wider web recommend trying to carry out the action to know whether permission is allowed. This post sums up what's required to implement the permission calculation and should be enough to put you off from doing this.
This code will be useful for any internal link on the web
$("[href^='#']").click(function() {
id=$(this).attr("href")
$('html, body').animate({
scrollTop: $(id).offset().top
}, 2000);
});
div { margin: auto; }
This will center your div.
Div by itself is a blockelement. Therefor you need to define the style to the div how to behave.
There is also a solution:
http://www.welefen.com/php-unicode-to-utf8.html
function entity2utf8onechar($unicode_c){
$unicode_c_val = intval($unicode_c);
$f=0x80; // 10000000
$str = "";
// U-00000000 - U-0000007F: 0xxxxxxx
if($unicode_c_val <= 0x7F){ $str = chr($unicode_c_val); } //U-00000080 - U-000007FF: 110xxxxx 10xxxxxx
else if($unicode_c_val >= 0x80 && $unicode_c_val <= 0x7FF){ $h=0xC0; // 11000000
$c1 = $unicode_c_val >> 6 | $h;
$c2 = ($unicode_c_val & 0x3F) | $f;
$str = chr($c1).chr($c2);
} else if($unicode_c_val >= 0x800 && $unicode_c_val <= 0xFFFF){ $h=0xE0; // 11100000
$c1 = $unicode_c_val >> 12 | $h;
$c2 = (($unicode_c_val & 0xFC0) >> 6) | $f;
$c3 = ($unicode_c_val & 0x3F) | $f;
$str=chr($c1).chr($c2).chr($c3);
}
//U-00010000 - U-001FFFFF: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
else if($unicode_c_val >= 0x10000 && $unicode_c_val <= 0x1FFFFF){ $h=0xF0; // 11110000
$c1 = $unicode_c_val >> 18 | $h;
$c2 = (($unicode_c_val & 0x3F000) >>12) | $f;
$c3 = (($unicode_c_val & 0xFC0) >>6) | $f;
$c4 = ($unicode_c_val & 0x3F) | $f;
$str = chr($c1).chr($c2).chr($c3).chr($c4);
}
//U-00200000 - U-03FFFFFF: 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
else if($unicode_c_val >= 0x200000 && $unicode_c_val <= 0x3FFFFFF){ $h=0xF8; // 11111000
$c1 = $unicode_c_val >> 24 | $h;
$c2 = (($unicode_c_val & 0xFC0000)>>18) | $f;
$c3 = (($unicode_c_val & 0x3F000) >>12) | $f;
$c4 = (($unicode_c_val & 0xFC0) >>6) | $f;
$c5 = ($unicode_c_val & 0x3F) | $f;
$str = chr($c1).chr($c2).chr($c3).chr($c4).chr($c5);
}
//U-04000000 - U-7FFFFFFF: 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
else if($unicode_c_val >= 0x4000000 && $unicode_c_val <= 0x7FFFFFFF){ $h=0xFC; // 11111100
$c1 = $unicode_c_val >> 30 | $h;
$c2 = (($unicode_c_val & 0x3F000000)>>24) | $f;
$c3 = (($unicode_c_val & 0xFC0000)>>18) | $f;
$c4 = (($unicode_c_val & 0x3F000) >>12) | $f;
$c5 = (($unicode_c_val & 0xFC0) >>6) | $f;
$c6 = ($unicode_c_val & 0x3F) | $f;
$str = chr($c1).chr($c2).chr($c3).chr($c4).chr($c5).chr($c6);
}
return $str;
}
function entities2utf8($unicode_c){
$unicode_c = preg_replace("/\&\#([\da-f]{5})\;/es", "entity2utf8onechar('\\1')", $unicode_c);
return $unicode_c;
}
For me the answer was to cd into the root directory of the app before running heroku create
or git push heroku master
This should be enough to answer your question: http://docs.oracle.com/javase/tutorial/java/IandI/objectclass.html
The
equals()
method compares two objects for equality and returnstrue
if they are equal. Theequals()
method provided in theObject
class uses the identity operator (==
) to determine whether two objects are equal. For primitive data types, this gives the correct result. For objects, however, it does not. Theequals()
method provided byObject
tests whether the object references are equal—that is, if the objects compared are the exact same object.To test whether two objects are equal in the sense of equivalency (containing the same information), you must override the
equals()
method.
(Partial quote - click through to read examples.)
As seen in Install crontab on CentOS, the crontab package in CentOS is vixie-cron
. Hence, do install it with:
yum install vixie-cron
And then start it with:
service crond start
To make it persistent, so that it starts on boot, use:
chkconfig crond on
On CentOS 7 you need to use cronie
:
yum install cronie
On CentOS 6 you can install vixie-cron
, but the real package is cronie
:
yum install vixie-cron
and
yum install cronie
In both cases you get the same output:
.../...
==================================================================
Package Arch Version Repository Size
==================================================================
Installing:
cronie x86_64 1.4.4-12.el6 base 73 k
Installing for dependencies:
cronie-anacron x86_64 1.4.4-12.el6 base 30 k
crontabs noarch 1.10-33.el6 base 10 k
exim x86_64 4.72-6.el6 epel 1.2 M
Transaction Summary
==================================================================
Install 4 Package(s)
Yes, once the return
statement is executed, the entire function is exited at that very point.
Just imagine what would happen if it did not and continued looping, and executing that return
statement each time? It would invalidate it's meaning of returning a value when you think about it.
<object Margin="left,top,right,bottom"/>
- or -
<object Margin="left,top"/>
- or -
<object Margin="thicknessReference"/>
See here: http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.margin.aspx
You shouldn't worry about this extra call costing you efficiency problems. If there's any cost, it'll be minimal, and should be negligible in the bigger picture of things.
Perhaps the reason why both exist is to offer readability. In the context of many types being converted to String
, then various calls to String.valueOf(SomeType)
may be more readable than various SomeType.toString
calls.
In my case, I needed to deploy two Qt apps on an Ubuntu virtualbox guest. One was command-line ("app"), the other GUI_based ("app_GUI").
I used "ldd app" to find out what the required libs are, and copied them to the Ubuntu guest. While the command-line executable "app" worked ok, the GUI-based executable crashed, giving the "Failed to load platform plugin "xcb" error. I checked ldd for libxcb.so, but this too had no missing dependencies.
The problem seemed to be that while I did copy all the right libraries I accidentally had copied also libraries that were already present at the guest system.. meaning that (a) they were unnecessary to copy them in the first place and (b) worse, copying them produced incompatibilities between the install libraries. Worse still, they were undetectable by ldd like I said..
The solution? Make sure that you copy libraries shown as missing by ldd and absolutely no extra libraries.
JavaScript doesn't have associate arrays. You need to use Objects instead:
var obj = {};
var name = "name";
var val = 2;
obj[name] = val;
console.log(obj);?
To get value you can use now different ways:
console.log(obj.name);?
console.log(obj[name]);?
console.log(obj["name"]);?
Committing .gitignore can be very useful but you want to make sure you don't modify it too much thereafter especially if you regularly switch between branches. If you do you might get cases where files are ignored in a branch and not in the other, forcing you to go manually delete or rename files in your work directory because a checkout failed as it would overwrite a non-tracked file.
Therefore yes, do commit your .gitignore, but not before you are reasonably sure it won't change that much thereafter.
I threw CMS's excellent answer into a quick jQuery extension:
(function($, window) {
$.fn.replaceOptions = function(options) {
var self, $option;
this.empty();
self = this;
$.each(options, function(index, option) {
$option = $("<option></option>")
.attr("value", option.value)
.text(option.text);
self.append($option);
});
};
})(jQuery, window);
It expects an array of objects which contain "text" and "value" keys. So usage is as follows:
var options = [
{text: "one", value: 1},
{text: "two", value: 2}
];
$("#foo").replaceOptions(options);
LibSh link has a good description of how they bound the programming language to the graphics primitives (and obviously, the primitives themselves), and GPU++ describes what its all about, both with code examples.
I know that this approach has been taken before, But I believe that using tables, the layout can be generated easily, Though this may not be the best practice.
<table>
<tr><td>Name:</td><td><input type="text"/></td></tr>
<tr><td>Age:</td><td><input type="text"/></td></tr>
</table>
<!--You can add the fields as you want-->
td{
text-align:right;
}
Not only can you add raw strings to matplotlib but you can also specify the font in matplotlibrc or locally with:
from matplotlib import rc
rc('font', **{'family':'serif','serif':['Palatino']})
rc('text', usetex=True)
This would change your serif latex font. You can also specify the sans-serif Helvetica like so
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
Other options are cursive
and monospace
with their respective font names.
Your label would then be
fig.gca().set_xlabel(r'wavelength $5000 \AA$')
If the font doesn't supply an Angstrom symbol you can try using \mathring{A}
Don't use enums. Reason #78 to not use enums. :) Use integers, which can easily be remoted through Bundle and Parcelable.
It's easy
// MARK: - Gradient
extension CAGradientLayer {
enum Point {
case topLeft
case centerLeft
case bottomLeft
case topCenter
case center
case bottomCenter
case topRight
case centerRight
case bottomRight
var point: CGPoint {
switch self {
case .topLeft:
return CGPoint(x: 0, y: 0)
case .centerLeft:
return CGPoint(x: 0, y: 0.5)
case .bottomLeft:
return CGPoint(x: 0, y: 1.0)
case .topCenter:
return CGPoint(x: 0.5, y: 0)
case .center:
return CGPoint(x: 0.5, y: 0.5)
case .bottomCenter:
return CGPoint(x: 0.5, y: 1.0)
case .topRight:
return CGPoint(x: 1.0, y: 0.0)
case .centerRight:
return CGPoint(x: 1.0, y: 0.5)
case .bottomRight:
return CGPoint(x: 1.0, y: 1.0)
}
}
}
convenience init(start: Point, end: Point, colors: [CGColor], type: CAGradientLayerType) {
self.init()
self.startPoint = start.point
self.endPoint = end.point
self.colors = colors
self.locations = (0..<colors.count).map(NSNumber.init)
self.type = type
}
}
Use like this:-
let fistColor = UIColor.white
let lastColor = UIColor.black
let gradient = CAGradientLayer(start: .topLeft, end: .topRight, colors: [fistColor.cgColor, lastColor.cgColor], type: .radial)
gradient.frame = yourView.bounds
yourView.layer.addSublayer(gradient)
You can have multiple addresses separated by comma
if (cc.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
else
message.setRecipient(Message.RecipientType.CC, new InternetAddress(cc));
First of all unit tests are, by design, supposed to run completely without interaction.
With that aside, I don't think there's a possibility that was thought of.
You could try hacking with the AllocConsole P/Invoke which will open a console even when your current application is a GUI application. The Console
class will then post to the now opened console.
Meteor's strength is in it's real-time updates feature which works well for some of the social applications you see nowadays where you see everyone's updates for what you're working on. These updates center around replicating subsets of a MongoDB collection underneath the covers as local mini-mongo (their client side MongoDB subset) database updates on your web browser (which causes multiple render events to be fired on your templates). The latter part about multiple render updates is also the weakness. If you want your UI to control when the UI refreshes (e.g., classic jQuery AJAX pages where you load up the HTML and you control all the AJAX calls and UI updates), you'll be fighting this mechanism.
Meteor uses a nice stack of Node.js plugins (Handlebars.js, Spark.js, Bootstrap css, etc. but using it's own packaging mechanism instead of npm) underneath along w/ MongoDB for the storage layer that you don't have to think about. But sometimes you end up fighting it as well...e.g., if you want to customize the Bootstrap theme, it messes up the loading sequence of Bootstrap's responsive.css file so it no longer is responsive (but this will probably fix itself when Bootstrap 3.0 is released soon).
So like all "full stack frameworks", things work great as long as your app fits what's intended. Once you go beyond that scope and push the edge boundaries, you might end up fighting the framework...
Use typeof
or instanceof
:
const assert = require('assert');
function myFunction(Date myDate, String myString)
{
assert( typeof(myString) === 'string', 'Error message about incorrect arg type');
assert( myDate instanceof Date, 'Error message about incorrect arg type');
}
The svg-tag needs the namespace attribute xmlns:
<svg xmlns="http://www.w3.org/2000/svg"></svg>
Using regedit, remove the entries corresponding to java 7. It will work.