What's going wrong with what you have? What error do you get, or what result do or don't you get that doesn't match your expectations?
I can see the following issues with that SP, which may or may not relate to your problem:
)
after @BrandName
in your SELECT
(at the end)@CategoryID
or @BrandName
to anything anywhere (they're local variables, but you don't assign values to them)Edit Responding to your comment: The error is telling you that you haven't declared any parameters for the SP (and you haven't), but you called it with parameters. Based on your reply about @CategoryID
, I'm guessing you wanted it to be a parameter rather than a local variable. Try this:
CREATE PROCEDURE AddBrand
@BrandName nvarchar(50),
@CategoryID int
AS
BEGIN
DECLARE @BrandID int
SELECT @BrandID = BrandID FROM tblBrand WHERE BrandName = @BrandName
INSERT INTO tblBrandinCategory (CategoryID, BrandID) VALUES (@CategoryID, @BrandID)
END
You would then call this like this:
EXEC AddBrand 'Gucci', 23
...assuming the brand name was 'Gucci' and category ID was 23.
Try to set the property when starting JVM, for example, add -Djava.net.preferIPv4Stack=true
.
You can't set it when code running, as the java.net just read it when jvm starting.
And about the root cause, this article give some hint: Why do I need java.net.preferIPv4Stack=true only on some windows 7 systems?.
My case is different, I had to kill running Nginx to restart it.
Instead of
sudo systemctl restart nginx
I had to use:
sudo pkill -f nginx & wait $!
sudo systemctl start nginx
Curl does that by default without any parameters or flags, I would use it for your purposes:
curl $url > /dev/null 2>&1
Curl is more about streams and wget is more about copying sites based on this comparison.
Note that this isn't perfect, since if you had something like, say, <a title=">">
it would break. However, it's about the closest you'd get in non-library Python without a really complex function:
import re
TAG_RE = re.compile(r'<[^>]+>')
def remove_tags(text):
return TAG_RE.sub('', text)
However, as lvc mentions xml.etree
is available in the Python Standard Library, so you could probably just adapt it to serve like your existing lxml
version:
def remove_tags(text):
return ''.join(xml.etree.ElementTree.fromstring(text).itertext())
On a Mac, SQLEditor will do what you want.
You can also use "bold" and "italic" instead of "normal" here. "Verdana" can be used for fontname..
But another question is this: How do you set the color of the text You write?
Answer: You use the turtle.color() method or turtle.fillcolor(), like this:
turtle.fillcolor("blue")
or just:
turtle.color("orange")
These calls must come before the turtle.write() command..
best explanation of Cohesion comes from Uncle Bob's Clean Code:
Classes should have a small number of instance variables. Each of the methods of a class should manipulate one or more of those variables. In general the more variables a method manipulates the more cohesive that method is to its class. A class in which each variable is used by each method is maximally cohesive.
In general it is neither advisable nor possible to create such maximally cohesive classes; on the other hand, we would like cohesion to be high. When cohesion is high, it means that the methods and variables of the class are co-dependent and hang together as a logical whole.
The strategy of keeping functions small and keeping parameter lists short can sometimes lead to a proliferation of instance variables that are used by a subset of methods. When this happens, it almost always means that there is at least one other class trying to get out of the larger class. You should try to separate the variables and methods into two or more classes such that the new classes are more cohesive.
If you only want to check if a single value is in an array, then Paolo's code will do the job. If you want to check which values are common to both arrays, then you'll want something like this (using Paolo's inArray function):
function arrayIntersect(a, b) {
var intersection = [];
for(var i = 0; i < a.length; i++) {
if(inArray(b, a[i]))
intersection.push(a[i]);
}
return intersection;
}
This wil return an array of values that are in both a
and b
. (Mathematically, this is an intersection of the two arrays.)
EDIT: See Paolo's Edited Code for the solution to your problem. :)
I'm facing same issue and resolving through
git add .
git commit -m "message"
git remote set-url origin https://[email protected]/aceofwings/RotairERP.git
then
git pull
I found this work for me!
var fd = new FormData();
$.each($('.modal-banner [type=file]'), function(index, file) {
fd.append('item[]', $('input[type=file]')[index].files[0]);
});
$.ajax({
type: 'POST',
url: 'your/path/',
data: fd,
dataType: 'json',
contentType: false,
processData: false,
cache: false,
success: function (response) {
console.log(response);
},
error: function(err){
console.log(err);
}
}).done(function() {
// do something....
});
return false;
I think you'll get what you want with the -maxdepth 1
option, based on your current command structure. If not, you can try looking at the man page for find
.
Relevant entry (for convenience's sake):
-maxdepth levels
Descend at most levels (a non-negative integer) levels of direc-
tories below the command line arguments. `-maxdepth 0' means
only apply the tests and actions to the command line arguments.
Your options basically are:
# Do NOT show hidden files (beginning with ".", i.e., .*):
find DirsRoot/* -maxdepth 0 -type f
Or:
# DO show hidden files:
find DirsRoot/ -maxdepth 1 -type f
This is how can you have automatic & flexible createDate/lastModified fields using triggers:
First define them like this:
CREATE TABLE `entity` (
`entityid` int(11) NOT NULL AUTO_INCREMENT,
`createDate` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`lastModified` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`name` varchar(255) DEFAULT NULL,
`comment` text,
PRIMARY KEY (`entityid`),
)
Then add these triggers:
DELIMITER ;;
CREATE trigger entityinsert BEFORE INSERT ON entity FOR EACH ROW BEGIN SET NEW.createDate=IF(ISNULL(NEW.createDate) OR NEW.createDate='0000-00-00 00:00:00', CURRENT_TIMESTAMP, IF(NEW.createDate<CURRENT_TIMESTAMP, NEW.createDate, CURRENT_TIMESTAMP));SET NEW.lastModified=NEW.createDate; END;;
DELIMITER ;
CREATE trigger entityupdate BEFORE UPDATE ON entity FOR EACH ROW SET NEW.lastModified=IF(NEW.lastModified<OLD.lastModified, OLD.lastModified, CURRENT_TIMESTAMP);
But here's the nice part:
m1 = (y2 - y1) / (x2 - x1)
if perpendicular two lines:
m1*m2 = -1
then
m2 = -1 / m1 //if (m1 == 0, then your line should have an equation like x = b)
y = m2*x + b //b is offset of new perpendicular line..
b is something if you want to pass it from a point you defined
I had the same problem, but its an easy fix! Just set
status bar is initially hidden = YES
then add an row by clicking on the plus right after the text status bar is initially hidden
, then set the text to
view controller-based status bar appearance
by clicking the arrows, and set it to NO
Hope this helps!
When you say
(a['x']==1) and (a['y']==10)
You are implicitly asking Python to convert (a['x']==1)
and (a['y']==10)
to boolean values.
NumPy arrays (of length greater than 1) and Pandas objects such as Series do not have a boolean value -- in other words, they raise
ValueError: The truth value of an array is ambiguous. Use a.empty, a.any() or a.all().
when used as a boolean value. That's because its unclear when it should be True or False. Some users might assume they are True if they have non-zero length, like a Python list. Others might desire for it to be True only if all its elements are True. Others might want it to be True if any of its elements are True.
Because there are so many conflicting expectations, the designers of NumPy and Pandas refuse to guess, and instead raise a ValueError.
Instead, you must be explicit, by calling the empty()
, all()
or any()
method to indicate which behavior you desire.
In this case, however, it looks like you do not want boolean evaluation, you want element-wise logical-and. That is what the &
binary operator performs:
(a['x']==1) & (a['y']==10)
returns a boolean array.
By the way, as alexpmil notes,
the parentheses are mandatory since &
has a higher operator precedence than ==
.
Without the parentheses, a['x']==1 & a['y']==10
would be evaluated as a['x'] == (1 & a['y']) == 10
which would in turn be equivalent to the chained comparison (a['x'] == (1 & a['y'])) and ((1 & a['y']) == 10)
. That is an expression of the form Series and Series
.
The use of and
with two Series would again trigger the same ValueError
as above. That's why the parentheses are mandatory.
Update query may have some issues
$query = "UPDATE anstalld SET mandag = '$mandag', tisdag = '$tisdag', onsdag = '$onsdag', torsdag = '$torsdag', fredag = '$fredag' WHERE namn = '$namn' ";
echo $query;
Please make sure that, your variable not having values with qoutes ( ' ), May be the query is breaking somewhere.
echo the query and try to execute in phpmyadmin itself. Then you can find the issues.
Open the file with a FileInputStream
, then use an InputStreamReader
with the UTF-8 Charset
to read characters from the stream, and use a BufferedReader
to read lines, e.g. via BufferedReader#readLine
, which will give you a string. Once you have the string, you can check for characters that aren't what you consider to be printable.
E.g. (without error checking), using try-with-resources (which is in vaguely modern Java version):
String line;
try (
InputStream fis = new FileInputStream("the_file_name");
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
BufferedReader br = new BufferedReader(isr);
) {
while ((line = br.readLine()) != null) {
// Deal with the line
}
}
The assert statement has two forms.
The simple form, assert <expression>
, is equivalent to
if __?debug__:
if not <expression>: raise AssertionError
The extended form, assert <expression1>, <expression2>
, is equivalent to
if __?debug__:
if not <expression1>: raise AssertionError, <expression2>
In my case, I left out wrapper sub folder while copying gradle folder and got the same error.
Could not find or load main class org.gradle.wrapper.GradleWrapperMain
make sure you have the correct folder structure if you copy wrapper from other location.
+-- build.gradle +-- gradle ¦ +-- wrapper ¦ +-- gradle-wrapper.jar ¦ +-- gradle-wrapper.properties +-- gradlew +-- gradlew.bat +-- settings.gradle
Command | New Files | Modified Files | Deleted Files | Description |
---|---|---|---|---|
git add -A |
?? | ?? | ?? | Stage all (new, modified, deleted) files |
git add . |
?? | ?? | ? | Stage new and modified files only in current folder |
git add -u |
? | ?? | ?? | Stage modified and deleted files only |
Command | New Files | Modified Files | Deleted Files | Description |
---|---|---|---|---|
git add -A |
?? | ?? | ?? | Stage all (new, modified, deleted) files |
git add . |
?? | ?? | ?? | Stage all (new, modified, deleted) files in current folder |
git add --ignore-removal . |
?? | ?? | ? | Stage new and modified files only |
git add -u |
? | ?? | ?? | Stage modified and deleted files only |
git add -A
is equivalent to git add --all
git add -u
is equivalent to git add --update
Here is the code and demo for Adding the marker, deleting any of the marker and also getting all the present/added markers :
Here is the entire JSFiddle code . Also here is the full page demo.
// Script for adding marker on map click
map.on('click', onMapClick);
function onMapClick(e) {
var geojsonFeature = {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [e.latlng.lat, e.latlng.lng]
}
}
var marker;
L.geoJson(geojsonFeature, {
pointToLayer: function(feature, latlng){
marker = L.marker(e.latlng, {
title: "Resource Location",
alt: "Resource Location",
riseOnHover: true,
draggable: true,
}).bindPopup("<input type='button' value='Delete this marker' class='marker-delete-button'/>");
marker.on("popupopen", onPopupOpen);
return marker;
}
}).addTo(map);
}
// Function to handle delete as well as other events on marker popup open
function onPopupOpen() {
var tempMarker = this;
// To remove marker on click of delete button in the popup of marker
$(".marker-delete-button:visible").click(function () {
map.removeLayer(tempMarker);
});
}
// getting all the markers at once
function getAllMarkers() {
var allMarkersObjArray = []; // for marker objects
var allMarkersGeoJsonArray = []; // for readable geoJson markers
$.each(map._layers, function (ml) {
if (map._layers[ml].feature) {
allMarkersObjArray.push(this)
allMarkersGeoJsonArray.push(JSON.stringify(this.toGeoJSON()))
}
})
console.log(allMarkersObjArray);
}
// any html element such as button, div to call the function()
$(".get-markers").on("click", getAllMarkers);
Cookies that 'expire at end of the session' expire unpredictably from the user's perspective!
On iOS with Safari they expire whenever you switch apps!
On Android with Chrome they don't expire when you close the browser.
On Windows desktop running Chrome they expire when you close the browser. That's not when you close your website's tab; its when you close all tabs. Nor do they expire if there are any other browser windows open. If users run web apps as windows they might not even know they are browser windows. So your cookie's life depends on what the user is doing with some apparently unrelated app.
I would stick with normal approach to call the file directly, but if you really want to call a function, have a look at JSON-RPC (JSON Remote Procedure Call).
You basically send a JSON string in a specific format to the server, e.g.
{ "method": "echo", "params": ["Hello JSON-RPC"], "id": 1}
which includes the function to call and the parameters of that function.
Of course the server has to know how to handle such requests.
Here is jQuery plugin for JSON-RPC and e.g. the Zend JSON Server as server implementation in PHP.
This might be overkill for a small project or less functions. Easiest way would be karim's answer. On the other hand, JSON-RPC is a standard.
I just had this problem. Turns out the XML file (not the contents) was not encoded in utf-8, but in ISO-8859-1. You can check this on a Mac with file -I xml_filename
.
I used Sublime to change the file encoding to utf-8, and lxml imported it no issues.
Put a file named log4j.xml
into your classpath. Contents are e.g.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="stdout" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ABSOLUTE} %5p %t %c{1}:%L - %m%n"/>
</layout>
</appender>
<root>
<level value="debug"/>
<appender-ref ref="stdout"/>
</root>
</log4j:configuration>
I like to add these functions in the head.
window.log=function(){if(this.console){console.log(Array.prototype.slice.call(arguments));}};
jQuery.fn.log=function (msg){console.log("%s: %o", msg,this);return this;};
Now log won't break IE I can enable it or disable it in one place I can log inline
$(".classname").log(); //show an array of all elements with classname class
If your OS is Unix base use this code:
import os
def check_process(name):
output = []
cmd = "ps -aef | grep -i '%s' | grep -v 'grep' | awk '{ print $2 }' > /tmp/out"
os.system(cmd % name)
with open('/tmp/out', 'r') as f:
line = f.readline()
while line:
output.append(line.strip())
line = f.readline()
if line.strip():
output.append(line.strip())
return output
Then call it and pass it a process name to get all PIDs.
>>> check_process('firefox')
['499', '621', '623', '630', '11733']
The command is lowercase: touch filename
.
Keep in mind that touch
will only create a new file if it does not exist! Here's some docs for good measure: http://unixhelp.ed.ac.uk/CGI/man-cgi?touch
If you always want an empty file, one way to do so would be to use:
echo "" > filename
you can try this simple 12 line of code for delete folder or folder files... happy coding... ;) :)
function deleteAll($str) {
if (is_file($str)) {
return unlink($str);
}
elseif (is_dir($str)) {
$scan = glob(rtrim($str,'/').'/*');
foreach($scan as $index=>$path) {
$this->deleteAll($path);
}
return @rmdir($str);
}
}
If using pip 6.0 or newer, try adding the --no-cache-dir
option (source).
If using pip older than pip 6.0, upgrade it with pip install -U pip
.
This error occurs because if you choosing the path deep in JDK or JRE. The exact path that should be chosen is in my case 64 bit
C:\Program Files\Java\jdk1.8.0_91
if 32 bit
C:\Program Files (86)\Java\jdk1.8.0_91
With OleDBConnection -> connect to Oracle
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "Provider=MSDAORA;Data Source=oracle;Persist Security Info=True;User ID=system;Password=**********;Unicode=True";
OleDbCommand comd1 = new OleDbCommand("select name from table", con);
OleDbDataReader DR = comd1.ExecuteReader();
while (DR.Read())
{
comboBox_delete.Items.Add(DR[0]);
}
con.Close();
That's all :)
VAR1=value1 VAR2=value2 myScript args ...
You can get its shape
with:
print((df.count(), len(df.columns)))
Just because the bean injected into the controller is prototype-scoped doesn't mean the controller is!
In case someone has this while trying to compile an Android project, there is an alternative Nullable implementation in android.support.annotation.Nullable
. So take care which package you've referenced in your import
s.
Amazon EC2 cannot offer Mac OS X EC2 instances due to Apple's tight licensing to only allow it to legally run on Apple hardware and the current EC2 infrastructure relies upon virtualized hardware.
Apple Mac image on Amazon EC2?
Can you run OS X on an Amazon EC2 instance?
There are other companies that do provide Mac OS X hosting, presumably on Apple hardware. One example is Go Daddy:
Go Daddy Product Catalog (see Mac® Powered Cloud Servers under Web Hosting)
To find more, search for "Mac OS X hosting" and you'll find more options.
I faced this issue because my $(elem).click(function(){});
script was placed inline in a div that was set to style="display:none;"
.
When the css display was switched to block, the script would add the event listener a second time. I moved the script to a separate .js file and the duplicate event listener was no longer initiated.
This problem happened to me because I had the hibernate.default_schema
set to a different database than the one in the DataSource.
Being strict on my mysql user permissions, when hibernate tried to query a table it queried the one in the hibernate.default_schema
database for which the user had no permissions.
Its unfortunate that mysql does not correctly specify the database in this error message, as that would've cleared things up straight away.
From PEP 249, which is usually implemented by Python database APIs:
Cursor Objects should respond to the following methods and attributes:
[…]
.rowcount
This read-only attribute specifies the number of rows that the last .execute*() produced (for DQL statements like 'select') or affected (for DML statements like 'update' or 'insert').
But be careful—it goes on to say:
The attribute is -1 in case no
.execute*()
has been performed on the cursor or the rowcount of the last operation is cannot be determined by the interface. [7]Note:
Future versions of the DB API specification could redefine the latter case to have the object returnNone
instead of -1.
So if you've executed your statement, and it works, and you're certain your code will always be run against the same version of the same DBMS, this is a reasonable solution.
I usually store phone numbers as a BIGINT in E164 format.
E164 never start with a 0, with the first few digits being the country code.
+441234567890
+44 (0)1234 567890
01234 567890
etc. would be stored as 441234567890
.
Since some of the answers are outdated, I would like to provide my own -
To integrate ZXing library into your Android app as suggested by their Wiki, you need to add 2 Java files to your project:
Then in Android Studio add the following line to build.gradle file:
dependencies {
....
compile 'com.google.zxing:core:3.2.1'
}
Or if still using Eclipse with ADT-plugin add core.jar file to the libs subdirectory of your project (here fullscreen Windows and fullscreen Mac):
Finally add this code to your MainActivity.java:
public void scanQRCode(View v) {
IntentIntegrator integrator = new IntentIntegrator(MainActivity.this);
integrator.initiateScan(IntentIntegrator.QR_CODE_TYPES);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult result =
IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (result != null) {
String contents = result.getContents();
if (contents != null) {
showDialog(R.string.result_succeeded, result.toString());
} else {
showDialog(R.string.result_failed,
getString(R.string.result_failed_why));
}
}
}
private void showDialog(int title, CharSequence message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(title);
builder.setMessage(message);
builder.setPositiveButton(R.string.ok_button, null);
builder.show();
}
The resulting app will ask to install and start Barcode Scanner app by ZXing (which will return to your app automatically after scanning):
Additionally, if you would like to build and run the ZXing Test app as inspiration for your own app:
Then you need 4 Java files from GitHub:
And 3 Jar files from Maven repository:
(You can build the Jar files yourself with mvn package
- if your check out ZXing from GitHub and install ant and maven tools at your computer).
Note: if your project does not recognize the Jar files, you might need to up the Java version in the Project Properties:
Below is a batch file that will run corflags.exe
against all dlls
and exes
in the current working directory and all sub-directories, parse the results and display the target architecture of each.
Depending on the version of corflags.exe
that is used, the line items in the output will either include 32BIT
, or 32BITREQ
(and 32BITPREF
). Whichever of these two is included in the output is the critical line item that must be checked to differentiate between Any CPU
and x86
. If you are using an older version of corflags.exe
(pre Windows SDK v8.0A), then only the 32BIT
line item will be present in the output, as others have indicated in past answers. Otherwise 32BITREQ
and 32BITPREF
replace it.
This assumes corflags.exe
is in the %PATH%
. The simplest way to ensure this is to use a Developer Command Prompt
. Alternatively you could copy it from it's default location.
If the batch file below is run against an unmanaged dll
or exe
, it will incorrectly display it as x86
, since the actual output from Corflags.exe
will be an error message similar to:
corflags : error CF008 : The specified file does not have a valid managed header
@echo off
echo.
echo Target architecture for all exes and dlls:
echo.
REM For each exe and dll in this directory and all subdirectories...
for %%a in (.exe, .dll) do forfiles /s /m *%%a /c "cmd /c echo @relpath" > testfiles.txt
for /f %%b in (testfiles.txt) do (
REM Dump corflags results to a text file
corflags /nologo %%b > corflagsdeets.txt
REM Parse the corflags results to look for key markers
findstr /C:"PE32+">nul .\corflagsdeets.txt && (
REM `PE32+` indicates x64
echo %%~b = x64
) || (
REM pre-v8 Windows SDK listed only "32BIT" line item,
REM newer versions list "32BITREQ" and "32BITPREF" line items
findstr /C:"32BITREQ : 0">nul /C:"32BIT : 0" .\corflagsdeets.txt && (
REM `PE32` and NOT 32bit required indicates Any CPU
echo %%~b = Any CPU
) || (
REM `PE32` and 32bit required indicates x86
echo %%~b = x86
)
)
del corflagsdeets.txt
)
del testfiles.txt
echo.
Well, you can achieve that with Jackson, too. (and it seems to be more comfortable since you were considering using jackson).
Use ObjectMapper
's convertValue
method:
final ObjectMapper mapper = new ObjectMapper(); // jackson's objectmapper
final MyPojo pojo = mapper.convertValue(map, MyPojo.class);
No need to convert into JSON string or something else; direct conversion does much faster.
There is no easy way to return the DDL. However you can get most of the details from Information Schema Views and System Views.
SELECT ORDINAL_POSITION, COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH
, IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Customers'
SELECT CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.CONSTRAINT_TABLE_USAGE
WHERE TABLE_NAME = 'Customers'
SELECT name, type_desc, is_unique, is_primary_key
FROM sys.indexes
WHERE [object_id] = OBJECT_ID('dbo.Customers')
To disable resizing completely:
textarea {
resize: none;
}
To allow only vertical resizing:
textarea {
resize: vertical;
}
To allow only horizontal resizing:
textarea {
resize: horizontal;
}
Or you can limit size:
textarea {
max-width: 100px;
max-height: 100px;
}
To limit size to parents width and/or height:
textarea {
max-width: 100%;
max-height: 100%;
}
The params object is included in $stateParams, but won't be part of the url.
1) In the route configuration:
$stateProvider.state('edit_user', {
url: '/users/:user_id/edit',
templateUrl: 'views/editUser.html',
controller: 'editUserCtrl',
params: {
paramOne: { objectProperty: "defaultValueOne" }, //default value
paramTwo: "defaultValueTwo"
}
});
2) In the controller:
.controller('editUserCtrl', function ($stateParams, $scope) {
$scope.paramOne = $stateParams.paramOne;
$scope.paramTwo = $stateParams.paramTwo;
});
3A) Changing the State from a controller
$state.go("edit_user", {
user_id: 1,
paramOne: { objectProperty: "test_not_default1" },
paramTwo: "from controller"
});
3B) Changing the State in html
<div ui-sref="edit_user({ user_id: 3, paramOne: { objectProperty: 'from_html1' }, paramTwo: 'fromhtml2' })"></div>
Let's say you have this image:
to make a circle out of this you only need to add
.circle {
border-radius: 50%;
width: 100px;
height: 100px;
}
So if you have a div you can do the same thing.
Check the example below:
.circle {_x000D_
border-radius: 50%;_x000D_
width: 100px;_x000D_
height: 100px; _x000D_
animation: stackoverflow-example infinite 20s linear;_x000D_
pointer-events: none;_x000D_
}_x000D_
_x000D_
@keyframes stackoverflow-example {_x000D_
from {_x000D_
transform: rotate(0deg);_x000D_
}_x000D_
to {_x000D_
transform: rotate(360deg);_x000D_
}_x000D_
}
_x000D_
<div>_x000D_
<img class="circle" src="https://www.sitepoint.com/wp-content/themes/sitepoint/assets/images/icon.javascript.png">_x000D_
</div>
_x000D_
I had similar problem and in my opinion best option is to use just a little bit of javascript or jquery.
You can get wanted divs to be same height by getting highest div value and applying that value to all other divs. If you have many divs and many solutions i suggest to write little advance js code to find out which of all divs is the highest and then use it's value.
With jquery and 2 divs it's very simple, here is example code:
$('.smaller-div').css('height',$('.higher-div').css('height'));
And for the end, there is 1 last thing. Their padding (top and bottom) must be the same ! If one have larger padding you need to eliminate padding difference.
If you want refresh the page you could use like this, but refreshing the page is usually not the best method, it better to try just update the content that you need to be updated.
javascript:
<script language="javascript">
setTimeout(function(){
window.location.reload(1);
}, 30000);
</script>
<input type="button" value="submit" style="height: 100px; width: 100px; left: 250; top: 250;">
Use this with your requirements.
Simplest answer:
the return code from a function can be only a value in the range from 0 to 255 . To store this value in a variable you have to do like in this example:
#!/bin/bash
function returnfunction {
# example value between 0-255 to be returned
return 23
}
# note that the value has to be stored immediately after the function call :
returnfunction
myreturnvalue=$?
echo "myreturnvalue is "$myreturnvalue
$a = array(1, 2, 3, 4);
$b = array_merge(array_slice($a, 0, 2), array(5), array_slice($a, 2));
// $b = array(1, 2, 5, 3, 4)
If you want the .wrapper
to be fullscreen, just add the following in the wrapper class:
position: absolute;
width: 100%;
height: 100%;
You can also add top: 0
and left:0
You could test the url via AJAX and read the status code - that is if the URL is in the same domain.
If it's a remote domain, you could have a server script on your own domain check out a remote URL.
Stopping the thread in midway using Thread.stop()
is not a good practice. More appropriate way is to make the thread return programmatically. Let the Runnable object use a shared variable in the run()
method. Whenever you want the thread to stop, use that variable as a flag.
EDIT: Sample code
class MyThread implements Runnable{
private Boolean stop = false;
public void run(){
while(!stop){
//some business logic
}
}
public Boolean getStop() {
return stop;
}
public void setStop(Boolean stop) {
this.stop = stop;
}
}
public class TestStop {
public static void main(String[] args){
MyThread myThread = new MyThread();
Thread th = new Thread(myThread);
th.start();
//Some logic goes there to decide whether to
//stop the thread or not.
//This will compell the thread to stop
myThread.setStop(true);
}
}
Leaving aside the fact that your text file is broken (U+2018 is a left quotation mark, not an apostrophe): iconv can be used to transliterate unicode characters to ascii.
You'll have to google for "iconvcodec", since the module seems not to be supported anymore and I can't find a canonical home page for it.
>>> import iconvcodec
>>> from locale import setlocale, LC_ALL
>>> setlocale(LC_ALL, '')
>>> u'\u2018'.encode('ascii//translit')
"'"
Alternatively you can use the iconv
command line utility to clean up your file:
$ xxd foo
0000000: e280 980a ....
$ iconv -t 'ascii//translit' foo | xxd
0000000: 270a '.
You can do it using group by:
c_maxes = df.groupby(['A', 'B']).C.transform(max)
df = df.loc[df.C == c_maxes]
c_maxes
is a Series
of the maximum values of C
in each group but which is of the same length and with the same index as df
. If you haven't used .transform
then printing c_maxes
might be a good idea to see how it works.
Another approach using drop_duplicates
would be
df.sort('C').drop_duplicates(subset=['A', 'B'], take_last=True)
Not sure which is more efficient but I guess the first approach as it doesn't involve sorting.
EDIT:
From pandas 0.18
up the second solution would be
df.sort_values('C').drop_duplicates(subset=['A', 'B'], keep='last')
or, alternatively,
df.sort_values('C', ascending=False).drop_duplicates(subset=['A', 'B'])
In any case, the groupby
solution seems to be significantly more performing:
%timeit -n 10 df.loc[df.groupby(['A', 'B']).C.max == df.C]
10 loops, best of 3: 25.7 ms per loop
%timeit -n 10 df.sort_values('C').drop_duplicates(subset=['A', 'B'], keep='last')
10 loops, best of 3: 101 ms per loop
In general you can say session.gc_maxlifetime specifies the maximum lifetime since the last change of your session data (not the last time session_start
was called!). But PHP’s session handling is a little bit more complicated.
Because the session data is removed by a garbage collector that is only called by session_start
with a probability of session.gc_probability devided by session.gc_divisor. The default values are 1 and 100, so the garbage collector is only started in only 1% of all session_start
calls. That means even if the the session is already timed out in theory (the session data had been changed more than session.gc_maxlifetime seconds ago), the session data can be used longer than that.
Because of that fact I recommend you to implement your own session timeout mechanism. See my answer to How do I expire a PHP session after 30 minutes? for more details.
Do it in this format:
classmehodisin.methodname();
For example:
MyClass1.clearscreen();
I hope this helped.` Note:The method must be static.
This Gist by Eldon McGuinness is by far the most complete implementation of a JavaScript query string parser that I've seen so far.
Unfortunately, it's written as a jQuery plugin.
I rewrote it to vanilla JS and made a few improvements :
function parseQuery(str) {
var qso = {};
var qs = (str || document.location.search);
// Check for an empty querystring
if (qs == "") {
return qso;
}
// Normalize the querystring
qs = qs.replace(/(^\?)/, '').replace(/;/g, '&');
while (qs.indexOf("&&") != -1) {
qs = qs.replace(/&&/g, '&');
}
qs = qs.replace(/([\&]+$)/, '');
// Break the querystring into parts
qs = qs.split("&");
// Build the querystring object
for (var i = 0; i < qs.length; i++) {
var qi = qs[i].split("=");
qi = qi.map(function(n) {
return decodeURIComponent(n)
});
if (typeof qi[1] === "undefined") {
qi[1] = null;
}
if (typeof qso[qi[0]] !== "undefined") {
// If a key already exists then make this an object
if (typeof (qso[qi[0]]) == "string") {
var temp = qso[qi[0]];
if (qi[1] == "") {
qi[1] = null;
}
qso[qi[0]] = [];
qso[qi[0]].push(temp);
qso[qi[0]].push(qi[1]);
} else if (typeof (qso[qi[0]]) == "object") {
if (qi[1] == "") {
qi[1] = null;
}
qso[qi[0]].push(qi[1]);
}
} else {
// If no key exists just set it as a string
if (qi[1] == "") {
qi[1] = null;
}
qso[qi[0]] = qi[1];
}
}
return qso;
}
var results = parseQuery("?foo=bar&foo=boo&roo=bar;bee=bop;=ghost;=ghost2;&;checkbox%5B%5D=b1;checkbox%5B%5D=b2;dd=;http=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab&http=http%3A%2F%2Fw3schools2.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab");
{
"foo": ["bar", "boo" ],
"roo": "bar",
"bee": "bop",
"": ["ghost", "ghost2"],
"checkbox[]": ["b1", "b2"],
"dd": null,
"http": [
"http://w3schools.com/my test.asp?name=ståle&car=saab",
"http://w3schools2.com/my test.asp?name=ståle&car=saab"
]
}
See also this Fiddle.
A bit more readable and simple approach could be achieved with the script below:
$Directory = "./"
Get-ChildItem $Directory -Recurse | % {
if ($_.Attributes -eq "Directory") {
Write-Host $_.FullName
}
}
Hope this helps!
Just use look-arounds to solve this:
(?<=^|,)garp(?=$|,)
The difference with look-arounds and just regular groups are that with regular groups the comma would be part of the match, and with look-arounds it wouldn't. In this case it doesn't make a difference though.
Without any server side solution, Theres is only one way in which a secure page can get something from a insecure page/request and that's thought postMessage and a popup
I said popup cuz the site isn't allowed to mix content. But a popup isn't really mixing. It has it's own window but are still able to communicate with the opener with postMessage.
So you can open a new http-page with window.open(...)
and have that making the request for you (that is if the site is using CORS as well)
XDomain came to mind when i wrote this but here is a modern approach using the new fetch api, the advantage is the streaming of large files, the downside is that it won't work in all browser
You put this proxy script on any http page
onmessage = evt => {
const port = evt.ports[0]
fetch(...evt.data).then(res => {
// the response is not clonable
// so we make a new plain object
const obj = {
bodyUsed: false,
headers: [...res.headers],
ok: res.ok,
redirected: res.redurected,
status: res.status,
statusText: res.statusText,
type: res.type,
url: res.url
}
port.postMessage(obj)
// Pipe the request to the port (MessageChannel)
const reader = res.body.getReader()
const pump = () => reader.read()
.then(({value, done}) => done
? port.postMessage(done)
: (port.postMessage(value), pump())
)
// start the pipe
pump()
})
}
Then you open a popup window in your https page (note that you can only do this on a user interaction event or else it will be blocked)
window.popup = window.open(http://.../proxy.html)
create your utility function
function xfetch(...args) {
// tell the proxy to make the request
const ms = new MessageChannel
popup.postMessage(args, '*', [ms.port1])
// Resolves when the headers comes
return new Promise((rs, rj) => {
// First message will resolve the Response Object
ms.port2.onmessage = ({data}) => {
const stream = new ReadableStream({
start(controller) {
// Change the onmessage to pipe the remaning request
ms.port2.onmessage = evt => {
if (evt.data === true) // Done?
controller.close()
else // enqueue the buffer to the stream
controller.enqueue(evt.data)
}
}
})
// Construct a new response with the
// response headers and a stream
rs(new Response(stream, data))
}
})
}
And make the request like you normally do with the fetch api
xfetch('http://httpbin.org/get')
.then(res => res.text())
.then(console.log)
Do you mean something like this:
def test_raises():
with pytest.raises(Exception) as execinfo:
raise Exception('some info')
# these asserts are identical; you can use either one
assert execinfo.value.args[0] == 'some info'
assert str(execinfo.value) == 'some info'
First error is caused by php because the extension mbstring is either not installed or not active.
The second error is output of phpMyAdmin/your site asking you to install / enable the mysqli extension.
To enable mbstring and mysqli edit your php.ini and add/uncomment the two lines with mbstring.so and mysqli.so on unix or mbstring.dll and mysqli.dll on windows
Unix /etc/(phpX/)php.ini
extension=mysqli.so
extension=mbstring.so
Windows PHP installation folder\etc\php.ini
extension=mysqli.dll
extension=mbstring.dll
Don't forget to restart your webserver after this.
EDIT: User added he was using redhat in the comments so here's how you install extensions on all CentOS/Fedora/RedHat/Yum based linux distros
sudo yum install php-mysqli
sudo yum install php-mbstring
restart your werbserver
sudo /etc/init.d/httpd restart
you can verify your installation with a little php script in your document root. This lists all settings, versions and active extensions you've installed for php
test.php
<?php
phpinfo();
This may resolve everyones problem: All tags are added so you don't need to worry about folders path. Replace res/xml/file_paths.xml with:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="external"
path="." />
<external-files-path
name="external_files"
path="." />
<cache-path
name="cache"
path="." />
<external-cache-path
name="external_cache"
path="." />
<files-path
name="files"
path="." />
</paths>
Try
CASE WHEN ebv.db_no IN (22978,23218,23219) THEN 'WECS 9500' ELSE 'WECS 9520' END
<div ng-if="modeldate==''"><span ng-message="required" class="change">Date is required</span> </div>
you can use the ng-if directive as above.
Open your terminal and open folder where file is saved.
Ex /home/User1/program/test.rb
cd /home/User1/program
ruby test.rb
format or test.rb
class Test
def initialize
puts "I love India"
end
end
# initialize object
Test.new
output
I love India
function get_input_tags($html)
{
$post_data = array();
// a new dom object
$dom = new DomDocument;
//load the html into the object
$dom->loadHTML($html);
//discard white space
$dom->preserveWhiteSpace = false;
//all input tags as a list
$input_tags = $dom->getElementsByTagName('input');
//get all rows from the table
for ($i = 0; $i < $input_tags->length; $i++)
{
if( is_object($input_tags->item($i)) )
{
$name = $value = '';
$name_o = $input_tags->item($i)->attributes->getNamedItem('name');
if(is_object($name_o))
{
$name = $name_o->value;
$value_o = $input_tags->item($i)->attributes->getNamedItem('value');
if(is_object($value_o))
{
$value = $input_tags->item($i)->attributes->getNamedItem('value')->value;
}
$post_data[$name] = $value;
}
}
}
return $post_data;
}
error_reporting(~E_WARNING);
$html = file_get_contents("https://accounts.google.com/ServiceLoginAuth");
print_r(get_input_tags($html));
Red lines under the ViewBag was my headache for 3 month ). Just remove the Microsoft.CSharp reference from project and then add it again.
I'll answer the more general question of how to have a canvas dynamically adapt in size upon window resize. The accepted answer appropriately handles the case where width and height are both supposed to be 100%, which is what was asked for, but which also will change the aspect ratio of the canvas. Many users will want the canvas to resize on window resize, but while keeping the aspect ratio untouched. It's not the exact question, but it "fits in", just putting the question into a slightly more general context.
The window will have some aspect ratio (width / height), and so will the canvas object. How you want these two aspect ratios to relate to each other is one thing you'll have to be clear about, there is no "one size fits all" answer to that question - I'll go through some common cases of what you might want.
Most important thing you have to be clear about: the html canvas object has a width attribute and a height attribute; and then, the css of the same object also has a width and a height attribute. Those two widths and heights are different, both are useful for different things.
Changing the width and height attributes is one method with which you can always change the size of your canvas, but then you'll have to repaint everything, which will take time and is not always necessary, because some amount of size change you can accomplish via the css attributes, in which case you do not redraw the canvas.
I see 4 cases of what you might want to happen on window resize (all starting with a full screen canvas)
1: you want the width to remain 100%, and you want the aspect ratio to stay as it was. In that case, you do not need to redraw the canvas; you don't even need a window resize handler. All you need is
$(ctx.canvas).css("width", "100%");
where ctx is your canvas context. fiddle: resizeByWidth
2: you want width and height to both stay 100%, and you want the resulting change in aspect ratio to have the effect of a stretched-out image. Now, you still don't need to redraw the canvas, but you need a window resize handler. In the handler, you do
$(ctx.canvas).css("height", window.innerHeight);
fiddle: messWithAspectratio
3: you want width and height to both stay 100%, but the answer to the change in aspect ratio is something different from stretching the image. Then you need to redraw, and do it the way that is outlined in the accepted answer.
fiddle: redraw
4: you want the width and height to be 100% on page load, but stay constant thereafter (no reaction to window resize.
fiddle: fixed
All fiddles have identical code, except for line 63 where the mode is set. You can also copy the fiddle code to run on your local machine, in which case you can select the mode via a querystring argument, as ?mode=redraw
A date-time object is supposed to store the information about the date, time, timezone etc., not about the formatting. You can format a date-time object into a String
with the pattern of your choice using date-time formatting API.
java.time.format
e.g. java.time.format.DateTimeFormatter
, java.time.format.DateTimeFormatterBuilder
etc.java.text
e.g. java.text.SimpleDateFormat
, java.text.DateFormat
etc.Demo using modern API:
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
ZonedDateTime zdt = ZonedDateTime.of(LocalDate.of(2012, Month.DECEMBER, 1).atStartOfDay(),
ZoneId.of("Europe/London"));
// Default format returned by Date#toString
System.out.println(zdt);
// Custom format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
String formattedDate = dtf.format(zdt);
System.out.println(formattedDate);
}
}
Output:
2012-12-01T00:00Z[Europe/London]
2012-12-01
Learn about the modern date-time API from Trail: Date Time.
Demo using legacy API:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.setTimeInMillis(0);
calendar.set(Calendar.YEAR, 2012);
calendar.set(Calendar.MONTH, 11);
calendar.set(Calendar.DAY_OF_MONTH, 1);
Date date = calendar.getTime();
// Default format returned by Date#toString
System.out.println(date);
// Custom format
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
}
}
Output:
Sat Dec 01 00:00:00 GMT 2012
2012-12-01
Some more important points:
java.util.Date
object is not a real date-time object like the modern date-time types; rather, it represents the milliseconds from the Epoch of January 1, 1970
. When you print an object of java.util.Date
, its toString
method returns the date-time calculated from this milliseconds value. Since java.util.Date
does not have timezone information, it applies the timezone of your JVM and displays the same. If you need to print the date-time in a different timezone, you will need to set the timezone to SimpleDateFomrat
and obtain the formatted string from it.java.util
and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.
When setting Environmental Variables in Windows, I have gone wrong on many, many occasions. I thought I should share a few of my past mistakes here hoping that it might help someone. (These apply to all Environmental Variables, not just when setting Python Path)
Watch out for these possible mistakes:
;C:\Python27
WITHOUT any spaces. (It is common to try C:\SomeOther; C:\Python27
That space (?) after the semicolon is not okay.)echo $PATH
but only backward slashes have worked for me.C:\Python27
NOT C:\Python27\
Hope this helps someone.
From Visual Studio 2015 consider to use out of the box Memory Usage diagnostic tool to collect and analyze memory usage data.
The Memory Usage tool lets you take one or more snapshots of the managed and native memory heap to help understand the memory usage impact of object types.
I actually found the right command to use.. its called timeout: http://www.ss64.com/nt/timeout.html
For me, this issue occurred after updating Google Play Services. One of the libraries I was using incorporated this library using the "+" in its gradel reference, like
compile 'com.google.android.gms:play-services:+'
This created an issue because the min version targeted by that library was less than what was targeted by the current version of Google Play Services. I found this by simply looking in the logs.
Yes, there is a static DoEvents method in the Application class in the System.Windows.Forms namespace. System.Windows.Forms.Application.DoEvents() can be used to process the messages waiting in the queue on the UI thread when performing a long-running task in the UI thread. This has the benefit of making the UI seem more responsive and not "locked up" while a long task is running. However, this is almost always NOT the best way to do things. According to Microsoft calling DoEvents "...causes the current thread to be suspended while all waiting window messages are processed." If an event is triggered there is a potential for unexpected and intermittent bugs that are difficult to track down. If you have an extensive task it is far better to do it in a separate thread. Running long tasks in a separate thread allows them to be processed without interfering with the UI continuing to run smoothly. Look here for more details.
Here is an example of how to use DoEvents; note that Microsoft also provides a caution against using it.
To answer the question, getApplication() returns an Application object and getApplicationContext() returns a Context object. Based on your own observations, I would assume that the Context of both are identical (i.e. behind the scenes the Application class calls the latter function to populate the Context portion of the base class or some equivalent action takes place). It shouldn't really matter which function you call if you just need a Context.
Sometimes, the same error occurs when you forget to include the corresponding header
.
adding to @tutts excelent answer, I modified it to this:
... includes a caption - where you can use FontAwesome icons or alike ...
var myCustomColour = '#334455d0', // d0 -> alpha value
lat = 5.5,
lon = 5.5;
var caption = '', // '<i class="fa fa-eye" />' or 'abc' or ...
size = 10, // size of the marker
border = 2; // border thickness
var markerHtmlStyles = ' \
background-color: ' + myCustomColour + '; \
width: '+ (size * 3) +'px; \
height: '+ (size * 3) +'px; \
display: block; \
left: '+ (size * -1.5) +'px; \
top: '+ (size * -1.5) +'px; \
position: relative; \
border-radius: '+ (size * 3) +'px '+ (size * 3) +'px 0; \
transform: rotate(45deg); \
border: '+border+'px solid #FFFFFF;\
';
var captionStyles = '\
transform: rotate(-45deg); \
display:block; \
width: '+ (size * 3) +'px; \
text-align: center; \
line-height: '+ (size * 3) +'px; \
';
var icon = L.divIcon({
className: "color-pin-" + myCustomColour.replace('#', ''),
// on another project this is needed: [0, size*2 + border/2]
iconAnchor: [border, size*2 + border*2],
labelAnchor: [-(size/2), 0],
popupAnchor: [0, -(size*3 + border)],
html: '<span style="' + markerHtmlStyles + '"><span style="'+captionStyles+'">'+ caption + '</span></span>'
});
var marker = L.marker([lat, lon], {icon: icon})
.addTo(mymap);
and the ES6 version (like @tutts) .. I am using it with vue-leaflet
// caption could be: '<i class="fa fa-eye" />',_x000D_
function makeMarkerIcon(color, caption) {_x000D_
let myCustomColour = color + 'd0';_x000D_
_x000D_
let size = 10, // size of the marker_x000D_
border = 2; // border thickness_x000D_
_x000D_
let markerHtmlStyles = `_x000D_
background-color: ${myCustomColour};_x000D_
width: ${size * 3}px;_x000D_
height: ${size * 3}px;_x000D_
display: block;_x000D_
left: ${size * -1.5}px;_x000D_
top: ${size * -1.5}px;_x000D_
position: relative;_x000D_
border-radius: ${size * 3}px ${size * 3}px 0;_x000D_
transform: rotate(45deg);_x000D_
border: ${border}px solid #FFFFFF;_x000D_
`;_x000D_
_x000D_
let captionStyles = `_x000D_
transform: rotate(-45deg);_x000D_
display:block;_x000D_
width: ${size * 3}px;_x000D_
text-align: center;_x000D_
line-height: ${size * 3}px;_x000D_
`;_x000D_
_x000D_
let icon = L.divIcon({_x000D_
className: 'color-pin-' + myCustomColour.replace('#', ''),_x000D_
iconAnchor: [border, size*2 + border*2],_x000D_
labelAnchor: [-(size/2), 0],_x000D_
popupAnchor: [0, -(size*3 + border)],_x000D_
_x000D_
html: `<span style="${markerHtmlStyles}"><span style="${captionStyles}">${caption || ''}</span></span>`_x000D_
});_x000D_
_x000D_
return icon;_x000D_
}_x000D_
_x000D_
var marker = L.marker([lat, lon], {icon: makeMarkerIcon('#123456d0', '?')})_x000D_
.addTo(mymap);
_x000D_
A great way to do it for a simple image is to do it using only CSS to set the background of the HTML element like so.
HTML {_x000D_
background: url('http://www.earthtimes.org/newsimage/eat-lead-by-example-obesity-expert-tells-parents_139.jpg');_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
}
_x000D_
If you want to get fancy, and set its opacity, then, in IE9+*, you can set a transparent background color of the body. This works by overlaying semitransparent white to make the image whiter, and appear to be brighter. For example, white with 75% opacity (rgba(255,255,255,.75)
) would produce the following effect.
HTML {_x000D_
background: url('http://www.earthtimes.org/newsimage/eat-lead-by-example-obesity-expert-tells-parents_139.jpg');_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
body {_x000D_
width: 100%;_x000D_
min-height: 100%;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
margin: 0;_x000D_
background: rgba(255, 255, 255, .75);_x000D_
}
_x000D_
<p>Lorem ipsum dolor sit amet, et id, maecenas a convallis, elit facilisi congue augue id ac. Suscipit luctus egestas rutrum, amet tincidunt porttitor ante convallis magna, vivamus amet at turpis, ante lacinia blandit vel metus mauris rutrum. Ipsum nam adipiscing._x000D_
Est sapien quis sem vestibulum, quis cubilia turpis, suspendisse mattis vehicula enim risus pede, placerat suspendisse dui. Convallis nostrud pede, mollit lobortis, ornare ipsum tempor faucibus tortor, vel pede, porttitor nulla nonummy vestibulum purus._x000D_
Eros placerat tenetur augue ipsum aliquam, pellentesque congue condimentum sed vitae lectus.</p>_x000D_
<p>Aliquam venenatis curabitur pellentesque sociosqu quam. Tincidunt id erat vestibulum in, est fermentum ipsum et augue, nascetur etiam. Lorem elit, sed donec, leo vivamus ac id enim faucibus vel. Nullam sit feugiat sed massa consectetuer auctor, nulla_x000D_
et erat lacinia nec, eget ut ante nullam est non in, elit porttitor in in donec eget porttitor. Interdum ultricies sem morbi facilisis nibh erat. Id suspendisse, sed tincidunt fringilla sit, sapien odio vel, at culpa augue sed taciti neque inceptos,_x000D_
massa class non. Vel tristique condimentum at pellentesque, commodo nulla sagittis rhoncus lorem. Viverra maecenas tellus pretium urna mauris proin, vel libero morbi, ante volutpat vestibulum augue. Itaque leo mauris turpis, vivamus nisl congue nisl_x000D_
nulla in turpis, eget vitae accumsan dolor ipsum leo venenatis, feugiat vehicula in risus, donec eu pede vivamus itaque nam. Justo amet vitae pellentesque sed, posuere fusce sapien, sed nam placerat libero sed etiam curabitur, suspendisse justo, amet_x000D_
porttitor.</p>_x000D_
<p>Condimentum eget. Sem elementum a et mauris sem a, velit justo consectetuer in turpis mauris, sit sed elit cum, fusce suspendisse pretium dictum, mattis dui tortor tellus. Volutpat ut ante lorem nec laoreet aliquam, lorem est magna amet, integer mauris_x000D_
purus tellus. Porta enim repellendus aliquam eros. Turpis posuere elementum suscipit wisi lobortis, nec nunc consequat dictum ut unde at, mi lorem amet nunc. Cubilia pede, integer dolor, eget platea felis elit enim rhoncus, integer proin quam in ipsum_x000D_
lorem, diam curabitur netus pretium pellentesque. Donec rutrum ultrices placerat, curabitur maecenas, feugiat pede varius accumsan quam lorem, dui et dictumst asperiores nulla, vivamus urna nam leo libero. Posuere non convallis amet justo parturient,_x000D_
imperdiet consectetuer arcu praesent cursus risus, quis pretium dolor.</p>
_x000D_
position: relative
, while the body is position: absolute
. This is to prevent the background color of the body from behaving more like a highlighter of the text in the body.This could even be expanded to something comparable to, but still very distinct from, CSS filters by changing around the body's RGBA color background. For example, rgba(0,255,0,.75)
would create a very green tint as you can see in the code snippet.
HTML {_x000D_
background: url('http://www.earthtimes.org/newsimage/eat-lead-by-example-obesity-expert-tells-parents_139.jpg');_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
position: relative;_x000D_
}_x000D_
body {_x000D_
width: 100%;_x000D_
min-height: 100%;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
margin: 0;_x000D_
background: rgba(0,255,0,.75);_x000D_
}
_x000D_
<p>Aliquam venenatis curabitur pellentesque sociosqu quam. Tincidunt id erat vestibulum in, est fermentum ipsum et augue, nascetur etiam. Lorem elit, sed donec, leo vivamus ac id enim faucibus vel. Nullam sit feugiat sed massa consectetuer auctor, nulla et erat lacinia nec, eget ut ante nullam est non in, elit porttitor in in donec eget porttitor. Interdum ultricies sem morbi facilisis nibh erat. Id suspendisse, sed tincidunt fringilla sit, sapien odio vel, at culpa augue sed taciti neque inceptos, massa class non. Vel tristique condimentum at pellentesque, commodo nulla sagittis rhoncus lorem. Viverra maecenas tellus pretium urna mauris proin, vel libero morbi, ante volutpat vestibulum augue. Itaque leo mauris turpis, vivamus nisl congue nisl nulla in turpis, eget vitae accumsan dolor ipsum leo venenatis, feugiat vehicula in risus, donec eu pede vivamus itaque nam. Justo amet vitae pellentesque sed, posuere fusce sapien, sed nam placerat libero sed etiam curabitur, suspendisse justo, amet porttitor.</p>_x000D_
<p>Condimentum eget. Sem elementum a et mauris sem a, velit justo consectetuer in turpis mauris, sit sed elit cum, fusce suspendisse pretium dictum, mattis dui tortor tellus. Volutpat ut ante lorem nec laoreet aliquam, lorem est magna amet, integer mauris purus tellus. Porta enim repellendus aliquam eros. Turpis posuere elementum suscipit wisi lobortis, nec nunc consequat dictum ut unde at, mi lorem amet nunc. Cubilia pede, integer dolor, eget platea felis elit enim rhoncus, integer proin quam in ipsum lorem, diam curabitur netus pretium pellentesque. Donec rutrum ultrices placerat, curabitur maecenas, feugiat pede varius accumsan quam lorem, dui et dictumst asperiores nulla, vivamus urna nam leo libero. Posuere non convallis amet justo parturient, imperdiet consectetuer arcu praesent cursus risus, quis pretium dolor.</p>_x000D_
<p>Lorem ipsum dolor sit amet, et id, maecenas a convallis, elit facilisi congue augue id ac. Suscipit luctus egestas rutrum, amet tincidunt porttitor ante convallis magna, vivamus amet at turpis, ante lacinia blandit vel metus mauris rutrum. Ipsum nam adipiscing. Est sapien quis sem vestibulum, quis cubilia turpis, suspendisse mattis vehicula enim risus pede, placerat suspendisse dui. Convallis nostrud pede, mollit lobortis, ornare ipsum tempor faucibus tortor, vel pede, porttitor nulla nonummy vestibulum purus. Eros placerat tenetur augue ipsum aliquam, pellentesque congue condimentum sed vitae lectus.</p>
_x000D_
rgba(0,255,0,.75)
as something exemplified by {red:0, green:255, blue:0, alpha:'75%'}
.*A full compatibility table can be found at Can I Use. However, please also note that you need to click the "Show All" to see that IE9 supports it.
Since I have already answered the question but I have more I want to add, I am titling this section addendum and having it add some potentially helpful information. So, to extrapolate even further on the content above, you could use an SVG as a background image to do wicked awesome things. For example, you could create a loading screen background featuring a cool website icon as you can see in the example of a base64 encoded SVG below.
HTML {_x000D_
background: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz48IURPQ1RZUEUgc3ZnIFBVQkxJQyAiLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4iICJodHRwOi8vd3d3LnczLm9yZy9HcmFwaGljcy9TVkcvMS4xL0RURC9zdmcxMS5kdGQiPjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB3aWR0aD0iNDAwIiBoZWlnaHQ9IjQwMCIgdmVyc2lvbj0iMS4xIiB2aWV3Qm94PSIwIDAgMSAxIiBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJ4TWluWU1pbiIgYXJpYS1oaWRkZW49InRydWUiPjxnIGlkPSJrIj48ZGVmcz48bGluZWFyR3JhZGllbnQgaWQ9ImMiIGdyYWRpZW50VHJhbnNmb3JtPSJyb3RhdGUoLTEyMCkiIHRyYW5zZm9ybS1vcmlnaW49Ii41LjUiPjxzdG9wIG9mZnNldD0iMCUiIHN0b3AtY29sb3I9InJnYmEoMCwwLDAsLjYpIi8+PHN0b3Agb2Zmc2V0PSI0NyUiIHN0b3AtY29sb3I9InJnYmEoMCwwLDAsLjYpIi8+PHN0b3Agb2Zmc2V0PSI1MyUiIHN0b3AtY29sb3I9InJnYmEoMCwwLDAsLjMpIi8+PHN0b3Agb2Zmc2V0PSIxMDAlIiBzdG9wLWNvbG9yPSJyZ2JhKDAsMCwwLC45KSIvPjxhbmltYXRlVHJhbnNmb3JtIGF0dHJpYnV0ZU5hbWU9ImdyYWRpZW50VHJhbnNmb3JtIiBhdHRyaWJ1dGVUeXBlPSJYTUwiIHR5cGU9InJvdGF0ZSIgZHVyPSI3MDAwbXMiIGZyb209IjAiIHRvPSIzNjAiIHJlcGVhdENvdW50PSJpbmRlZmluaXRlIi8+PC9saW5lYXJHcmFkaWVudD48cmFkaWFsR3JhZGllbnQgaWQ9ImQiIHI9Ii41IiBjeT0iLjUiIGN4PSIuNSI+PHN0b3Agb2Zmc2V0PSIzNSUiIHN0b3AtY29sb3I9ImJsYWNrIi8+PHN0b3Agb2Zmc2V0PSI1MCUiIHN0b3AtY29sb3I9ImdyZXkiLz48c3RvcCBvZmZzZXQ9IjY1JSIgc3RvcC1jb2xvcj0iYmxhY2siLz48L3JhZGlhbEdyYWRpZW50PjxyYWRpYWxHcmFkaWVudCBpZD0iZSIgcj0iLjUiIGN5PSIuNSIgY3g9Ii41Ij48c3RvcCBvZmZzZXQ9IjAlIiBzdG9wLWNvbG9yPSJ3aGl0ZSIvPjxzdG9wIG9mZnNldD0iMjUlIiBzdG9wLWNvbG9yPSJ5ZWxsb3ciLz48c3RvcCBvZmZzZXQ9Ijc1JSIgc3RvcC1jb2xvcj0ieWVsbG93Ii8+PHN0b3Agb2Zmc2V0PSIxMDAlIiBzdG9wLWNvbG9yPSJ3aGl0ZSIvPjwvcmFkaWFsR3JhZGllbnQ+PGNsaXBQYXRoIGlkPSJmIj48cGF0aCBzdHJva2U9ImdyZXkiIHN0cm9rZS13aWR0aD0iLjAxIiBpZD0iYiIgZD0iTS43NS43MUEuMzEuMzEgMCAxIDEgLjc1LjMxTC42OS4zOEEuMjIuMjIgMCAxIDAgLjY4LjY2TC41Ni41N0wuNi41MUwuODIuNjh6TS42LjYzQS4xNC4xNCAwIDEgMSAuNjIuNDJMLjY2LjM5QS4xOS4xOSAwIDEgMCAuNjQuNjZ6TS41NS41OEEuMDcuMDcgMCAxIDEgLjU2LjQ2TC42LjQzQS4xMi4xMiAwIDEgMCAuNTkuNjF6Ii8+PC9jbGlwUGF0aD48Y2xpcFBhdGggaWQ9ImciPjxwYXRoIHN0cm9rZT0iZ3JleSIgZmlsbD0icmVkIiBzdHJva2Utd2lkdGg9Ii4wMSIgZD0iTS42LjYzQS4xNC4xNCAwIDEgMSAuNjIuNDJMLjY2LjM5QS4xOS4xOSAwIDEgMCAuNjQuNjZ6Ii8+PC9jbGlwUGF0aD48L2RlZnM+PGcgY2xpcC1wYXRoPSJ1cmwoI2YpIiBmaWxsPSJ1cmwoI2MpIj48cmVjdCB4PSIwIiB5PSIwIiB3aWR0aD0iMSIgaGVpZ2h0PSIxIi8+PHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjEiIGhlaWdodD0iMSIgZmlsbD0icmVkIiBjbGlwLXBhdGg9InVybCgjZykiLz48L2c+PGcgdHJhbnNmb3JtPSJzY2FsZSgxLjEpIiB0cmFuc2Zvcm0tb3JpZ2luPSIuNS41Ij48dGV4dD48dGV4dFBhdGggaHJlZj0iI2IiIGZvbnQtc2l6ZT0iLjY1JSIgZm9udC1mYW1pbHk9Im1vbm9zcGFjZSIgbGV0dGVyLXNwYWNpbmc9Ii0uNSUiIHN0eWxlPSJ3aGl0ZS1zcGFjZTpwcmUiPiBZT1VSIDx0c3BhbiBmaWxsPSJyZWQiPkVYQU1QTEUgV0VCU0lURTwvdHNwYW4+IExPR088L3RleHRQYXRoPjwvdGV4dD48L2c+PC9nPjwvc3ZnPg==');_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
position: relative;_x000D_
background-size: cover;_x000D_
}_x000D_
body {_x000D_
width: 100%;_x000D_
min-height: 100%;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
margin: 0;_x000D_
background: rgba(255,255,255,.5);_x000D_
}
_x000D_
<p>Condimentum eget. Sem elementum a et mauris sem a, velit justo consectetuer in turpis mauris, sit sed elit cum, fusce suspendisse pretium dictum, mattis dui tortor tellus. Volutpat ut ante lorem nec laoreet aliquam, lorem est magna amet, integer mauris purus tellus. Porta enim repellendus aliquam eros. Turpis posuere elementum suscipit wisi lobortis, nec nunc consequat dictum ut unde at, mi lorem amet nunc. Cubilia pede, integer dolor, eget platea felis elit enim rhoncus, integer proin quam in ipsum lorem, diam curabitur netus pretium pellentesque. Donec rutrum ultrices placerat, curabitur maecenas, feugiat pede varius accumsan quam lorem, dui et dictumst asperiores nulla, vivamus urna nam leo libero. Posuere non convallis amet justo parturient, imperdiet consectetuer arcu praesent cursus risus, quis pretium dolor.</p>_x000D_
<p>Lorem ipsum dolor sit amet, et id, maecenas a convallis, elit facilisi congue augue id ac. Suscipit luctus egestas rutrum, amet tincidunt porttitor ante convallis magna, vivamus amet at turpis, ante lacinia blandit vel metus mauris rutrum. Ipsum nam adipiscing. Est sapien quis sem vestibulum, quis cubilia turpis, suspendisse mattis vehicula enim risus pede, placerat suspendisse dui. Convallis nostrud pede, mollit lobortis, ornare ipsum tempor faucibus tortor, vel pede, porttitor nulla nonummy vestibulum purus. Eros placerat tenetur augue ipsum aliquam, pellentesque congue condimentum sed vitae lectus.</p>_x000D_
<p>Aliquam venenatis curabitur pellentesque sociosqu quam. Tincidunt id erat vestibulum in, est fermentum ipsum et augue, nascetur etiam. Lorem elit, sed donec, leo vivamus ac id enim faucibus vel. Nullam sit feugiat sed massa consectetuer auctor, nulla et erat lacinia nec, eget ut ante nullam est non in, elit porttitor in in donec eget porttitor. Interdum ultricies sem morbi facilisis nibh erat. Id suspendisse, sed tincidunt fringilla sit, sapien odio vel, at culpa augue sed taciti neque inceptos, massa class non. Vel tristique condimentum at pellentesque, commodo nulla sagittis rhoncus lorem. Viverra maecenas tellus pretium urna mauris proin, vel libero morbi, ante volutpat vestibulum augue. Itaque leo mauris turpis, vivamus nisl congue nisl nulla in turpis, eget vitae accumsan dolor ipsum leo venenatis, feugiat vehicula in risus, donec eu pede vivamus itaque nam. Justo amet vitae pellentesque sed, posuere fusce sapien, sed nam placerat libero sed etiam curabitur, suspendisse justo, amet porttitor.</p>
_x000D_
background-size: cover
CSS causes the SVG logo in the background to be resized to the size of the HTML element.If you use ng > 1.2, here is an example of using ng-repeat-start/end
without generating unnecessary tags:
<html>_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<script>_x000D_
angular.module('mApp', []);_x000D_
</script>_x000D_
</head>_x000D_
<body ng-app="mApp">_x000D_
<table border="1" width="100%">_x000D_
<tr ng-if="0" ng-repeat-start="elem in [{k: 'A', v: ['a1','a2']}, {k: 'B', v: ['b1']}, {k: 'C', v: ['c1','c2','c3']}]"></tr>_x000D_
_x000D_
<tr>_x000D_
<td rowspan="{{elem.v.length}}">{{elem.k}}</td>_x000D_
<td>{{elem.v[0]}}</td>_x000D_
</tr>_x000D_
<tr ng-repeat="v in elem.v" ng-if="!$first">_x000D_
<td>{{v}}</td>_x000D_
</tr>_x000D_
_x000D_
<tr ng-if="0" ng-repeat-end></tr>_x000D_
</table>_x000D_
</body>_x000D_
</html>
_x000D_
The important point: for tags used for ng-repeat-start
and ng-repeat-end
set ng-if="0"
, to let not be inserted in the page. In this way the inner content will be handled exactly as it is in knockoutjs (using commands in <!--...-->
), and there will be no garbage.
A cookie is a object with key value pair to store information related to the customer. Main objective is to personalize the customer's experience.
An utility method can be created like
private Cookie createCookie(String cookieName, String cookieValue) {
Cookie cookie = new Cookie(cookieName, cookieValue);
cookie.setPath("/");
cookie.setMaxAge(MAX_AGE_SECONDS);
cookie.setHttpOnly(true);
cookie.setSecure(true);
return cookie;
}
If storing important information then we should alsways put setHttpOnly so that the cookie cannot be accessed/modified via javascript. setSecure is applicable if you are want cookies to be accessed only over https protocol.
using above utility method you can add cookies to response as
Cookie cookie = createCookie("name","value");
response.addCookie(cookie);
I say "star-args" and Python people seem to know what i mean.
**
is trickier - I think just "qargs" since it is usually used as **kw
or **kwargs
The Reason for Warning is your using Old ADT (Android development tools), so Update your ADT by following the procedures below
Procedure 1:
Procedure 2:
Click Help > Install New Software. In the Work with field, enter: https://dl-ssl.google.com/android/eclipse/ Select Developer Tools / Android Development Tools. Click Next and complete the wizard.
What's dumpsys and what are its benefit
dumpsys is an android tool that runs on the device and dumps interesting information about the status of system services.
Obvious benefits:
What information can we retrieve from dumpsys shell command and how we can use it
If you run dumpsys you would see a ton of system information. But you can use only separate parts of this big dump.
to see all of the "subcommands" of dumpsys do:
dumpsys | grep "DUMP OF SERVICE"
Output:
DUMP OF SERVICE SurfaceFlinger:
DUMP OF SERVICE accessibility:
DUMP OF SERVICE account:
DUMP OF SERVICE activity:
DUMP OF SERVICE alarm:
DUMP OF SERVICE appwidget:
DUMP OF SERVICE audio:
DUMP OF SERVICE backup:
DUMP OF SERVICE battery:
DUMP OF SERVICE batteryinfo:
DUMP OF SERVICE clipboard:
DUMP OF SERVICE connectivity:
DUMP OF SERVICE content:
DUMP OF SERVICE cpuinfo:
DUMP OF SERVICE device_policy:
DUMP OF SERVICE devicestoragemonitor:
DUMP OF SERVICE diskstats:
DUMP OF SERVICE dropbox:
DUMP OF SERVICE entropy:
DUMP OF SERVICE hardware:
DUMP OF SERVICE input_method:
DUMP OF SERVICE iphonesubinfo:
DUMP OF SERVICE isms:
DUMP OF SERVICE location:
DUMP OF SERVICE media.audio_flinger:
DUMP OF SERVICE media.audio_policy:
DUMP OF SERVICE media.player:
DUMP OF SERVICE meminfo:
DUMP OF SERVICE mount:
DUMP OF SERVICE netstat:
DUMP OF SERVICE network_management:
DUMP OF SERVICE notification:
DUMP OF SERVICE package:
DUMP OF SERVICE permission:
DUMP OF SERVICE phone:
DUMP OF SERVICE power:
DUMP OF SERVICE reboot:
DUMP OF SERVICE screenshot:
DUMP OF SERVICE search:
DUMP OF SERVICE sensor:
DUMP OF SERVICE simphonebook:
DUMP OF SERVICE statusbar:
DUMP OF SERVICE telephony.registry:
DUMP OF SERVICE throttle:
DUMP OF SERVICE usagestats:
DUMP OF SERVICE vibrator:
DUMP OF SERVICE wallpaper:
DUMP OF SERVICE wifi:
DUMP OF SERVICE window:
Some Dumping examples and output
1) Getting all possible battery statistic:
$~ adb shell dumpsys battery
You will get output:
Current Battery Service state:
AC powered: false
AC capacity: 500000
USB powered: true
status: 5
health: 2
present: true
level: 100
scale: 100
voltage:4201
temperature: 271 <---------- Battery temperature! %)
technology: Li-poly <---------- Battery technology! %)
2)Getting wifi informations
~$ adb shell dumpsys wifi
Output:
Wi-Fi is enabled
Stay-awake conditions: 3
Internal state:
interface tiwlan0 runState=Running
SSID: XXXXXXX BSSID: xx:xx:xx:xx:xx:xx, MAC: xx:xx:xx:xx:xx:xx, Supplicant state: COMPLETED, RSSI: -60, Link speed: 54, Net ID: 2, security: 0, idStr: null
ipaddr 192.168.1.xxx gateway 192.168.x.x netmask 255.255.255.0 dns1 192.168.x.x dns2 8.8.8.8 DHCP server 192.168.x.x lease 604800 seconds
haveIpAddress=true, obtainingIpAddress=false, scanModeActive=false
lastSignalLevel=2, explicitlyDisabled=false
Latest scan results:
Locks acquired: 28 full, 0 scan
Locks released: 28 full, 0 scan
Locks held:
3) Getting CPU info
~$ adb shell dumpsys cpuinfo
Output:
Load: 0.08 / 0.4 / 0.64
CPU usage from 42816ms to 34683ms ago:
system_server: 1% = 1% user + 0% kernel / faults: 16 minor
kdebuglog.sh: 0% = 0% user + 0% kernel / faults: 160 minor
tiwlan_wq: 0% = 0% user + 0% kernel
usb_mass_storag: 0% = 0% user + 0% kernel
pvr_workqueue: 0% = 0% user + 0% kernel
+sleep: 0% = 0% user + 0% kernel
+sleep: 0% = 0% user + 0% kernel
TOTAL: 6% = 1% user + 3% kernel + 0% irq
4)Getting memory usage informations
~$ adb shell dumpsys meminfo 'your apps package name'
Output:
** MEMINFO in pid 5527 [com.sec.android.widgetapp.weatherclock] **
native dalvik other total
size: 2868 5767 N/A 8635
allocated: 2861 2891 N/A 5752
free: 6 2876 N/A 2882
(Pss): 532 80 2479 3091
(shared dirty): 932 2004 6060 8996
(priv dirty): 512 36 1872 2420
Objects
Views: 0 ViewRoots: 0
AppContexts: 0 Activities: 0
Assets: 3 AssetManagers: 3
Local Binders: 2 Proxy Binders: 8
Death Recipients: 0
OpenSSL Sockets: 0
SQL
heap: 0 MEMORY_USED: 0
PAGECACHE_OVERFLOW: 0 MALLOC_SIZE: 0
If you want see the info for all processes, use ~$ adb shell dumpsys meminfo
dumpsys is ultimately flexible and useful tool!
If you want to use this tool do not forget to add permission into your android manifest automatically android.permission.DUMP
Try to test all commands to learn more about dumpsys. Happy dumping!
If you want to send data with form serialize you may try this
var form= $("#formId");
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()+"&variable="+otherData,
success: function (data) {
var result=data;
$('#result').attr("value",result);
}
});
There are only two ways to be 100% certain that the COUNT(*)
and the actual query will give consistent results:
COUNT(*)
with the query, as in your Approach 2. I recommend the form you show in your example, not the correlated subquery form shown in the comment from kogus.SNAPSHOT
or SERIALIZABLE
isolation level. Using one of those isolation levels is important because any other isolation level allows new rows created by other clients to become visible in your current transaction. Read the MSDN documentation on SET TRANSACTION ISOLATION
for more details.
I actually use ASP C# to send my emails now, with something that looks like :
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form.Count > 0)
{
string formEmail = "";
string fromEmail = "[email protected]";
string defaultEmail = "[email protected]";
string sendTo1 = "";
int x = 0;
for (int i = 0; i < Request.Form.Keys.Count; i++)
{
formEmail += "<strong>" + Request.Form.Keys[i] + "</strong>";
formEmail += ": " + Request.Form[i] + "<br/>";
if (Request.Form.Keys[i] == "Email")
{
if (Request.Form[i].ToString() != string.Empty)
{
fromEmail = Request.Form[i].ToString();
}
formEmail += "<br/>";
}
}
System.Net.Mail.MailMessage myMsg = new System.Net.Mail.MailMessage();
SmtpClient smtpClient = new SmtpClient();
try
{
myMsg.To.Add(new System.Net.Mail.MailAddress(defaultEmail));
myMsg.IsBodyHtml = true;
myMsg.Body = formEmail;
myMsg.From = new System.Net.Mail.MailAddress(fromEmail);
myMsg.Subject = "Sent using Gmail Smtp";
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = new System.Net.NetworkCredential("[email protected]", "pward");
smtpClient.Send(defaultEmail, sendTo1, "Sent using gmail smpt", formEmail);
}
catch (Exception ee)
{
debug.Text += ee.Message;
}
}
}
This is an example using gmail as the smtp mail sender. Some of what is in here isn't needed, but it is how I use it, as I am sure there are more effective ways in the same fashion.
If you want to select only certain values from a single table you can try this
select distinct(*) from table_name where table_field in (1,1,2,3,4,5)
eg:
select first_name,phone_number from telephone_list where district id in (1,2,5,7,8,9)
if you want to select from multiple tables then you must go for UNION
.
If you just want to select the values 1, 1, 1, 2, 5, 1, 6 then you must do this
select 1
union select 1
union select 1
union select 2
union select 5
union select 1
union select 6
Related to this I went through a similar problem, but not with get or post made by Angular but with an extension made by a 3rd party (in my case Chrome Extension).
The problem that I faced is that the Chrome Extension won't return then()
so I was unable to do it the way in the solution above but the result is still Asynchronous.
So my solution is to create a service and to proceed to a callback
app.service('cookieInfoService', function() {
this.getInfo = function(callback) {
var model = {};
chrome.cookies.get({url:serverUrl, name:'userId'}, function (response) {
model.response= response;
callback(model);
});
};
});
Then in my controller
app.controller("MyCtrl", function ($scope, cookieInfoService) {
cookieInfoService.getInfo(function (info) {
console.log(info);
});
});
Hope this can help others getting the same issue.
Click Right Click On Your Database The Press tasks>Back Up and take a back up from your database before restore your database i'm using this way to solve this Problem
NOTE: AppJS is deprecated and not recommended anymore.
Take a look at NW.js instead.
Try this instead in the end:
exec (@query)
If you do not have the brackets, SQL Server assumes the value of the variable to be a stored procedure name.
OR
EXECUTE sp_executesql @query
And it should not be because of FULL JOIN.
But I hope you have already created the temp tables: #TrafficFinal, #TrafficFinal2, #TrafficFinal3 before this.
Please note that there are performance considerations between using EXEC and sp_executesql. Because sp_executesql uses forced statement caching like an sp.
More details here.
On another note, is there a reason why you are using dynamic sql for this case, when you can use the query as is, considering you are not doing any query manipulations and executing it the way it is?
When working with graphical user interfaces, you need to remember that drawing on a pane is done in the Java AWT/Swing event queue. You can't just use the Graphics
object outside the paint()
/paintComponent()
/etc. methods.
However, you can use a technique called "Frame buffering". Basically, you need to have a BufferedImage and draw directly on it (see it's createGraphics()
method; that graphics context you can keep and reuse for multiple operations on a same BufferedImage
instance, no need to recreate it all the time, only when creating a new instance). Then, in your JPanel
's paintComponent()
, you simply need to draw the BufferedImage
instance unto the JPanel
. Using this technique, you can perform zoom, translation and rotation operations quite easily through affine transformations.
I thought I was not stupid enough to mix up the versions - however, I didn't realize that on my new server, a SQL Server 2005 instance was already installed from birth named SQLEXPRESS
. When trying to restore my SQL Server 2008 R2 backed up database in SSMS 2012 to the SQLEXPRESS
instance, the list of backup sets was empty.
Eventually I realized that the SQLEXPRESS
instance on the server was not a 2012 instance, but a 2005. I disconnected and connected to the actual 2012 instance (in my case named SQLEXPRESS2012
), and it (obviously) worked.
You are doing mistake in "configuration_page.jsp" file. here in this file , function loadXMLDoc() 's line number 2 should be like this:
var config=document.getElementsByName('configselect').value;
because you have declared only the name
attribute in your <select>
tag. So you should get this element by name.
After correcting this, it will run without any JavaScript error
You have to use Appcompat
library for that. Which is used like below:
dashboard.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_search"
android:icon="@android:drawable/ic_menu_search"
app:showAsAction="always|collapseActionView"
app:actionViewClass="androidx.appcompat.widget.SearchView"
android:title="Search"/>
</menu>
Activity file (in Java):
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.dashboard, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchManager searchManager = (SearchManager) MainActivity.this.getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = null;
if (searchItem != null) {
searchView = (SearchView) searchItem.getActionView();
}
if (searchView != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(MainActivity.this.getComponentName()));
}
return super.onCreateOptionsMenu(menu);
}
Activity file (in Kotlin):
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_search, menu)
val searchItem: MenuItem? = menu?.findItem(R.id.action_search)
val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager
val searchView: SearchView? = searchItem?.actionView as SearchView
searchView?.setSearchableInfo(searchManager.getSearchableInfo(componentName))
return super.onCreateOptionsMenu(menu)
}
manifest file:
<meta-data
android:name="android.app.default_searchable"
android:value="com.apkgetter.SearchResultsActivity" />
<activity
android:name="com.apkgetter.SearchResultsActivity"
android:label="@string/app_name"
android:launchMode="singleTop" >
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="@xml/searchable" />
</activity>
searchable xml file:
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:hint="@string/search_hint"
android:label="@string/app_name" />
And at last, your SearchResultsActivity
class code. for showing result of your search.
another way, this will scan the table only once instead of twice if you use a subquery
only sql server 2005 and up
select Date, User, Status, Notes
from (
select m.*, row_number() over (partition by user order by Date desc) as rn
from [SOMETABLE] m
) m2
where m2.rn = 1;
try this
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'url';
document.getElementsByTagName('head')[0].appendChild(script);
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,
}]
There can be so many issues but if you are using oracle 10g , uninstall oracle 10g and also remove the value from registry and install oracle 11g. But if you are using oracle 11g , first go and check on registry if it is pointing to right home. Sometimes there can be more than one home because you install sql developer again and again . In that case either you can remove unnecessary home registry value or you can add tns and sql.net file to all of those home, that might resolve the issue. I resolved mine in that way.
Am I the only one who can't recognize the character between 'return' and the semicolon? That could be it!
Look at the ToLookup
and/or ToDictionary
extension methods.
Why javascript when you can use just css?
a[aria-expanded="true"]{_x000D_
background-color: #42DCA3;_x000D_
}
_x000D_
<li class="active">_x000D_
<a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="true"> _x000D_
<span class="network-name">Google+</span>_x000D_
</a>_x000D_
</li>_x000D_
<li class="active">_x000D_
<a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="false"> _x000D_
<span class="network-name">Google+</span>_x000D_
</a>_x000D_
</li>
_x000D_
Here's the steps to achieve this:
Download the sendmail.zip through this link
Open sendmail.ini and set the configuration as follows:
smtp_server=smtp.gmail.com
hostname=localhost
Access your email account. Click the Gear Tool > Settings > Forwarding and POP/IMAP > IMAP access. Click "Enable IMAP", then save your changes.
Run your WAMP Server. Enable ssl_module under Apache Module.
Next, enable php_openssl and php_sockets under PHP.
Open php.ini and configure it as the codes below. Basically, you just have to set the sendmail_path.
[mail function] ; For Win32 only. ; http://php.net/smtp ;SMTP = ; http://php.net/smtp-port ;smtp_port = 25 ; For Win32 only. ; http://php.net/sendmail-from ;sendmail_from = [email protected] ; For Unix only. You may supply arguments as well (default: "sendmail -t -i"). ; http://php.net/sendmail-path sendmail_path = "C:\wamp\sendmail\sendmail.exe -t -i"
I hope this will work for you..
To determine the class of an object simply call:
someObject.getClass()
You can abbreviate this to someObject.class
in most cases. However, if you use this on a Map
it will try to retrieve the value with key 'class'. Because of this, I always use getClass()
even though it's a little longer.
If you want to check if an object implements a particular interface or extends a particular class (e.g. Date) use:
(somObject instanceof Date)
or to check if the class of an object is exactly a particular class (not a subclass of it), use:
(somObject.getClass() == Date)
##To check for a particular string in a file
cd PATH_TO_YOUR_DIRECTORY #Changing directory to your working directory
File=YOUR_FILENAME
if grep -q STRING_YOU_ARE_CHECKING_FOR "$File"; ##note the space after the string you are searching for
then
echo "Hooray!!It's available"
else
echo "Oops!!Not available"
fi
I think there's no way to do that, unless you pass the value of the JavaScript var on the URL, but it's a ugly workaround.
Well, it partly depends what you want to happen if you're actually in a derived class.
For example, suppose SuperClass
is in A.jar and SubClass
is in B.jar, and you're executing code in an instance method declared in SuperClass
but where this
refers to an instance of SubClass
. If you use this.getClass().getResource()
it will look relative to SubClass
, in B.jar. I suspect that's usually not what's required.
Personally I'd probably use Foo.class.getResourceAsStream(name)
most often - if you already know the name of the resource you're after, and you're sure of where it is relative to Foo
, that's the most robust way of doing it IMO.
Of course there are times when that's not what you want, too: judge each case on its merits. It's just the "I know this resource is bundled with this class" is the most common one I've run into.
Because of the GDPR it makes no sense to use the iframe, you should rather use the object tag with the embed tag and also use the embed link.
<object width="100%" height="333">
<param name="movie" value="https://www.youtube-nocookie.com/embed/Sdg0ef2PpBw">
<embed src="https://www.youtube-nocookie.com/embed/Sdg0ef2PpBw" width="100%" height="333">
</object>
_x000D_
You should also activate the extended data protection mode function to receive the no cookie url.
type="application/x-shockwave-flash"
flash does not have to be used
Nocookie, however, means that data is still being transmitted, namely the thumbnail that is loaded from YouTube. But at least data is no longer passed on to advertising networks (as example DoubleClick). And no user data is stored on your website by youtube.
The javaw.exe command is identical to java.exe, except that with javaw.exe there is no associated console window
Officially it's Ctrl+F11 & Ctrl+F12 or KEYPAD 7 & KEYPAD 9.
In practise it's a bit quirky.
Specifically it's Left Ctrl+F11 and Left Ctrl+F12 to switch to previous orientation and next orientation respectively.
You have to release Ctrl before you can rotate again.
KEYPAD 7 and KEYPAD 9 only work with Num Lock OFF (so they're acting as Home & PageUp rather than 7 & 9).
The only orientations are vertically upright and rotated one quarter-turn anti-clockwise.
Maybe a bit too much info for such a simple question, but it drove me half-mad finding this out.
Note: This was tested on Android SDK R16 and a very old keyboard, modern keyboards may behave differently.
Another way to do it is to splice two parsed sections of the numerical value together:
Cells(RowNum, ColumnNum).Value = Mid(varNumber,1,1) & Mid(varNumber,2,Len(varNumber))
I have found better success with this than CStr()
because CStr()
doesn't seem to convert decimal numbers that came from variants in my experience.
In my case worked with:
np.load(path, allow_pickle=True)
You can convert the value user provides to a double and store it again as nvarchar, with the aid of FormatProviders. CultureInfo is a typical FormatProvider. Assuming you know the culture you are operating,
System.Globalization.CultureInfo EnglishCulture = new System.Globalization.CultureInfo("en-EN");
System.Globalization.CultureInfo GermanCulture = new System.Globalization.CultureInfo("de-de");
will suffice to do the neccesary transformation, like;
double val;
if(double.TryParse("65,89875", System.Globalization.NumberStyles.Float, GermanCulture, out val))
{
string valInGermanFormat = val.ToString(GermanCulture);
string valInEnglishFormat = val.ToString(EnglishCulture);
}
if(double.TryParse("65.89875", System.Globalization.NumberStyles.Float, EnglishCulture, out val))
{
string valInGermanFormat = val.ToString(GermanCulture);
string valInEnglishFormat = val.ToString(EnglishCulture);
}
The call to time(NULL)
returns the current calendar time (seconds since Jan 1, 1970). See this reference for details. Ordinarily, if you pass in a pointer to a time_t
variable, that pointer variable will point to the current time.
Multiple folks have already pointed that
$ screen -ls
would list the screen sessions.
Here is another trick that may be useful to you.
If you add the following command as a last line in your .bashrc file on server xxx, then it will automatically reconnect to your screen session on login.
screen -d -r
Hope you find it useful.
You can pass the container by reference in order to modify it in the function. What other answers haven’t addressed is that std::vector
does not have a push_front
member function. You can use the insert()
member function on vector
for O(n) insertion:
void do_something(int el, std::vector<int> &arr){
arr.insert(arr.begin(), el);
}
Or use std::deque
instead for amortised O(1) insertion:
void do_something(int el, std::deque<int> &arr){
arr.push_front(el);
}
SQLAlchemy's declarative extension, which is becoming standard in 0.5, provides an all in one interface very much like that of Django or Storm. It also integrates seamlessly with classes/tables configured using the datamapper style:
Base = declarative_base()
class Foo(Base):
__tablename__ = 'foos'
id = Column(Integer, primary_key=True)
class Thing(Base):
__tablename__ = 'things'
id = Column(Integer, primary_key=True)
name = Column(Unicode)
description = Column(Unicode)
foo_id = Column(Integer, ForeignKey('foos.id'))
foo = relation(Foo)
engine = create_engine('sqlite://')
Base.metadata.create_all(engine) # issues DDL to create tables
session = sessionmaker(bind=engine)()
foo = Foo()
session.add(foo)
thing = Thing(name='thing1', description='some thing')
thing.foo = foo # also adds Thing to session
session.commit()
layout_weight
tells Android how to distribute your View
s in a LinearLayout
. Android then first calculates the total proportion required for all View
s that have a weight specified and places each View
according to what fraction of the screen it has specified it needs. In the following example, Android sees that the TextView
s have a layout_weight
of 0
(this is the default) and the EditText
s have a layout_weight
of 2
each, while the Button
has a weight of 1
. So Android allocates 'just enough' space to display tvUsername
and tvPassword
and then divides the remainder of the screen width into 5 equal parts, two of which are allocated to etUsername
, two to etPassword
and the last part to bLogin
:
<LinearLayout android:orientation="horizontal" ...>
<TextView android:id="@+id/tvUsername"
android:text="Username"
android:layout_width="wrap_content" ... />
<EditText android:id="@+id/etUsername"
android:layout_width="0dp"
android:layout_weight="2" ... />
<TextView android:id="@+id/tvPassword"
android:text="Password"
android:layout_width="wrap_content" />
<EditText android:id="@+id/etPassword"
android:layout_width="0dp"
android:layout_weight="2" ... />
<Button android:id="@+id/bLogin"
android:layout_width="0dp"
android:layout_weight="1"
android:text="Login"... />
</LinearLayout>
It looks like:
and
i would suggest the following way:
@PropertySource(ignoreResourceNotFound = true, value = "classpath:otherprops.properties")
@Controller
public class ClassA {
@Value("${myName}")
private String name;
@RequestMapping(value = "/xyz")
@ResponseBody
public void getName(){
System.out.println(name);
}
}
Here your new properties file name is "otherprops.properties" and the property name is "myName". This is the simplest implementation to access properties file in spring boot version 1.5.8.
By default the rotation point is the Canvas's (0,0) point, and my guess is that you may want to rotate it around the center. I did that:
protected void renderImage(Canvas canvas)
{
Rect dest,drawRect ;
drawRect = new Rect(0,0, mImage.getWidth(), mImage.getHeight());
dest = new Rect((int) (canvas.getWidth() / 2 - mImage.getWidth() * mImageResize / 2), // left
(int) (canvas.getHeight()/ 2 - mImage.getHeight()* mImageResize / 2), // top
(int) (canvas.getWidth() / 2 + mImage.getWidth() * mImageResize / 2), //right
(int) (canvas.getWidth() / 2 + mImage.getHeight()* mImageResize / 2));// bottom
if(!mRotate) {
canvas.drawBitmap(mImage, drawRect, dest, null);
} else {
canvas.save(Canvas.MATRIX_SAVE_FLAG); //Saving the canvas and later restoring it so only this image will be rotated.
canvas.rotate(90,canvas.getWidth() / 2, canvas.getHeight()/ 2);
canvas.drawBitmap(mImage, drawRect, dest, null);
canvas.restore();
}
}
Work example to find average default center with react-google-maps on ES6
:
const bounds = new google.maps.LatLngBounds();
paths.map((latLng) => bounds.extend(new google.maps.LatLng(latLng)));
const defaultCenter = bounds.getCenter();
<GoogleMap
defaultZoom={paths.length ? 12 : 4}
defaultCenter={defaultCenter}
>
<Marker position={{ lat, lng }} />
</GoogleMap>
If your access remotely you can do it
for bson:
mongorestore --host m2.mongodb.net --port 27016 --ssl --username $user --password $password --authenticationDatabase $authdb -d test -c people "/home/${USER}/people.bson"
for bson compressed in .gz (gzip) format:
mongorestore --host m2.mongodb.net --port 27016 --ssl --username $user --password $password --authenticationDatabase $authdb -d test -c people --gzip --dir "/home/${USER}/people.bson.gz"
I use this .htacess for removing .html extantion from my url site, please verify this is correct code:
RewriteEngine on
RewriteBase /
RewriteCond %{http://www.proofers.co.uk/new} !(\.[^./]+)$
RewriteCond %{REQUEST_fileNAME} !-d
RewriteCond %{REQUEST_fileNAME} !-f
RewriteRule (.*) /$1.html [L]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^.]+)\.html\ HTTP
RewriteRule ^([^.]+)\.html$ http://www.proofers.co.uk/new/$1 [R=301,L]
I get this error using gulp with rollup when I tried to use ES6 generators:
gulp.task('scripts', () => {
return rollup({
entry: './app/scripts/main.js',
format: "iife",
sourceMap: true,
plugins: [babel({
exclude: 'node_modules/**',
"presets": [
[
"es2015-rollup"
]
],
"plugins": [
"external-helpers"
]
}),
includePaths({
include: {},
paths: ['./app/scripts'],
external: [],
extensions: ['.js']
})]
})
.pipe(source('app.js'))
.pipe(buffer())
.pipe(sourcemaps.init({
loadMaps: true
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('.tmp/scripts'))
.pipe(reload({ stream: true }));
});
I may case the solution was to include babel-polyfill
as bower component:
bower install babel-polyfill --save
and add it as dependency in index.html:
<script src="/bower_components/babel-polyfill/browser-polyfill.js"></script>
If you need something from super's __init__
to be done in addition to what is being done in the current class's __init__,
you must call it yourself, since that will not happen automatically. But if you don't need anything from super's __init__,
no need to call it. Example:
>>> class C(object):
def __init__(self):
self.b = 1
>>> class D(C):
def __init__(self):
super().__init__() # in Python 2 use super(D, self).__init__()
self.a = 1
>>> class E(C):
def __init__(self):
self.a = 1
>>> d = D()
>>> d.a
1
>>> d.b # This works because of the call to super's init
1
>>> e = E()
>>> e.a
1
>>> e.b # This is going to fail since nothing in E initializes b...
Traceback (most recent call last):
File "<pyshell#70>", line 1, in <module>
e.b # This is going to fail since nothing in E initializes b...
AttributeError: 'E' object has no attribute 'b'
__del__
is the same way, (but be wary of relying on __del__
for finalization - consider doing it via the with statement instead).
I rarely use __new__.
I do all the initialization in __init__.
To make the command window of a .bat file that executes a .exe file exit out as fast as possible, use the line @start
before the file you're trying to execute. Here is an example:
(insert other code here)
@start executable.exe
(insert other code here)
You don't have to use other code with @start executable.exe
.
In the Web Developer Toolbar, have you tried the Tools -> Validate HTML
or Tools -> Validate Local HTML
options?
The Validate HTML
option sends the url to the validator, which works well with publicly facing sites. The Validate Local HTML
option sends the current page's HTML to the validator, which works well with pages behind a login, or those that aren't publicly accessible.
You may also want to try View Source Chart (also as FireFox add-on). An interesting note there:
Q. Why does View Source Chart change my XHTML tags to HTML tags?
A. It doesn't. The browser is making these changes, VSC merely displays what the browser has done with your code. Most common: self closing tags lose their closing slash (/). See this article on Rendered Source for more information (archive.org).
In my case I changed this:
<mat-form-field>
<input type="email" placeholder="email" [(ngModel)]="data.email">
</mat-form-field>
to this:
<mat-form-field>
<input matInput type="email" placeholder="email" [(ngModel)]="data.email">
</mat-form-field>
Adding the matInput directive to the input tag was what fixed this error for me.
Try using following command it work.
mysql --user=root --password=root_password
It is important to notice that in C# the char type is stored as Unicode UTF-16.
char c = (char)88;
or
char c = Convert.ToChar(88)
int asciiCode = (int)'A';
The literal must be ASCII equivalent. For example:
string str = "X?????????";
Console.WriteLine((int)str[0]);
Console.WriteLine((int)str[1]);
will print
X
3626
Extended ASCII ranges from 0 to 255.
Using the Symbol
char c = 'X';
Using the Unicode code
char c = '\u0058';
Using the Hexadecimal
char c = '\x0058';
It boils down to adding android:stretchColumns="*"
to your TableLayout
root and setting android:layout_width="0dp"
to all the children in your TableRow
s.
<TableLayout
android:stretchColumns="*" // Optionally use numbered list "0,1,2,3,..."
>
<TableRow
android:layout_width="0dp"
>
This will work:
smegma$ curl http://www.wolframalpha.com/input/?i=14+divided+by+3 2>/dev/null | gawk 'match($0, /link to /input/\?i=([0-9.+-]+)/, ary) { print substr( $0, ary[1, "start"], ary[1, "length"] )}' 4.6666666666666666666666666666666666666666666666666666
Just substitute '14' and '3' with your numbers.
The declaration and definition of insertLike
are different
In your header file:
void insertLike(const char sentence[], const int lengthTo, const int length,
const char writeTo[]);
In your 'function file':
void insertLike(const char sentence[], const int lengthTo, const int length,
char writeTo[]);
C++ allows function overloading, where you can have multiple functions/methods with the same name, as long as they have different arguments. The argument types are part of the function's signature.
In this case, insertLike
which takes const char*
as its fourth parameter and insertLike
which takes char *
as its fourth parameter are different functions.
Java 8's stream()
interface provides a great way to update a list in place.
To safely update items in the list, use map()
:
List<String> letters = new ArrayList<>();
// add stuff to list
letters = letters.stream().map(x -> "D").collect(Collectors.toList());
To safely remove items in place, use filter()
:
letters.stream().filter(x -> !x.equals("A")).collect(Collectors.toList());
I am contributing here, as the OP asked:
How to change collation of database, table, column?
The selected answer just states it on table level.
Changing it database wide:
ALTER DATABASE <database_name> CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
Changing it per table:
ALTER TABLE <table_name> CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
Good practice is to change it at table level as it'll change it for columns as well. Changing for specific column is for any specific case.
Changing collation for a specific column:
ALTER TABLE <table_name> MODIFY <column_name> VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
Because timedelta is defined like:
class datetime.timedelta([days,] [seconds,] [microseconds,] [milliseconds,] [minutes,] [hours,] [weeks])
All arguments are optional and default to 0.
You can easily say "Three days and four milliseconds" with optional arguments that way.
>>> datetime.timedelta(days=3, milliseconds=4)
datetime.timedelta(3, 0, 4000)
>>> datetime.timedelta(3, 0, 0, 4) #no need for that.
datetime.timedelta(3, 0, 4000)
And for str casting, it returns a nice formatted value instead of __repr__
to improve readability. From docs:
str(t) Returns a string in the form [D day[s], ][H]H:MM:SS[.UUUUUU], where D is negative for negative t. (5)
>>> datetime.timedelta(seconds = 42).__repr__()
'datetime.timedelta(0, 42)'
>>> datetime.timedelta(seconds = 42).__str__()
'0:00:42'
Checkout documentation:
http://docs.python.org/library/datetime.html#timedelta-objects
to_char(mydate, 'MONTH')
will do the job.
.html always for new files. .htm is a throwback to dos days.
Check this example of post the array of different types
function PostArray() {
var myObj = [
{ 'fstName': 'name 1', 'lastName': 'last name 1', 'age': 32 }
, { 'fstName': 'name 2', 'lastName': 'last name 1', 'age': 33 }
];
var postData = JSON.stringify({ lst: myObj });
console.log(postData);
$.ajax({
type: "POST",
url: urlWebMethods + "/getNames",
data: postData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
},
failure: function (msg) {
alert(msg.d);
}
});
}
If using a WebMethod in C# you can retrieve the data like this
[WebMethod]
public static string getNames(IEnumerable<object> lst)
{
string names = "";
try
{
foreach (object item in lst)
{
Type myType = item.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());
foreach (PropertyInfo prop in props)
{
if(prop.Name == "Values")
{
Dictionary<string, object> dic = item as Dictionary<string, object>;
names += dic["fstName"];
}
}
}
}
catch (Exception ex)
{
names = "-1";
}
return names;
}
Example in POST an array of objects with $.ajax to C# WebMethod
I might get beat up for my answer but here goes anyway:
I would simply write
string s = ""
if (myObj != null) {
x = myObj.toString();
}
Is there a payoff in terms of performance for using the ternary operator? I don't know off the top of my head.
And clearly, as someone above mentioned, you can put this behavior into a method such as safeString(myObj)
that allows for reuse.
JavaScript:
document.getElementsByTagName('head')[0].appendChild( ... );
Make DOM element like so:
link=document.createElement('link');
link.href='href';
link.rel='rel';
document.getElementsByTagName('head')[0].appendChild(link);
If you want to parse the format yourself you could do it easily with a regex such as
private static Pattern pattern = Pattern.compile("(\\d{2}):(\\d{2}):(\\d{2}).(\\d{3})");
public static long dateParseRegExp(String period) {
Matcher matcher = pattern.matcher(period);
if (matcher.matches()) {
return Long.parseLong(matcher.group(1)) * 3600000L
+ Long.parseLong(matcher.group(2)) * 60000
+ Long.parseLong(matcher.group(3)) * 1000
+ Long.parseLong(matcher.group(4));
} else {
throw new IllegalArgumentException("Invalid format " + period);
}
}
However, this parsing is quite lenient and would accept 99:99:99.999 and just let the values overflow. This could be a drawback or a feature.
It's not so much the prime numbers themselves that are important, but the algorithms that work with primes. In particular, finding the factors of a number (any number).
As you know, any number has at least two factors. Prime numbers have the unique property in that they have exactly two factors: 1 and themselves.
The reason factoring is so important is mathematicians and computer scientists don't know how to factor a number without simply trying every possible combination. That is, first try dividing by 2, then by 3, then by 4, and so forth. If you try to factor a prime number--especially a very large one--you'll have to try (essentially) every possible number between 2 and that large prime number. Even on the fastest computers, it will take years (even centuries) to factor the kinds of prime numbers used in cryptography.
It is the fact that we don't know how to efficiently factor a large number that gives cryptographic algorithms their strength. If, one day, someone figures out how to do it, all the cryptographic algorithms we currently use will become obsolete. This remains an open area of research.
I'm going to give you an example of how I read REST headers for my controllers. My controllers only accept application/json as a request type if I have data that needs to be read. I suspect that your problem is that you have an application/octet-stream that Spring doesn't know how to handle.
Normally my controllers look like this:
@Controller
public class FooController {
@Autowired
private DataService dataService;
@RequestMapping(value="/foo/", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Data> getData(@RequestHeader String dataId){
return ResponseEntity.newInstance(dataService.getData(dataId);
}
Now there is a lot of code doing stuff in the background here so I will break it down for you.
ResponseEntity is a custom object that every controller returns. It contains a static factory allowing the creation of new instances. My Data Service is a standard service class.
The magic happens behind the scenes, because you are working with JSON, you need to tell Spring to use Jackson to map HttpRequest objects so that it knows what you are dealing with.
You do this by specifying this inside your <mvc:annotation-driven>
block of your config
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper" ref="objectMapper" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
ObjectMapper is simply an extension of com.fasterxml.jackson.databind.ObjectMapper
and is what Jackson uses to actually map your request from JSON into an object.
I suspect you are getting your exception because you haven't specified a mapper that can read an Octet-Stream into an object, or something that Spring can handle. If you are trying to do a file upload, that is something else entirely.
So my request that gets sent to my controller looks something like this simply has an extra header called dataId
.
If you wanted to change that to a request parameter and use @RequestParam String dataId
to read the ID out of the request your request would look similar to this:
contactId : {"fooId"}
This request parameter can be as complex as you like. You can serialize an entire object into JSON, send it as a request parameter and Spring will serialize it (using Jackson) back into a Java Object ready for you to use.
Example In Controller:
@RequestMapping(value = "/penguin Details/", method = RequestMethod.GET)
@ResponseBody
public DataProcessingResponseDTO<Pengin> getPenguinDetailsFromList(
@RequestParam DataProcessingRequestDTO jsonPenguinRequestDTO)
Request Sent:
jsonPengiunRequestDTO: {
"draw": 1,
"columns": [
{
"data": {
"_": "toAddress",
"header": "toAddress"
},
"name": "toAddress",
"searchable": true,
"orderable": true,
"search": {
"value": "",
"regex": false
}
},
{
"data": {
"_": "fromAddress",
"header": "fromAddress"
},
"name": "fromAddress",
"searchable": true,
"orderable": true,
"search": {
"value": "",
"regex": false
}
},
{
"data": {
"_": "customerCampaignId",
"header": "customerCampaignId"
},
"name": "customerCampaignId",
"searchable": true,
"orderable": true,
"search": {
"value": "",
"regex": false
}
},
{
"data": {
"_": "penguinId",
"header": "penguinId"
},
"name": "penguinId",
"searchable": false,
"orderable": true,
"search": {
"value": "",
"regex": false
}
},
{
"data": {
"_": "validpenguin",
"header": "validpenguin"
},
"name": "validpenguin",
"searchable": true,
"orderable": true,
"search": {
"value": "",
"regex": false
}
},
{
"data": {
"_": "",
"header": ""
},
"name": "",
"searchable": false,
"orderable": false,
"search": {
"value": "",
"regex": false
}
}
],
"order": [
{
"column": 0,
"dir": "asc"
}
],
"start": 0,
"length": 10,
"search": {
"value": "",
"regex": false
},
"objectId": "30"
}
which gets automatically serialized back into an DataProcessingRequestDTO object before being given to the controller ready for me to use.
As you can see, this is quite powerful allowing you to serialize your data from JSON to an object without having to write a single line of code. You can do this for @RequestParam
and @RequestBody
which allows you to access JSON inside your parameters or request body respectively.
Now that you have a concrete example to go off, you shouldn't have any problems once you change your request type to application/json
.
function getParsedDate(date){
date = String(date).split(' ');
var days = String(date[0]).split('-');
var hours = String(date[1]).split(':');
return [parseInt(days[0]), parseInt(days[1])-1, parseInt(days[2]), parseInt(hours[0]), parseInt(hours[1]), parseInt(hours[2])];
}
var date = new Date(...getParsedDate('2016-01-04 10:34:23'));
console.log(date);
Because of the variances in parsing of date strings, it is recommended to always manually parse strings as results are inconsistent, especially across different ECMAScript implementations where strings like "2015-10-12 12:00:00" may be parsed to as NaN, UTC or local timezone.
... as described in the resource:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
You can update your provisioning certificates in XCode at:
Organizer -> Devices -> LIBRARY -> Provisioning Profiles
There is a refresh button :) So if you have created the certificate manually in iTunes connect, then you need to press this button or download the certificate manually.
If you have Gimp, I saw that exporting the image in .eps format would do the job.
You will have to access db through the ip of host machine, or if you want to access it via localhost:1521, then run webserver like -
docker run --net=host --name oracle-wls wls-image:latest
This excerpt from the glibc manual 0.02 may also be relevant when researching the topic:
There is a potential problem with the size_t type and versions of GCC prior to release 2.4. ANSI C requires that size_t always be an unsigned type. For compatibility with existing systems' header files, GCC defines size_t in stddef.h' to be whatever type the system's
sys/types.h' defines it to be. Most Unix systems that define size_t in `sys/types.h', define it to be a signed type. Some code in the library depends on size_t being an unsigned type, and will not work correctly if it is signed.
The GNU C library code which expects size_t to be unsigned is correct. The definition of size_t as a signed type is incorrect. We plan that in version 2.4, GCC will always define size_t as an unsigned type, and the fixincludes' script will massage the system's
sys/types.h' so as not to conflict with this.
In the meantime, we work around this problem by telling GCC explicitly to use an unsigned type for size_t when compiling the GNU C library. `configure' will automatically detect what type GCC uses for size_t arrange to override it if necessary.
What worked for me after following all your workarounds was to call the API:
<script async defer src="https://maps.googleapis.com/maps/api/js?key=you_API_KEY&callback=initMap&libraries=places"
type="text/javascript"></script>
before my : <div id="map"></div>
I am using .ASP NET (MVC)
You can bind the mouseenter
and mouseleave
events and jQuery will emulate those where they are not native.
$("div.system_box").on('mouseenter', function(){
//enter
})
.on('mouseleave', function(){
//leave
});
note: do not use hover as that is deprecated
from cmd run: SVN List URL you will be provided with 3 options (r)eject, (a)ccept, (p)ermanently. enter p. This resolved issue for me
Either add an event listener, or have the image announce itself with onload. Then figure out the dimensions from there.
<img id="photo"
onload='loaded(this.id)'
src="a_really_big_file.jpg"
alt="this is some alt text"
title="this is some title text" />
The easiest way is kill all nginx processes
sudo killall nginx
then
sudo nginx
or
sudo service nginx start
If you want to upload a single file with Python requests
library, then requests lib supports streaming uploads, which allow you to send large files or streams without reading into memory.
with open('massive-body', 'rb') as f:
requests.post('http://some.url/streamed', data=f)
Then store the file on the server.py
side such that save the stream into file without loading into the memory. Following is an example with using Flask file uploads.
@app.route("/upload", methods=['POST'])
def upload_file():
from werkzeug.datastructures import FileStorage
FileStorage(request.stream).save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return 'OK', 200
Or use werkzeug Form Data Parsing as mentioned in a fix for the issue of "large file uploads eating up memory" in order to avoid using memory inefficiently on large files upload (s.t. 22 GiB file in ~60 seconds. Memory usage is constant at about 13 MiB.).
@app.route("/upload", methods=['POST'])
def upload_file():
def custom_stream_factory(total_content_length, filename, content_type, content_length=None):
import tempfile
tmpfile = tempfile.NamedTemporaryFile('wb+', prefix='flaskapp', suffix='.nc')
app.logger.info("start receiving file ... filename => " + str(tmpfile.name))
return tmpfile
import werkzeug, flask
stream, form, files = werkzeug.formparser.parse_form_data(flask.request.environ, stream_factory=custom_stream_factory)
for fil in files.values():
app.logger.info(" ".join(["saved form name", fil.name, "submitted as", fil.filename, "to temporary file", fil.stream.name]))
# Do whatever with stored file at `fil.stream.name`
return 'OK', 200
update q
set q.QuestionID = a.QuestionID
from QuestionTrackings q
inner join QuestionAnswers a
on q.AnswerID = a.AnswerID
where q.QuestionID is null -- and other conditions you might want
I recommend to check what the result set to update is before running the update (same query, just with a select):
select *
from QuestionTrackings q
inner join QuestionAnswers a
on q.AnswerID = a.AnswerID
where q.QuestionID is null -- and other conditions you might want
Particularly whether each answer id has definitely only 1 associated question id.
A handle can be anything from an integer index to a pointer to a resource in kernel space. The idea is that they provide an abstraction of a resource, so you don't need to know much about the resource itself to use it.
For instance, the HWND in the Win32 API is a handle for a Window. By itself it's useless: you can't glean any information from it. But pass it to the right API functions, and you can perform a wealth of different tricks with it. Internally you can think of the HWND as just an index into the GUI's table of windows (which may not necessarily be how it's implemented, but it makes the magic make sense).
EDIT: Not 100% certain what specifically you were asking in your question. This is mainly talking about pure C/C++.
function readFile() {_x000D_
_x000D_
if (this.files && this.files[0]) {_x000D_
_x000D_
var FR= new FileReader();_x000D_
_x000D_
FR.addEventListener("load", function(e) {_x000D_
document.getElementById("img").src = e.target.result;_x000D_
document.getElementById("b64").innerHTML = e.target.result;_x000D_
}); _x000D_
_x000D_
FR.readAsDataURL( this.files[0] );_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
document.getElementById("inp").addEventListener("change", readFile);
_x000D_
<input id="inp" type='file'>_x000D_
<p id="b64"></p>_x000D_
<img id="img" height="150">
_x000D_
(P.S: A base64 encoded image (String) 4/3 the size of the original image data)
Check this answer for multiple images upload.
Browser support: http://caniuse.com/#search=file%20api
More info here: https://developer.mozilla.org/en-US/docs/Web/API/FileReader
There are 4 ways that I know of:
I assume you don't want to pay for this, so I think the most elegant solution is the first one, what can be accomplished this way:
http://blog.crazybob.org/2010/02/android-trusting-ssl-certificates.html
In order to use our own class objects as keys in collections like HashMap, Hashtable etc.. , we should override both methods ( hashCode() and equals() ) by having an awareness on internal working of collection. Otherwise, it leads to wrong results which we are not expected.
In ExtJs, you can use
xtype: 'image'
to render a image.
Here is a fiddle showing rendering of binary data with extjs.
atob -- > converts ascii to binary
btoa -- > converts binary to ascii
Ext.application({
name: 'Fiddle',
launch: function () {
var srcBase64 = "data:image/jpeg;base64," + btoa(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8H8hYDwAFegHS8+X7mgAAAABJRU5ErkJggg=="));
Ext.create("Ext.panel.Panel", {
title: "Test",
renderTo: Ext.getBody(),
height: 400,
items: [{
xtype: 'image',
width: 100,
height: 100,
src: srcBase64
}]
})
}
});
For IPv4, you could get away with storing the 4 raw bytes of the IP address (each of the numbers between the periods in an IP address are 0-255, i.e., one byte). But then you would have to translate going in and out of the DB and that's messy.
IPv6 addresses are 128 bits (as opposed to 32 bits of IPv4 addresses). They are usually written as 8 groups of 4 hex digits separated by colons: 2001:0db8:85a3:0000:0000:8a2e:0370:7334
. 39 characters is appropriate to store IPv6 addresses in this format.
Edit: However, there is a caveat, see @Deepak's answer for details about IPv4-mapped IPv6 addresses. (The correct maximum IPv6 string length is 45 characters.)
While I respect the answer from qkrijger explaining how you can work around this issue I think there is a lot more we can learn about what's going on here ...
To actually answer your question of "why" ... I think it would for helpful for you to understand how the docker stop
command works and that all processes should be shutdown cleanly to prevent problems when you try to restart them (file corruption etc).
Problem: What if docker did start SSH from it's command and started RabbitMQ from your Docker file? "The docker stop command attempts to stop a running container first by sending a SIGTERM signal to the root process (PID 1) in the container." Which process is docker tracking as PID 1 that will get the SIGTERM? Will it be SSH or Rabbit?? "According to the Unix process model, the init process -- PID 1 -- inherits all orphaned child processes and must reap them. Most Docker containers do not have an init process that does this correctly, and as a result their containers become filled with zombie processes over time."
Answer: Docker simply takes that last CMD as the one that will get launched as the root process with PID 1 and get the SIGTERM from docker stop
.
Suggested solution: You should use (or create) a base image specifically made for running more than one service, such as phusion/baseimage
It should be important to note that tini exists exactly for this reason, and as of Docker 1.13 and up, tini is officially part of Docker, which tells us that running more than one process in Docker IS VALID .. so even if someone claims to be more skilled regarding Docker, and insists that you absurd for thinking of doing this, know that you are not. There are perfectly valid situations for doing so.
Good to know:
This doesn't seem to have <a> </a>
tags so selenium might not be able to detect it as a link.
You may try and use
driver.findElement(By.xpath("//*[@class='ng-binding']")).click();
if this is the only element in that page with this class .
A standard width space for a standard 16px font is 4px.
I had the same problem.
I solved it by changing selinux status to permissive with below command:
setenforce 0
In my case URI, as it was defined on FB, was fine, but I was using Spring Security and it was adding ;jsessionid=0B9A5E71DAA32A01A3CD351E6CA1FCDD to my URI so, it caused the mismatching.
https://m.facebook.com/v2.5/dialog/oauth?client_id=your-fb-id-code&response_type=code&redirect_uri=https://localizator.org/auth/facebook;jsessionid=0B9A5E71DAA32A01A3CD351E6CA1FCDD&scope=email&state=b180578a-007b-48bc-bd81-4b08c6989e18
In order to avoid the URL rewriting I added disable-url-rewriting="true" to Spring Security config, in this way:
<http auto-config="true" access-denied-page="/security/accessDenied" use-expressions="true"
disable-url-rewriting="true" entry-point-ref="authenticationEntryPoint"/>
And it fixed my problem.
An important point is to consider if you perform tasks based on difference between 2 timestamps because you will get odd behavior if you generate it with gettimeofday()
, and even clock_gettime(CLOCK_REALTIME,..)
at the moment where you will set the time of your system.
To prevent such problem, use clock_gettime(CLOCK_MONOTONIC_RAW, &tms)
instead.
a recursive try for this
function t(k){
if (k[0]==' ') {
return t(k.substr(1,k.length));
} else if (k[k.length-1]==' ') {
return t(k.substr(0,k.length-1));
} else {
return k;
}
}
call like this:
t(" mehmet "); //=>"mehmet"
if you want to filter spesific chars you can define a list string basically:
function t(k){
var l="\r\n\t "; //you can add more chars here.
if (l.indexOf(k[0])>-1) {
return t(k.substr(1,k.length));
} else if (l.indexOf(k[k.length-1])>-1) {
return t(k.substr(0,k.length-1));
} else {
return k;
}
}
Change encoding in notepad++ UTF-8 with BOM. That is how it worked for me
Added MSSQLSERVER full access to the folder, diskadmin and bulkadmin server roles.
In my c# application, when preparing for the bulk insert command,
string strsql = "BULK INSERT PWCR_Contractor_vw_TEST FROM '" + strFileName + "' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\\n')";
And I get this error - Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 8 (STATUS).
I looked at my logfile and found that the terminator becomes ' ' instead of '\n'. The OLE DB provider "BULK" for linked server "(null)" reported an error. The provider did not give any information about the error:
Cannot fetch a row from OLE DB provider "BULK" for linked server "(null)". Query :BULK INSERT PWCR_Contractor_vw_TEST FROM 'G:\NEWSTAGEWWW\CalAtlasToPWCR\Results\parsedRegistration.csv' WITH (FIELDTERMINATOR = ',', **ROWTERMINATOR = ''**)
So I added extra escape to the rowterminator - string strsql = "BULK INSERT PWCR_Contractor_vw_TEST FROM '" + strFileName + "' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\\n')";
And now it inserts successfully.
Bulk Insert SQL - ---> BULK INSERT PWCR_Contractor_vw_TEST FROM 'G:\\NEWSTAGEWWW\\CalAtlasToPWCR\\Results\\parsedRegistration.csv' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n')
Bulk Insert to PWCR_Contractor_vw_TEST successful... ---> clsDatase.PerformBulkInsert
If you want to stay close to .NET check out Enterprise Library Logging Application Block. Look here. Or for a quickstart tutorial check this. I have used the Validation application Block from the Enterprise Library and it really suits my needs and is very easy to "inherit" (install it and refrence it!) in your project.
You can get the multiple element by id by identifying what element it is. For example
<div id='id'></div>
<div id='id'></div>
<div id='id'></div>
I assume if you are using jQuery you can select all them all by
$("div#id")
. This will get you array of elements you loop them based on your logic.
Use:
git reset HEAD^
That does a "mixed" reset by default, which will do what you asked; put foo.java in unstaged, removing the most recent commit.
Every time I go from heavy C++ coding to Java, it takes me a little while to adapt to the lack of const-correctness in Java. This usage of const
in C++ is much different than just declaring constant variables, if you didn't know. Essentially, it ensures that an object is immutable when accessed through a special kind of pointer called a const-pointer When in Java, in places where I'd normally want to return a const-pointer, I instead return a reference with an interface type containing only methods that shouldn't have side effects. Unfortunately, this isn't enforced by the langauge.
Wikipedia offers the following information on the subject:
Interestingly, the Java language specification regards const as a reserved keyword — i.e., one that cannot be used as variable identifier — but assigns no semantics to it. It is thought that the reservation of the keyword occurred to allow for an extension of the Java language to include C++-style const methods and pointer to const type. The enhancement request ticket in the Java Community Process for implementing const correctness in Java was closed in 2005, implying that const correctness will probably never find its way into the official Java specification.
Note that the type(numpy.ndarray)
is a type
itself and watch out for boolean and scalar types. Don't be too discouraged if it's not intuitive or easy, it's a pain at first.
See also: - https://docs.scipy.org/doc/numpy-1.15.1/reference/arrays.dtypes.html - https://github.com/machinalis/mypy-data/tree/master/numpy-mypy
>>> import numpy as np
>>> np.ndarray
<class 'numpy.ndarray'>
>>> type(np.ndarray)
<class 'type'>
>>> a = np.linspace(1,25)
>>> type(a)
<class 'numpy.ndarray'>
>>> type(a) == type(np.ndarray)
False
>>> type(a) == np.ndarray
True
>>> isinstance(a, np.ndarray)
True
Fun with booleans:
>>> b = a.astype('int32') == 11
>>> b[0]
False
>>> isinstance(b[0], bool)
False
>>> isinstance(b[0], np.bool)
False
>>> isinstance(b[0], np.bool_)
True
>>> isinstance(b[0], np.bool8)
True
>>> b[0].dtype == np.bool
True
>>> b[0].dtype == bool # python equivalent
True
More fun with scalar types, see: - https://docs.scipy.org/doc/numpy-1.15.1/reference/arrays.scalars.html#arrays-scalars-built-in
>>> x = np.array([1,], dtype=np.uint64)
>>> x[0].dtype
dtype('uint64')
>>> isinstance(x[0], np.uint64)
True
>>> isinstance(x[0], np.integer)
True # generic integer
>>> isinstance(x[0], int)
False # but not a python int in this case
# Try matching the `kind` strings, e.g.
>>> np.dtype('bool').kind
'b'
>>> np.dtype('int64').kind
'i'
>>> np.dtype('float').kind
'f'
>>> np.dtype('half').kind
'f'
# But be weary of matching dtypes
>>> np.integer
<class 'numpy.integer'>
>>> np.dtype(np.integer)
dtype('int64')
>>> x[0].dtype == np.dtype(np.integer)
False
# Down these paths there be dragons:
# the .dtype attribute returns a kind of dtype, not a specific dtype
>>> isinstance(x[0].dtype, np.dtype)
True
>>> isinstance(x[0].dtype, np.uint64)
False
>>> isinstance(x[0].dtype, np.dtype(np.uint64))
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: isinstance() arg 2 must be a type or tuple of types
# yea, don't go there
>>> isinstance(x[0].dtype, np.int_)
False # again, confusing the .dtype with a specific dtype
# Inequalities can be tricky, although they might
# work sometimes, try to avoid these idioms:
>>> x[0].dtype <= np.dtype(np.uint64)
True
>>> x[0].dtype <= np.dtype(np.float)
True
>>> x[0].dtype <= np.dtype(np.half)
False # just when things were going well
>>> x[0].dtype <= np.dtype(np.float16)
False # oh boy
>>> x[0].dtype == np.int
False # ya, no luck here either
>>> x[0].dtype == np.int_
False # or here
>>> x[0].dtype == np.uint64
True # have to end on a good note!
If you check Use option as meta key
in the keyboard tab of the preferences, then the default emacs style commands for forward- and backward-word and ?F
(Alt+F) and ?B
(Alt+B) respectively.
I'd recommend reading From Bash to Z-Shell. If you want to increase your bash/zsh prowess!
If nothing work try the following in the production environment
1-
composer install --optimize-autoloader --no-dev
2-
php artisan cache:clear
3-
php artisan config:clear
4-
php artisan view:clear
5-
php artisan config:cache
6-
php artisan route:cache
Works for me
(Updated 2018-03-17)
The problem, as you've spotted, is that String.Contains
does not perform a word-boundary check, so Contains("float")
will return true
for both "foo float bar" (correct) and "unfloating" (which is incorrect).
The solution is to ensure that "float" (or whatever your desired class-name is) appears alongside a word-boundary at both ends. A word-boundary is either the start (or end) of a string (or line), whitespace, certain punctuation, etc. In most regular-expressions this is \b
. So the regex you want is simply: \bfloat\b
.
A downside to using a Regex
instance is that they can be slow to run if you don't use the .Compiled
option - and they can be slow to compile. So you should cache the regex instance. This is more difficult if the class-name you're looking for changes at runtime.
Alternatively you can search a string for words by word-boundaries without using a regex by implementing the regex as a C# string-processing function, being careful not to cause any new string or other object allocation (e.g. not using String.Split
).
Suppose you just want to look for elements with a single, design-time specified class-name:
class Program {
private static readonly Regex _classNameRegex = new Regex( @"\bfloat\b", RegexOptions.Compiled );
private static IEnumerable<HtmlNode> GetFloatElements(HtmlDocument doc) {
return doc
.Descendants()
.Where( n => n.NodeType == NodeType.Element )
.Where( e => e.Name == "div" && _classNameRegex.IsMatch( e.GetAttributeValue("class", "") ) );
}
}
If you need to choose a single class-name at runtime then you can build a regex:
private static IEnumerable<HtmlNode> GetElementsWithClass(HtmlDocument doc, String className) {
Regex regex = new Regex( "\\b" + Regex.Escape( className ) + "\\b", RegexOptions.Compiled );
return doc
.Descendants()
.Where( n => n.NodeType == NodeType.Element )
.Where( e => e.Name == "div" && regex.IsMatch( e.GetAttributeValue("class", "") ) );
}
If you have multiple class-names and you want to match all of them, you could create an array of Regex
objects and ensure they're all matching, or combine them into a single Regex
using lookarounds, but this results in horrendously complicated expressions - so using a Regex[]
is probably better:
using System.Linq;
private static IEnumerable<HtmlNode> GetElementsWithClass(HtmlDocument doc, String[] classNames) {
Regex[] exprs = new Regex[ classNames.Length ];
for( Int32 i = 0; i < exprs.Length; i++ ) {
exprs[i] = new Regex( "\\b" + Regex.Escape( classNames[i] ) + "\\b", RegexOptions.Compiled );
}
return doc
.Descendants()
.Where( n => n.NodeType == NodeType.Element )
.Where( e =>
e.Name == "div" &&
exprs.All( r =>
r.IsMatch( e.GetAttributeValue("class", "") )
)
);
}
The advantage of using a custom C# method to do string matching instead of a regex is hypothetically faster performance and reduced memory usage (though Regex
may be faster in some circumstances - always profile your code first, kids!)
This method below: CheapClassListContains
provides a fast word-boundary-checking string matching function that can be used the same way as regex.IsMatch
:
private static IEnumerable<HtmlNode> GetElementsWithClass(HtmlDocument doc, String className) {
return doc
.Descendants()
.Where( n => n.NodeType == NodeType.Element )
.Where( e =>
e.Name == "div" &&
CheapClassListContains(
e.GetAttributeValue("class", ""),
className,
StringComparison.Ordinal
)
);
}
/// <summary>Performs optionally-whitespace-padded string search without new string allocations.</summary>
/// <remarks>A regex might also work, but constructing a new regex every time this method is called would be expensive.</remarks>
private static Boolean CheapClassListContains(String haystack, String needle, StringComparison comparison)
{
if( String.Equals( haystack, needle, comparison ) ) return true;
Int32 idx = 0;
while( idx + needle.Length <= haystack.Length )
{
idx = haystack.IndexOf( needle, idx, comparison );
if( idx == -1 ) return false;
Int32 end = idx + needle.Length;
// Needle must be enclosed in whitespace or be at the start/end of string
Boolean validStart = idx == 0 || Char.IsWhiteSpace( haystack[idx - 1] );
Boolean validEnd = end == haystack.Length || Char.IsWhiteSpace( haystack[end] );
if( validStart && validEnd ) return true;
idx++;
}
return false;
}
HtmlAgilityPack is somewhat stagnated doesn't support .querySelector
and .querySelectorAll
, but there are third-party libraries that extend HtmlAgilityPack with it: namely Fizzler and CssSelectors. Both Fizzler and CssSelectors implement QuerySelectorAll
, so you can use it like so:
private static IEnumerable<HtmlNode> GetDivElementsWithFloatClass(HtmlDocument doc) {
return doc.QuerySelectorAll( "div.float" );
}
With runtime-defined classes:
private static IEnumerable<HtmlNode> GetDivElementsWithClasses(HtmlDocument doc, IEnumerable<String> classNames) {
String selector = "div." + String.Join( ".", classNames );
return doc.QuerySelectorAll( selector );
}
It looks it's essential to call decode() function to make use of actual string data even after calling base64.b64decode over base64 encoded string. Because never forget it always return bytes literals.
import base64
conv_bytes = bytes('your string', 'utf-8')
print(conv_bytes) # b'your string'
encoded_str = base64.b64encode(conv_bytes)
print(encoded_str) # b'eW91ciBzdHJpbmc='
print(base64.b64decode(encoded_str)) # b'your string'
print(base64.b64decode(encoded_str).decode()) # your string
If you have forked a repository fro Delete your forked copy and fork it again from master.
git clone ssh://[email protected]:[port]/gitolite-admin
Note that the port number should be there without the square brackets: []
You can use it like this:
$(document).ready(function(){
setTimeout("swapImages()",1000);
function swapImages(){
var active = $('.active');
var next = ($('.active').next().length > 0) ? $('.active').next() : $('#siteNewsHead img:first');
active.removeClass('active');
next.addClass('active');
setTimeout("swapImages()",1000);
}
});
I am not a javascript person, but I found here for searching this problem. For who google it and find here, I am hoping that this helps some. So, as in question if we have a list of radio buttons:
<div class="list">
<input type="radio" name="b1" value="1">
<input type="radio" name="b2" value="2" checked="checked">
<input type="radio" name="b3" value="3">
</div>
I can find which one selected with this selector:
$('.list input[type="radio"]:checked:first').val();
Even if there is no element selected, I still don't get undefined error. So, you don't have to write extra if statement before taking element's value.
Here is very basic jsfiddle example.
I usually approach it like this:
char[] c = text.ToCharArray();
for (i=0; i<c.Length; i++)
{
if (c[i]>'9' || c[i]<'0') // use any rules of your choice
{
c[i]=' '; // put in any character you like
}
}
// the new string can have the same name, or a new variable
String text=new string(c);
You are correct that this is currently not natively supported in Android, although Google has been saying it will be coming ever since Android was officially launched.
While not natively supported, the hardware on every android device released to date do support it. It is just disabled in software, and you would need to enable it in order to use these features.
It is however, fairly easy to do this, but you need to be root, and the specifics may be slightly different between different devices. Your best source for more informationa about this, would be XDA developers: http://forum.xda-developers.com/forumdisplay.php?f=564. Most of the existing solutions are based on replacing wpa_supplicant, and is the method I would recommend if possible on your device. For more details, see http://szym.net/2010/12/adhoc-wifi-in-android/.
Update: Its been a few years now, and whenever I need an ad hoc network connection on my phone I use CyanogenMod. It gives you both programmatic and scripted access to these functions, and the ability to create ad hoc (ibss) networks in the WiFi settings menu.
I was getting this exception when debugging in PyCharm, given that no breakpoint was being hit. To prevent it, I added a breakpoint just after the with
block, and then it stopped happening.
I am using the new EF & Identity Core and I have the same issue, with the addition that I've got this error:
The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked.
With the new DI model I added the constructor's Controller the context to the DB.
I tried to see what are the conflict with _conext.ChangeTracker.Entries()
and adding AsNoTracking()
to my calls without success.
I only need to change the state of my object (in this case Identity)
_context.Entry(user).State = EntityState.Modified;
var result = await _userManager.UpdateAsync(user);
And worked without create another store or object and mapping.
I hope someone else is useful my two cents.
Android has all the tools you need to parse json built-in. Example follows, no need for GSON or anything like that.
Get your JSON:
Assume you have a json string
String result = "{\"someKey\":\"someValue\"}";
Create a JSONObject:
JSONObject jObject = new JSONObject(result);
If your json string is an array, e.g.:
String result = "[{\"someKey\":\"someValue\"}]"
then you should use JSONArray
as demonstrated below and not JSONObject
To get a specific string
String aJsonString = jObject.getString("STRINGNAME");
To get a specific boolean
boolean aJsonBoolean = jObject.getBoolean("BOOLEANNAME");
To get a specific integer
int aJsonInteger = jObject.getInt("INTEGERNAME");
To get a specific long
long aJsonLong = jObject.getLong("LONGNAME");
To get a specific double
double aJsonDouble = jObject.getDouble("DOUBLENAME");
To get a specific JSONArray:
JSONArray jArray = jObject.getJSONArray("ARRAYNAME");
To get the items from the array
for (int i=0; i < jArray.length(); i++)
{
try {
JSONObject oneObject = jArray.getJSONObject(i);
// Pulling items from the array
String oneObjectsItem = oneObject.getString("STRINGNAMEinTHEarray");
String oneObjectsItem2 = oneObject.getString("anotherSTRINGNAMEINtheARRAY");
} catch (JSONException e) {
// Oops
}
}
If your server certificated file is not trusted, (for example, you may generate the keystore by yourself with keytool command in java), you should add the extra option rejectUnauthorized
var socket = io.connect('https://localhost', {rejectUnauthorized: false});
We can get a list of files inside a folder on the file system using various golang standard library functions.
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
)
func main() {
var (
root string
files []string
err error
)
root := "/home/manigandan/golang/samples"
// filepath.Walk
files, err = FilePathWalkDir(root)
if err != nil {
panic(err)
}
// ioutil.ReadDir
files, err = IOReadDir(root)
if err != nil {
panic(err)
}
//os.File.Readdir
files, err = OSReadDir(root)
if err != nil {
panic(err)
}
for _, file := range files {
fmt.Println(file)
}
}
The
path/filepath
package provides a handy way to scan all the files in a directory, it will automatically scan each sub-directories in the directory.
func FilePathWalkDir(root string) ([]string, error) {
var files []string
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if !info.IsDir() {
files = append(files, path)
}
return nil
})
return files, err
}
ioutil.ReadDir
reads the directory named by dirname and returns a list of directory entries sorted by filename.
func IOReadDir(root string) ([]string, error) {
var files []string
fileInfo, err := ioutil.ReadDir(root)
if err != nil {
return files, err
}
for _, file := range fileInfo {
files = append(files, file.Name())
}
return files, nil
}
Readdir reads the contents of the directory associated with file and returns a slice of up to n FileInfo values, as would be returned by Lstat, in directory order. Subsequent calls on the same file will yield further FileInfos.
func OSReadDir(root string) ([]string, error) {
var files []string
f, err := os.Open(root)
if err != nil {
return files, err
}
fileInfo, err := f.Readdir(-1)
f.Close()
if err != nil {
return files, err
}
for _, file := range fileInfo {
files = append(files, file.Name())
}
return files, nil
}
Benchmark results.
Get more details on this Blog Post