With jQuery UI just do this!
$( "#draggable" ).draggable({
start: function() {
},
drag: function() {
},
stop: function() {
}
});
waits milliseconds to check if the key is pressed, if pressed in that interval return its ascii value, otherwise it still -1
Here's the correct answer, extracted from comments by Daniel Rikowski and pseidemann. I'm tired of having to weed through comments to find the right answer...
If you use Rails (ActiveSupport):
result.class.name.demodulize
If you use POR (plain-ol-Ruby):
result.class.name.split('::').last
There is no limit according to the HTTP protocol itself, but implementations will have a practical upper limit. I have sent data exceeding 4 GB using POST to Apache, but some servers did have a limit of 4 GB at the time.
I use that for all status (update, insert and delete)
CREATE TRIGGER trg_Insert_Test
ON [dbo].[MyTable]
AFTER UPDATE, INSERT, DELETE
AS
BEGIN
SET NOCOUNT ON;
DECLARE @Activity NVARCHAR (50)
-- update
IF EXISTS (SELECT * FROM inserted) AND EXISTS (SELECT * FROM deleted)
BEGIN
SET @Activity = 'UPDATE'
END
-- insert
IF EXISTS (SELECT * FROM inserted) AND NOT EXISTS(SELECT * FROM deleted)
BEGIN
SET @Activity = 'INSERT'
END
-- delete
IF EXISTS (SELECT * FROM deleted) AND NOT EXISTS(SELECT * FROM inserted)
BEGIN
SET @Activity = 'DELETE'
END
-- delete temp table
IF OBJECT_ID('tempdb..#tmpTbl') IS NOT NULL DROP TABLE #tmpTbl
-- get last 1 row
SELECT * INTO #tmpTbl FROM (SELECT TOP 1 * FROM (SELECT * FROM inserted
UNION
SELECT * FROM deleted
) AS A ORDER BY A.Date DESC
) AS T
-- try catch
BEGIN TRY
INSERT INTO MyTable (
[Code]
,[Name]
.....
,[Activity])
SELECT [Code]
,[Name]
,@Activity
FROM #tmpTbl
END TRY BEGIN CATCH END CATCH
-- delete temp table
IF OBJECT_ID('tempdb..#tmpTbl') IS NOT NULL DROP TABLE #tmpTbl
SET NOCOUNT OFF;
END
You can call a function after the state value has updated:
this.setState({foo: 'bar'}, () => {
// Do something here.
});
Also, if you have lots of states to update at once, group them all within the same setState
:
Instead of:
this.setState({foo: "one"}, () => {
this.setState({bar: "two"});
});
Just do this:
this.setState({
foo: "one",
bar: "two"
});
Instead of opening a folder, try adding a folder by going to "Project" -> "Add Folder to Project..." which opens a Folder choosing dialog. This way the folder won't open in a new window and will be added to your current workspace.
If you then go to "Project" -> "Save Project As..." you can even save your current setup (cells setup, opened files, unsaved changes, etc...), this makes it easy to hotswitch between multiple projects without loosing control and unsaved changes which could be unsafe to be saved right now, but would be a loss if you just ditched them.
(Just be sure to have the "hot_exit"
setting set to true
.)
And Ctrl + Alt + P (Linux and Windows) / Super + Ctrl + P (Mac) lets you switch between the saved projects.
This way you don't have to setup your editor every time you want to work on one of your projects.
Hint: Try http://sublime-text-unofficial-documentation.readthedocs.org/en/sublime-text-2/ which is a wonderful resource for beginners, it teaches you the ropes and shows you the power of your "new" editor, just start with the "Editing" chapter.
convert string to Date fromat (you have to know server timezone)
new Date('2015-06-16 11:00:00'.replace(/\s+/g, 'T').concat('.000+08:00')).getTime()
where +08:00 = timeZone from server
Here's some custom modal code that gives the modal states more explicitly named classes:
$('.modal').on('show.bs.modal', function(e)
{
e.currentTarget.classList.add("modal-fading-in");
e.currentTarget.classList.remove("modal-fading-out");
e.currentTarget.classList.remove("modal-hidden");
e.currentTarget.classList.remove("modal-visible");
});
$('.modal').on('hide.bs.modal', function(e)
{
e.currentTarget.classList.add("modal-fading-out");
e.currentTarget.classList.remove("modal-fading-in");
e.currentTarget.classList.remove("modal-hidden");
e.currentTarget.classList.remove("modal-visible");
});
$('.modal').on('hidden.bs.modal', function(e)
{
e.currentTarget.classList.add("modal-hidden");
e.currentTarget.classList.remove("modal-fading-in");
e.currentTarget.classList.remove("modal-fading-out");
e.currentTarget.classList.remove("modal-visible");
});
$('.modal').on('shown.bs.modal', function(e)
{
e.currentTarget.classList.add("modal-visible");
e.currentTarget.classList.remove("modal-fading-in");
e.currentTarget.classList.remove("modal-fading-out");
e.currentTarget.classList.remove("modal-hidden");
});
You can then easily target the modal's various states with both JS and CSS.
JS example:
if (document.getElementById('myModal').hasClass('modal-fading-in'))
{
console.log("The modal is currently fading in. Please wait.");
}
CSS example:
.modal-fading-out, .modal-hidden
{
opacity: 0.5;
}
Limit words in text:
function limitTextWords($content = false, $limit = false, $stripTags = false, $ellipsis = false)
{
if ($content && $limit) {
$content = ($stripTags ? strip_tags($content) : $content);
$content = explode(' ', $content, $limit+1);
array_pop($content);
if ($ellipsis) {
array_push($content, '...');
}
$content = implode(' ', $content);
}
return $content;
}
Limit chars in text:
function limitTextChars($content = false, $limit = false, $stripTags = false, $ellipsis = false)
{
if ($content && $limit) {
$content = ($stripTags ? strip_tags($content) : $content);
$ellipsis = ($ellipsis ? "..." : $ellipsis);
$content = mb_strimwidth($content, 0, $limit, $ellipsis);
}
return $content;
}
Use:
$text = "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.";
echo limitTextWords($text, 5, true, true);
echo limitTextChars($text, 5, true, true);
There are a few points to consider.
A \u2018 character may appear only as a fragment of representation of a unicode string in Python, e.g. if you write:
>>> text = u'‘'
>>> print repr(text)
u'\u2018'
Now if you simply want to print the unicode string prettily, just use unicode's encode
method:
>>> text = u'I don\u2018t like this'
>>> print text.encode('utf-8')
I don‘t like this
To make sure that every line from any file would be read as unicode, you'd better use the codecs.open
function instead of just open
, which allows you to specify file's encoding:
>>> import codecs
>>> f1 = codecs.open(file1, "r", "utf-8")
>>> text = f1.read()
>>> print type(text)
<type 'unicode'>
>>> print text.encode('utf-8')
I don‘t like this
you could use something like
<select ng-model="myselect">
<option ng-repeat="o in options" ng-selected="{{o==myselect}}" value="{{o}}">
{{o}}
</option>
</select>
using ng-selected you preselect the option in case myselect was prefilled.
I prefer this method over ng-options anyway, as ng-options only works with arrays. ng-repeat also works with json-like objects.
The package setuptools/distribute is listed in requirements.txt. Please remove the same.
There is a system function called ISNUMERIC for SQL 2008 and up. An example:
SELECT myCol
FROM mTable
WHERE ISNUMERIC(myCol)<> 1;
I did a couple of quick tests and also looked further into the docs:
ISNUMERIC returns 1 when the input expression evaluates to a valid numeric data type; otherwise it returns 0.
Which means it is fairly predictable for example
-9879210433
would pass but 987921-0433
does not.
$9879210433
would pass but 9879210$433
does not.
So using this information you can weed out based on the list of valid currency symbols and +
& -
characters.
You're probably not accessing it correctly. You can output it directly or cast it as a string. (in this example, the casting is superfluous, as echo automatically does it anyway)
$content = simplexml_load_string(
'<content><![CDATA[Hello, world!]]></content>'
);
echo (string) $content;
// or with parent element:
$foo = simplexml_load_string(
'<foo><content><![CDATA[Hello, world!]]></content></foo>'
);
echo (string) $foo->content;
You might have better luck with LIBXML_NOCDATA
:
$content = simplexml_load_string(
'<content><![CDATA[Hello, world!]]></content>'
, null
, LIBXML_NOCDATA
);
interface in the Java programming language is an abstract type that is used to specify a behavior that classes must implement. They are similar to protocols. Interfaces are declared using the interface keyword
@interface is used to create your own (custom) Java annotations. Annotations are defined in their own file, just like a Java class or interface. Here is custom Java annotation example:
@interface MyAnnotation {
String value();
String name();
int age();
String[] newNames();
}
This example defines an annotation called MyAnnotation which has four elements. Notice the @interface keyword. This signals to the Java compiler that this is a Java annotation definition.
Notice that each element is defined similarly to a method definition in an interface. It has a data type and a name. You can use all primitive data types as element data types. You can also use arrays as data type. You cannot use complex objects as data type.
To use the above annotation, you could use code like this:
@MyAnnotation(
value="123",
name="Jakob",
age=37,
newNames={"Jenkov", "Peterson"}
)
public class MyClass {
}
Reference - http://tutorials.jenkov.com/java/annotations.html
I display images in windows forms when I put it in Load event like this:
private void Form1_Load( object sender , EventArgs e )
{
pictureBox1.ImageLocation = "./image.png"; //path to image
pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
}
as @Pointy said you don't cache images with javascript, the browser does that. so this may be what you are asking for and may not be... but you can preload images using javascript. By putting all of the images you want to preload into an array and putting all of the images in that array into hidden img elements, you effectively preload (or cache) the images.
var images = [
'/path/to/image1.png',
'/path/to/image2.png'
];
$(images).each(function() {
var image = $('<img />').attr('src', this);
});
If it's acceptible to simply publish your modules preinstalled in node_modules alongside your other files, you can do it like this:
// ./node_modules/foo/package.json
{
"name":"foo",
"version":"0.0.1",
"main":"index.js"
}
// ./package.json
...
"dependencies": {
"foo":"0.0.1",
"bar":"*"
}
// ./app.js
var foo = require('foo');
You may also want to store your module on git and tell your parent package.json to install the dependency from git: https://npmjs.org/doc/json.html#Git-URLs-as-Dependencies
Finally, i solved the problem by using following way, in which the position of the spinner can be get by its string
private int getPostiton(String locationid,Cursor cursor)
{
int i;
cursor.moveToFirst();
for(i=0;i< cursor.getCount()-1;i++)
{
String locationVal = cursor.getString(cursor.getColumnIndex(RoadMoveDataBase.LT_LOCATION));
if(locationVal.equals(locationid))
{
position = i+1;
break;
}
else
{
position = 0;
}
cursor.moveToNext();
}
Calling the method
Spinner location2 = (Spinner)findViewById(R.id.spinner1);
int location2id = getPostiton(cursor.getString(3),cursor);
location2.setSelection(location2id);
I hope it will help for some one..
Editor warning: This solution is computationally inefficient and may bring down your connection for a large table.
NB - You need to do this first on a test copy of your table!
When I did it, I found that unless I also included AND n1.id <> n2.id
, it deleted every row in the table.
If you want to keep the row with the lowest id
value:
DELETE n1 FROM names n1, names n2 WHERE n1.id > n2.id AND n1.name = n2.name
If you want to keep the row with the highest id
value:
DELETE n1 FROM names n1, names n2 WHERE n1.id < n2.id AND n1.name = n2.name
I used this method in MySQL 5.1
Not sure about other versions.
Update: Since people Googling for removing duplicates end up here
Although the OP's question is about DELETE
, please be advised that using INSERT
and DISTINCT
is much faster. For a database with 8 million rows, the below query took 13 minutes, while using DELETE
, it took more than 2 hours and yet didn't complete.
INSERT INTO tempTableName(cellId,attributeId,entityRowId,value)
SELECT DISTINCT cellId,attributeId,entityRowId,value
FROM tableName;
This really isn't too hard to implement with ModelForms. So lets say you have Forms A, B, and C. You print out each of the forms and the page and now you need to handle the POST.
if request.POST():
a_valid = formA.is_valid()
b_valid = formB.is_valid()
c_valid = formC.is_valid()
# we do this since 'and' short circuits and we want to check to whole page for form errors
if a_valid and b_valid and c_valid:
a = formA.save()
b = formB.save(commit=False)
c = formC.save(commit=False)
b.foreignkeytoA = a
b.save()
c.foreignkeytoB = b
c.save()
Here are the docs for custom validation.
The way I usually explain this to people is to show how it's similar to other JavaScript patterns.
First, you should know that there are two ways to declare a function (actually, there's at least five, but these are the two main culprits):
function foo() {/*code*/}
and
var foo = function() {/*code*/};
Even if this construction looks strange, you probably use it all the time when attaching events:
window.onload=function(){/*code*/};
You should notice that the second form is not much different from a regular variable declaration:
var bar = 5;
var baz = 'some string';
var foo = function() {/*code*/};
But in JavaScript, you always have the choice between using a value directly or through a variable. If bar
is 5
, then the next two statements are equivalent:
var myVal = bar * 100; // use 'bar'
var myVal = 5 * 100; // don't use 'bar'
Well, if you can use 5
on its own, why can't you use function() {\*code*\}
on its own too? In fact, you can. And that's called an anonymous function. So these two examples are equivalent as well:
var foo = function() {/*code*/}; // use 'foo'
foo();
(function(){/*code*/})(); // don't use 'foo'
The only difference you should see is in the extra brackets. That's simply because if you start a line with the keyword function
, the parser will think you are declaring a function using the very first pattern at the top of this answer and throw a syntax error exception. So wrap your entire anonymous function inside a pair of braces and the problem goes away.
In other words, the following three statements are valid:
5; // pointless and stupid
'some string'; // pointless and stupid
(function(){/*code*/})(); // wonderfully powerful
[EDIT in 2020]
The previous version of my answer recommended Douglas Crockford's form of parens-wrapping for these "immediately invoked anonymous functions". User @RayLoveless recommended in 2012 to use the version shown now. Back then, before ES6 and arrow functions, there was no obvious idiomatic difference; you simply had to prevent the statement starting with the function
keyword. In fact, there were lots of ways to do that. But using parens, these two statements were syntactically and idiomatically equivalent:
( function() { /* code */}() );
( function() { /* code */} )();
But user @zentechinc's comment below reminds me that arrow functions change all this. So now only one of these statements is correct.
( () => { /* code */ }() ); // Syntax error
( () => { /* code */ } )();
Why on earth does this matter? Actually, it's pretty easy to demonstrate. Remember an arrow function can come in two basic forms:
() => { return 5; }; // With a function body
() => { console.log(5); };
() => 5; // Or with a single expression
() => console.log(5);
Without parens wrapping this second type of arrow function, you end up with an idiomatic mess:
() => 5(); // How do you invoke a 5?
() => console.log(5)(); // console.log does not return a function!
You can use jQuery's Deferred object along with the when method.
deferredArray = [];
forloop {
deferred = new $.Deferred();
ajaxCall(function() {
deferred.resolve();
}
deferredArray.push(deferred);
}
$.when(deferredArray, function() {
//this code is called after all the ajax calls are done
});
Use document.title
:
console.log(document.title)
_x000D_
<title>Title test</title>
_x000D_
Two suggestions:
std::deque
instead of std::vector
for better performance in your specific case and use the method std::deque::pop_front()
.&
in std::vector<ScanRule>& topPriorityRules;
IF()
in MySQL is a ternary function, not a control structure -- if the condition in the first argument is true, it returns the second argument; otherwise, it returns the third argument. There is no corresponding ELSEIF()
function or END IF
keyword.
The closest equivalent to what you've got would be something like:
IF(qty_1<='23', price,
IF('23'>qty_1 && qty_2<='23', price_2,
IF('23'>qty_2 && qty_3<='23', price_3,
IF('23'>qty_3, price_4, 1)
)
)
)
The conditions don't all make sense to me (it looks as though some of them may be inadvertently reversed?), but without knowing what exactly you're trying to accomplish, it's hard for me to fix that.
The model has a save
method, which saves all the details necessary to reconstitute the model. An example from the keras documentation:
from keras.models import load_model
model.save('my_model.h5') # creates a HDF5 file 'my_model.h5'
del model # deletes the existing model
# returns a compiled model
# identical to the previous one
model = load_model('my_model.h5')
this works for me
new_df = df[df.loc[:]!=0].dropna()
Faster than the above solutions, including the highest rated one:
(x < 0) ? -1 : (x > 0)
Simply use this in your WHERE
clause.
The "SubmitDate" portion below is the column name, so insert your own.
This will return only the "Year" portion of the results, omitting the mins etc.
Where datepart(year, SubmitDate) = '2017'
You can also use Aragon Package Manager if you prefer a decentralized approach:
Compare date only instead of date + time (NOW) with:
CURDATE()
You could use a closure. Just modify your code like this:
google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){
return function() {
infowindow.setContent(content);
infowindow.open(map,marker);
};
})(marker,content,infowindow));
Here is the DEMO
I use this for Automatic column hiding as per column data, in that case, sometimes its break table structure. i solve that problem with this $($.fn.dataTable.tables(true)).DataTable().columns.adjust(); and this function $('#datatableId').on('draw.dt', function () { }); call after tabledata load.
$('#datatableId').on('draw.dt', function () {
$($.fn.dataTable.tables(true)).DataTable().columns.adjust();
})
A roll your own function.
Supports recursion or not with the 2nd
switch.
Also, allow names of files with ;
which the accepted answer fails to address although a great answer, this will get over that issue.
The idea was taken from https://ss64.com/nt/empty.html
Notes within code.
@echo off
title %~nx0
setlocal EnableDelayedExpansion
set dir=C:\Users\%username%\Desktop
title Echos folders and files in root directory...
call :FOLDER_FILE_CNT dir TRUE
echo !dir!
echo/ & pause & cls
::
:: FOLDER_FILE_CNT function by Ste
::
:: First Written: 2020.01.26
:: Posted on the thread here: https://stackoverflow.com/q/10813943/8262102
:: Based on: https://ss64.com/nt/empty.html
::
:: Notes are that !%~1! will expand to the returned variable.
:: Syntax call: call :FOLDER_FILE_CNT "<path>" <BOOLEAN>
:: "<path>" = Your path wrapped in quotes.
:: <BOOLEAN> = Count files in sub directories (TRUE) or not (FALSE).
:: Returns a variable with a value of:
:: FALSE = if directory doesn't exist.
:: 0-inf = if there are files within the directory.
::
:FOLDER_FILE_CNT
if "%~1"=="" (
echo Use this syntax: & echo call :FOLDER_FILE_CNT "<path>" ^<BOOLEAN^> & echo/ & goto :eof
) else if not "%~1"=="" (
set count=0 & set msg= & set dirExists=
if not exist "!%~1!" (set msg=FALSE)
if exist "!%~1!" (
if {%~2}=={TRUE} (
>nul 2>nul dir /a-d /s "!%~1!\*" && (for /f "delims=;" %%A in ('dir "!%~1!" /a-d /b /s') do (set /a count+=1)) || (set /a count+=0)
set msg=!count!
)
if {%~2}=={FALSE} (
for /f "delims=;" %%A in ('dir "!%~1!" /a-d /b') do (set /a count+=1)
set msg=!count!
)
)
)
set "%~1=!msg!" & goto :eof
)
The use of http.createClient
is now deprecated. You can pass Headers in options collection as below.
var options = {
hostname: 'example.com',
path: '/somePath.php',
method: 'GET',
headers: {'Cookie': 'myCookie=myvalue'}
};
var results = '';
var req = http.request(options, function(res) {
res.on('data', function (chunk) {
results = results + chunk;
//TODO
});
res.on('end', function () {
//TODO
});
});
req.on('error', function(e) {
//TODO
});
req.end();
The official documentation of Dockerfile best practices does a great job explaining the differences. Dockerfile best practices
CMD:
The CMD instruction should be used to run the software contained by your image, along with any arguments. CMD should almost always be used in the form of CMD ["executable", "param1", "param2"…]
. Thus, if the image is for a service, such as Apache and Rails, you would run something like CMD ["apache2","-DFOREGROUND"]
. Indeed, this form of the instruction is recommended for any service-based image.
ENTRYPOINT:
The best use for ENTRYPOINT is to set the image’s main command, allowing that image to be run as though it was that command (and then use CMD as the default flags).
std::string::iterator end_pos = std::remove(str.begin(), str.end(), ' ');
str.erase(end_pos, str.end());
If you're using VSCode:
1.
cmd + ,
)jshint.options
into the search bar"esversion": 6
to the options object.2.
Or simply add this to your user settings:
"jshint.options": {
"esversion": 6
}
[UPDATE] new vscode settings
cmd + ,
)jshint
into search2.
content
doesn't support HTML, only text. You should probably use javascript, jQuery or something like that.
Another problem with your code is "
inside a "
block. You should mix '
and "
(class='headingDetail'
).
If content
did support HTML you could end up in an infinite loop where content
is added inside content
.
Update energydata set energydata.kWh = temp.kWh
where energydata.webmeterID = (select webmeterID from temp_energydata as temp)
Max. capacity is 2 gigabytes of space - so you're looking at just over 1 billion 2-byte characters that will fit into a NVARCHAR(MAX)
field.
Using the other answer's more detailed numbers, you should be able to store
(2 ^ 31 - 1 - 2) / 2 = 1'073'741'822 double-byte characters
1 billion, 73 million, 741 thousand and 822 characters to be precise
in your NVARCHAR(MAX)
column (unfortunately, that last half character is wasted...)
Update: as @MartinMulder pointed out: any variable length character column also has a 2 byte overhead for storing the actual length - so I needed to subtract two more bytes from the 2 ^ 31 - 1
length I had previously stipulated - thus you can store 1 Unicode character less than I had claimed before.
If it could help other, I've also face this error. The problem was cause by on incorrect reference in me web site. For unknown reason my web site was referring another web site, in the same solution. And once I remove that bad reference, thing began to work properly.
Because there are more than one way to skin a cat, here's my approach:
Code:
#!/usr/bin/env lua
local content = [=[
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat.
]=]
local function split(str, sep)
local result = {}
local regex = ("([^%s]+)"):format(sep)
for each in str:gmatch(regex) do
table.insert(result, each)
end
return result
end
local lines = split(content, "\n")
for _,line in ipairs(lines) do
print(line)
end
Output:
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat.
Explanation:
The gmatch
function works as an iterator, it fetches all the strings that match regex
. The regex
takes all characters until it finds a separator.
If you're searching for hits within a larger text, you don't want to use ^
and $
as some other responders have said; those match the beginning and end of the text. Try this instead:
\bdbo\.\w+_fn\b
\b
is a word boundary: it matches a position that is either preceded by a word character and not followed by one, or followed by a word character and not preceded by one. This regex will find what you're looking for in any of these strings:
dbo.functionName_fn
foo dbo.functionName_fn bar
(dbo.functionName_fn)
...but not in this one:
foodbo.functionName_fnbar
\w+
matches one or more "word characters" (letters, digits, or _
). If you need something more inclusive, you can try \S+
(one or more non-whitespace characters) or .+?
(one or more of any characters except linefeeds, non-greedily). The non-greedy +?
prevents it from accidentally matching something like dbo.func1_fn dbo.func2_fn
as if it were just one hit.
You are may be on the wrong owl's doc version.
autoPlay is for 1st version
autoplay is for 2nd version
SELECT
B.Title, B.Edition, B.Year, B.Pages, B.Rating --from Books
, C.Category --from Categories
, P.Publisher --from Publishers
, W.LastName --from Writers
FROM Books B
JOIN Categories_Books CB ON B._ISBN = CB._Books_ISBN
JOIN Categories_Books CB ON CB.__Categories_Category_ID = C._CategoryID
JOIN Publishers P ON B.PublisherID = P._Publisherid
JOIN Writers_Books WB ON B._ISBN = WB._Books_ISBN
JOIN Writers W ON WB._Writers_WriterID = W._WriterID
Just to enrich the discussion, if you want to move myBranch
branch to your current commit, just omit the second argument after -f
Example:
git branch -f myBranch
I generally do this when I rebase
while in a Detached HEAD state :)
You might want to start with scapy.
Yes:
RelativeLayout.LayoutParams params= new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.BELOW, R.id.below_id);
viewToLayout.setLayoutParams(params);
First, the code creates a new layout params by specifying the height and width. The addRule
method adds the equivalent of the xml properly android:layout_below
. Then you just call View#setLayoutParams
on the view you want to have those params.
You should first pull
the changes from the develop
branch and only then merge them to your branch:
git checkout develop
git pull
git checkout branch-x
git rebase develop
Or, when on branch-x
:
git fetch && git rebase origin/develop
I have an alias that saves me a lot of time. Add to your ~/.gitconfig
:
[alias]
fr = "!f() { git fetch && git rebase origin/"$1"; }; f"
Now, all that you have to do is:
git fr develop
Do the following two steps. I hope, it will solve the "404 not found" issue in tomcat server during the development of java servlet application.
Step 1: Right click on the server(in the server explorer tab)->Properties->Switch Location from workspace metadata to tomcat server
Step 2: Double Click on the server(in the server explorer tab)->Select Use tomcat installation option inside server location menu
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {_x000D_
var target = $(e.target).attr("href") // activated tab_x000D_
alert(target);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<ul id="myTab" class="nav nav-tabs">_x000D_
<li class="active"><a href="#home" data-toggle="tab">Home</a></li>_x000D_
<li class=""><a href="#profile" data-toggle="tab">Profile</a></li>_x000D_
</ul>_x000D_
<div id="myTabContent" class="tab-content">_x000D_
<div class="tab-pane fade active in" id="home">_x000D_
home tab!_x000D_
</div>_x000D_
<div class="tab-pane fade" id="profile">_x000D_
profile tab!_x000D_
</div>_x000D_
</div>
_x000D_
Creating a virtual environment for Jupyter Notebooks
A minimal Python install is
sudo apt install python3.7 python3.7-venv python3.7-minimal python3.7-distutils python3.7-dev python3.7-gdbm python3-gdbm-dbg python3-pip
Then you can create and use the environment
/usr/bin/python3.7 -m venv test
cd test
source test/bin/activate
pip install jupyter matplotlib seaborn numpy pandas scipy
# install other packages you need with pip/apt
jupyter notebook
deactivate
You can make a kernel for Jupyter with
ipython3 kernel install --user --name=test
It's programmer preference. Personally, I love using this
since it explicitly marks the object members. Of course the _
does the same thing (only when you follow the convention)
Steps to fix:
Run flutter clean
in terminal.
Run your app again.
Short answer is: No, it's not possible to prevent CSS inheritance. You can only override the styles that are set on the parents. See the spec:
Every element in an HTML document will inherit all inheritable properties from its parent except the root element (
html
), which doesn’t have a parent. -W3C
Apart from overriding every single inherited property. You can also use initial
keyword, e.g. color: initial;
. It also can be used together with all
, e.g. all: initial;
, that will reset all properties at once. Example:
.container {_x000D_
color: blue;_x000D_
font-style: italic;_x000D_
}_x000D_
.initial {_x000D_
all: initial;_x000D_
}
_x000D_
<div class="container">_x000D_
The quick brown <span class="initial">fox</span> jumps over the lazy dog_x000D_
</div>
_x000D_
Browser support tables according to Can I use...
all
(Currently no support in both IE and Edge, others are good)initial
(Currently no support in IE, others are good)You may find it useful by using direct children selector >
in some cases. Example:
.list > li {_x000D_
border: 1px solid red;_x000D_
color: blue;_x000D_
}
_x000D_
<ul class="list">_x000D_
<li>_x000D_
<span>HEADING 1</span>_x000D_
<ul>_x000D_
<li>sub-heading A</li>_x000D_
<li>sub-heading B</li>_x000D_
</ul>_x000D_
</li>_x000D_
<li>_x000D_
<span>HEADING 2</span>_x000D_
<ul>_x000D_
<li>sub-heading A</li>_x000D_
<li>sub-heading B</li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>
_x000D_
The border style has been applied only to the direct children <li>
s, as border
is an non-inherited property. But text color has been applied to all the children, as color
is an inherited property.
Therefore, >
selector would be only useful with non-inherited properties, when it comes to preventing inheritance.
Josh Lee's answer works, but you can use the "&&" operator for better readability like this:
echo "You have provided the following arguments $arg1 $arg2 $arg3"
if [ "$arg1" = "$arg2" ] && [ "$arg1" != "$arg3" ]
then
echo "Two of the provided args are equal."
exit 3
elif [ $arg1 = $arg2 ] && [ $arg1 = $arg3 ]
then
echo "All of the specified args are equal"
exit 0
else
echo "All of the specified args are different"
exit 4
fi
First, have to check
SELECT * FROM university
WHERE course_name LIKE '%&%'
Next, have to update
UPDATE university SET course_name = REPLACE(course_name, '&', '&') WHERE id = 1
Results: Engineering & Technology => Engineering & Technology
Is there a function in the .net Math library?
No.
It's not hard to write your own though. The naive algorithm sorts the array and picks the middle (or the average of the two middle) elements. However, this algorithm is O(n log n)
while its possible to solve this problem in O(n)
time. You want to look at selection algorithms to get such an algorithm.
Define what GetData is. At the moment it is not defined.
Function getData(currentWorksheet as Worksheet, dataStartRow as Integer, dataEndRow as Integer, DataStartCol as Integer, dataEndCol as Integer) as variant
You can use command prompt to open explorer with path.
here example with batch or command prompt:
start "" explorer.exe (path)
so In VBA ms.access you can write with:
Dim Path
Path="C:\Example"
shell "cmd /c start """" explorer.exe " & Path ,vbHide
This code might work:
//if the directory exists
DWORD dwAttr = GetFileAttributes(str);
if(dwAttr != 0xffffffff && (dwAttr & FILE_ATTRIBUTE_DIRECTORY))
If you have mysqladmin
available, you may get the list of queries with:
> mysqladmin -uUSERNAME -pPASSWORD pr
+-----+------+-----------------+--------+---------+------+--------------+------------------+
| Id | User | Host | db | Command | Time | State | Info |
+-----+------+-----------------+--------+---------+------+--------------+------------------+
| 137 | beet | localhost:53535 | people | Query | 292 | Sending data | DELETE FROM |
| 145 | root | localhost:55745 | | Query | 0 | | show processlist |
+-----+------+-----------------+--------+---------+------+--------------+------------------+
Then you may stop the mysql process that is hosting the long running query:
> mysqladmin -uUSERNAME -pPASSWORD kill 137
For java 7 and up:
Path path = Paths.get("/your/path/string");
Files.createDirectories(path);
It seems unnecessary to check for existence of the dir or file before creating, from createDirectories javadocs:
Creates a directory by creating all nonexistent parent directories first. Unlike the createDirectory method, an exception is not thrown if the directory could not be created because it already exists. The attrs parameter is optional file-attributes to set atomically when creating the nonexistent directories. Each file attribute is identified by its name. If more than one attribute of the same name is included in the array then all but the last occurrence is ignored.
If this method fails, then it may do so after creating some, but not all, of the parent directories.
Here is example given which so how to use open
and "python close
from sys import argv
script,filename=argv
txt=open(filename)
print "filename %r" %(filename)
print txt.read()
txt.close()
print "Change the file name"
file_again=raw_input('>')
print "New file name %r" %(file_again)
txt_again=open(file_again)
print txt_again.read()
txt_again.close()
It's necessary to how many times you opened file have to close that times.
Take a look at the Group by function.
What the group by function does is pretuty much grouping the similar value for a given field. You can then show the number of number of time that this value was groupped using the COUNT function.
You can also use the group by function with a good number of other function define by MySQL (see the above link).
mysql> SELECT student_name, AVG(test_score)
-> FROM student
-> GROUP BY student_name;
Instead of just doing this quoted method from https://stackoverflow.com/a/4635440/3787376,
You can do something like this:
// show loading image $('#loader_img').show(); // main image loaded ? $('#main_img').on('load', function(){ // hide/remove the loading image $('#loader_img').hide(); });
You assign
load
event to the image which fires when image has finished loading. Before that, you can show your loader image.
you can use a different jQuery function to make the loading image fade away, then be hidden:
// Show the loading image.
$('#loader_img').show();
// When main image loads:
$('#main_img').on('load', function(){
// Fade out and hide the loading image.
$('#loader_img').fadeOut(100); // Time in milliseconds.
});
"Once the opacity reaches 0, the display style property is set to none." http://api.jquery.com/fadeOut/
Or you could not use the jQuery library because there are already simple cross-browser JavaScript methods.
Same thing happened with me, when i have enabled 2-way authentication for github. Things i did to resolve:
Doing this will solve your issue.
I feel like the main answer is still not so clear, and it's worth taking the time to understand time and timezones.
The most important thing to understand when dealing with time is that time is relative!
2017-08-30 13:23:00
: (a naive datetime), represents a local time somewhere in the world, but note that 2017-08-30 13:23:00
in London is NOT THE SAME TIME as 2017-08-30 13:23:00
in San Francisco.Because the same time string can be interpreted as different points-in-time depending on where you are in the world, there is a need for an absolute notion of time.
A UTC timestamp is a number in seconds (or milliseconds) from Epoch (defined as 1 January 1970 00:00:00
at GMT
timezone +00:00 offset).
Epoch is anchored on the GMT timezone and therefore is an absolute point in time. A UTC timestamp being an offset from an absolute time therefore defines an absolute point in time.
This makes it possible to order events in time.
Without timezone information, time is relative, and cannot be converted to an absolute notion of time without providing some indication of what timezone the naive datetime should be anchored to.
What are the types of time used in computer system?
naive datetime: usually for display, in local time (i.e. in the browser) where the OS can provide timezone information to the program.
UTC timestamps: A UTC timestamp is an absolute point in time, as mentioned above, but it is anchored in a given timezone, so a UTC timestamp can be converted to a datetime in any timezone, however it does not contain timezone information. What does that mean? That means that 1504119325 corresponds to 2017-08-30T18:55:24Z
, or 2017-08-30T17:55:24-0100
or also 2017-08-30T10:55:24-0800
. It doesn't tell you where the datetime recorded is from. It's usually used on the server side to record events (logs, etc...) or used to convert a timezone aware datetime to an absolute point in time and compute time differences.
ISO-8601 datetime string: The ISO-8601 is a standardized format to record datetime with timezone. (It's in fact several formats, read on here: https://en.wikipedia.org/wiki/ISO_8601) It is used to communicate timezone aware datetime information in a serializable manner between systems.
When to use which? or rather when do you need to care about timezones?
If you need in any way to care about time-of-day, you need timezone information. A calendar or alarm needs time-of-day to set a meeting at the correct time of the day for any user in the world. If this data is saved on a server, the server needs to know what timezone the datetime corresponds to.
To compute time differences between events coming from different places in the world, UTC timestamp is enough, but you lose the ability to analyze at what time of day events occured (ie. for web analytics, you may want to know when users come to your site in their local time: do you see more users in the morning or the evening? You can't figure that out without time of day information.
Timezone offset in a date string:
Another point that is important, is that timezone offset in a date string is not fixed. That means that because 2017-08-30T10:55:24-0800
says the offset -0800
or 8 hours back, doesn't mean that it will always be!
In the summer it may well be in daylight saving time, and it would be -0700
What that means is that timezone offset (+0100) is not the same as timezone name (Europe/France) or even timezone designation (CET)
America/Los_Angeles
timezone is a place in the world, but it turns into PST
(Pacific Standard Time) timezone offset notation in the winter, and PDT
(Pacific Daylight Time) in the summer.
So, on top of getting the timezone offset from the datestring, you should also get the timezone name to be accurate.
Most packages will be able to convert numeric offsets from daylight saving time to standard time on their own, but that is not necessarily trivial with just offset. For example WAT
timezone designation in West Africa, is UTC+0100 just like CET
timezone in France, but France observes daylight saving time, while West Africa does not (because they're close to the equator)
So, in short, it's complicated. VERY complicated, and that's why you should not do this yourself, but trust a package that does it for you, and KEEP IT UP TO DATE!
I solve it by download the reportviewer.exe and install it. After the installation, all related assemblies will be available in C:\Windows\assembly\GAC_MSIL, then you can refer it in web config
Minimal runnable example
Main.java
public class Main {
public native int square(int i);
public static void main(String[] args) {
System.loadLibrary("Main");
System.out.println(new Main().square(2));
}
}
Main.c
#include <jni.h>
#include "Main.h"
JNIEXPORT jint JNICALL Java_Main_square(
JNIEnv *env, jobject obj, jint i) {
return i * i;
}
Compile and run:
sudo apt-get install build-essential openjdk-7-jdk
export JAVA_HOME='/usr/lib/jvm/java-7-openjdk-amd64'
javac Main.java
javah -jni Main
gcc -shared -fpic -o libMain.so -I${JAVA_HOME}/include \
-I${JAVA_HOME}/include/linux Main.c
java -Djava.library.path=. Main
Output:
4
Tested on Ubuntu 14.04 AMD64. Also worked with Oracle JDK 1.8.0_45.
Example on GitHub for you to play with.
Underscores in Java package / file names must be escaped with _1
in the C function name as mentioned at: Invoking JNI functions in Android package name containing underscore
Interpretation
native
allows you to:
This could be used to:
with the tradeoff of lower portability.
It is also possible for you to call Java from C, but you must first create a JVM in C: How to call Java functions from C++?
Analogous native extension APIs are also present in many other "VM languages" for the same reasons, e.g. Python, Node.js, Ruby.
Android NDK
The concept is exact the same in this context, except that you have to use Android boilerplate to set it up.
The official NDK repository contains "canonical" examples such as the hello-jni app:
In you unzip
an .apk
with NDK on Android O, you can see the pre-compiled .so
that corresponds to the native code under lib/arm64-v8a/libnative-lib.so
.
TODO confirm: furthermore, file /data/app/com.android.appname-*/oat/arm64/base.odex
, says it is a shared library, which I think is the AOT precompiled .dex corresponding to the Java files in ART, see also: What are ODEX files in Android? So maybe the Java is actually also run via a native
interface?
Example in the OpenJDK 8
Let's find find where Object#clone
is defined in jdk8u60-b27.
We will conclude that it is implemented with a native
call.
First we find:
find . -name Object.java
which leads us to jdk/src/share/classes/java/lang/Object.java#l212:
protected native Object clone() throws CloneNotSupportedException;
Now comes the hard part, finding where clone is amidst all the indirection. The query that helped me was:
find . -iname object.c
which would find either C or C++ files that might implement Object's native methods. It leads us to jdk/share/native/java/lang/Object.c#l47:
static JNINativeMethod methods[] = {
...
{"clone", "()Ljava/lang/Object;", (void *)&JVM_Clone},
};
JNIEXPORT void JNICALL
Java_java_lang_Object_registerNatives(JNIEnv *env, jclass cls)
{
(*env)->RegisterNatives(env, cls,
methods, sizeof(methods)/sizeof(methods[0]));
}
which leads us to the JVM_Clone
symbol:
grep -R JVM_Clone
which leads us to hotspot/src/share/vm/prims/jvm.cpp#l580:
JVM_ENTRY(jobject, JVM_Clone(JNIEnv* env, jobject handle))
JVMWrapper("JVM_Clone");
After expanding a bunch of macros, we come to the conclusion that this is the definition point.
As I never had a paid app in my google account I don't think its related to credit cards nor to cache clear in google services.
the trick that worked for me :
I did notice a 2-3 hours idle will also fix it by itself.
Check the Variables section in the Go template docs. A range may declare two variables, separated by a comma. The following should work:
{{ range $key, $value := . }}
<li><strong>{{ $key }}</strong>: {{ $value }}</li>
{{ end }}
If you could use MariaDB there is a very very easy solution.
Since MariaDB-10.02 there has been added a new storage engine called CONNECT that can help us to convert the results of another query or table into a pivot table, just like what you want: You can have a look at the docs.
First of all install the connect storage engine.
Now the pivot column of our table is itemname
and the data for each item is located in itemvalue
column, so we can have the result pivot table using this query:
create table pivot_table
engine=connect table_type=pivot tabname=history
option_list='PivotCol=itemname,FncCol=itemvalue';
Now we can select what we want from the pivot_table
:
select * from pivot_table
This might prove useful:
a,b=map(int,raw_input().split())
You can then use 'a' and 'b' separately.
"C:\Program Files\PuTTY\pscp.exe" -scp file.py server.com:
file.py
will be uploaded into your HOME
dir on remote server.
or when the remote server has a different user, use "C:\Program Files\PuTTY\pscp.exe" -l username -scp file.py server.com:
After connecting to the server pscp will ask for a password.
The problem is in the Eclipse Maven support, the related question is here.
Under Eclipse, the java.home
variable is set to the JRE that was used to start Eclipse, not the build JRE. The default system JRE from C:\Program Files
doesn't include the JDK so tools.jar
is not being found.
To fix the issue you need to start Eclipse using the JRE from the JDK by adding something like this to eclipse.ini
(before -vmargs
!):
-vm
C:/<your_path_to_jdk170>/jre/bin/server/jvm.dll
Then refresh the Maven dependencies (Alt-F5) (Just refreshing the project isn't sufficient).
I think the largely correct way, is to set css to this:
html
{
overflow: hidden;
}
body
{
margin: 0;
box-sizing: border-box;
}
html, body
{
height: 100%;
}
Über
is the German word for above
or over
(it's actually cognate with the English over
).
Hence, in this context, an uber-jar is an "over-jar", one level up from a simple JAR (a), defined as one that contains both your package and all its dependencies in one single JAR file. The name can be thought to come from the same stable as ultrageek, superman, hyperspace, and metadata, which all have similar meanings of "beyond the normal".
The advantage is that you can distribute your uber-jar and not care at all whether or not dependencies are installed at the destination, as your uber-jar actually has no dependencies.
All the dependencies of your own stuff within the uber-jar are also within that uber-jar. As are all dependencies of those dependencies. And so on.
(a) I probably shouldn't have to explain what a JAR is to a Java developer but I'll include it for completeness. It's a Java archive, basically a single file that typically contains a number of Java class files along with associated metadata and resources.
An alternative to Apache Commons: Use Spring's HtmlUtils.htmlEscape(String input)
method.
RaYell,
You don't need to parse the value returned. document.getElementById("FileUpload1").value
returns only the file name with extension.
This was useful for me because I wanted to copy the name of the file to be uploaded to an input box called 'title'. In my application, the uploaded file is renamed to the index generated by the backend database and the title is stored in the database.
Just for the next guy searching for a micropython solution, this works purely based on os (listdir, remove, rmdir). It is neither complete (especially in errorhandling) nor fancy, it will however work in most circumstances.
def deltree(target):
print("deltree", target)
for d in os.listdir(target):
try:
deltree(target + '/' + d)
except OSError:
os.remove(target + '/' + d)
os.rmdir(target)
Use an ID to uniquely identify the checkbox. Your current example is trying to select the checkbox with an id of '#chk0':
<input type="checkbox" id="chk0" name="chk0" value="true" disabled>
$('#chk0').attr("disabled", "disabled");
You'll also need to remove the attribute for disabled
to enable the checkbox. Something like:
$('#chk0').removeAttr("disabled");
See the docs for removeAttr
The value XHTML for disabling/enabling an input element is as follows:
<input type="checkbox" id="chk0" name="chk0" value="true" disabled="disabled" />
<input type="checkbox" id="chk0" name="chk0" value="true" />
Note that it's the absence of the disabled attribute that makes the input element enabled.
Using Promise
and checking if the body
object is a valid JSON. If not a Promise reject
will be returned.
var DoPost = function(url, body) {
try {
body = JSON.stringify(body);
} catch (error) {
return reject(error);
}
return new Promise((resolve, reject) => {
$.ajax({
type: 'POST',
url: url,
data: body,
contentType: "application/json",
dataType: 'json'
})
.done(function(data) {
return resolve(data);
})
.fail(function(error) {
console.error(error);
return reject(error);
})
.always(function() {
// called after done or fail
});
});
}
Based on (dangerouslySetInnerHTML).
It's a prop that does exactly what you want. However they name it to convey that it should be use with caution
For someone looking to solve same by using maven. Add below dependency in POM:
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>7.0.0.jre8</version>
</dependency>
And use below code for connection:
String connectionUrl = "jdbc:sqlserver://localhost:1433;databaseName=master;user=sa;password=your_password";
try {
System.out.print("Connecting to SQL Server ... ");
try (Connection connection = DriverManager.getConnection(connectionUrl)) {
System.out.println("Done.");
}
} catch (Exception e) {
System.out.println();
e.printStackTrace();
}
Look for this link for other CRUD type of queries.
I had a similar issue. The Maven projects have different structure than "Dynamic Web Projects". Eclipse knows only how to deploy the Dynamic Web Projects (project structure used by Web Tools Platform).
In order to solve this and tell Eclipse how to deploy a "maven style" projects, you have to install the M2E Eclipse WTP plugin (I suppose you are already using the m2e plugin).
To install: Preferences->Maven->Discovery->Open Catalog and choose the WTP plugin.
After reinstalling, you will be able to "run on server" those projects which are maven web projects.
Hope that helps,
// Change $_FILES to new vars and loop them
foreach($_FILES['files'] as $key=>$val)
{
$i = 1;
foreach($val as $v)
{
$field_name = "file_".$i;
$_FILES[$field_name][$key] = $v;
$i++;
}
}
// Unset the useless one ;)
unset($_FILES['files']);
// Put each errors and upload data to an array
$error = array();
$success = array();
// main action to upload each file
foreach($_FILES as $field_name => $file)
{
if ( ! $this->upload->do_upload($field_name))
{
echo ' failed ';
}else{
echo ' success ';
}
}
there is no timeout, by default.
This will do it to every line in the file:
:%s/$/,/
If you want to do a subset of lines instead of the whole file, you can specify them in place of the %
.
One way is to do a visual select and then type the :
. It will fill in :'<,'>
for you, then you type the rest of it (Notice you only need to add s/$/,/
)
:'<,'>s/$/,/
None of these solutions were working for me. Here's a minimal solution that works on Lollipop. On my device, only Gmail and the native email apps appear in the resulting chooser list.
Intent emailIntent = new Intent(Intent.ACTION_SENDTO,
Uri.parse("mailto:" + Uri.encode(address)));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, body);
startActivity(Intent.createChooser(emailIntent, "Send email via..."));
Use content=
"IE=edge,chrome=1"
Skip other X-UA-Compatible
modes
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
--------------------------
No compatibility icon
The IE9 Address bar does not show up the Compatibility View button
and the page does not also show up a jumble of out-of-place menus, images, and text boxes.
Features
This meta tag is required to enable javascript::JSON.parse()
on IE8
(even when <!DOCTYPE html>
is present)
Correctness
Rendering/Execution of modern HTML/CSS/JavaScript is more valid (nicer).
Performance
The Trident rendering engine should run faster in its edge mode.
In your HTML
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
IE=edge
means IE should use the latest (edge) version of its rendering enginechrome=1
means IE should use the Chrome rendering engine if installedOr better in the configuration of your web server:
(see also the RiaD's answer)
Apache as proposed by pixeline
<IfModule mod_setenvif.c>
<IfModule mod_headers.c>
BrowserMatch MSIE ie
Header set X-UA-Compatible "IE=Edge,chrome=1" env=ie
</IfModule>
</IfModule>
<IfModule mod_headers.c>
Header append Vary User-Agent
</IfModule>
Nginx as proposed by Stef Pause
server {
#...
add_header X-UA-Compatible "IE=Edge,chrome=1";
}
Varnish proxy as proposed by Lucas Riutzel
sub vcl_deliver {
if( resp.http.Content-Type ~ "text/html" ) {
set resp.http.X-UA-Compatible = "IE=edge,chrome=1";
}
}
IIS (since v7)
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="X-UA-Compatible" value="IE=edge,chrome=1" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
As noticed by Lynda (see comments), the Compatibility changes in IE11 recommends Edge mode:
Starting with IE11, edge mode is the preferred document mode; it represents the highest support for modern standards available to the browser.
But the position of Microsoft was not clear. Another MSDN page did not recommend Edge mode:
Because Edge mode forces all pages to be opened in standards mode, regardless of the version of Internet Explorer, you might be tempted to use this for all pages viewed with Internet Explorer. Don't do this, as the
X-UA-Compatible
header is only supported starting with Windows Internet Explorer 8.
Instead, Microsoft recommended using <!DOCTYPE html>
:
If you want all supported versions of Internet Explorer to open your pages in standards mode, use the HTML5 document type declaration [...]
As Ricardo explains (in the comments below) any DOCTYPE (HTML4, XHTML1...) can be used to trigger Standards Mode, not only HTML5's DOCTYPE. The important thing is to always have a DOCTYPE in the page.
Clara Onager has even noticed in an older version of Specifying legacy document modes:
Edge mode is intended for testing purposes only; do not use it in a production environment.
It is so confusing that Usman Y thought Clara Onager was speaking about:
The [...] example is provided for illustrative purposes only; don't use it in a production environment.
<meta http-equiv="X-UA-Compatible" content="IE=7,9,10" >
Well... In the rest of this answer I give more explanations why using content="IE=edge,chrome=1"
is a good practice in production.
For many years (2000 to 2008), IE market share was more than 80%. And IE v6 was considered as a de facto standard (80% to 97% market share in 2003, 2004, 2005 and 2006 for IE6 only, more market share with all IE versions).
As IE6 was not respecting Web standards, developers had to test their website using IE6. That situation was great for Microsoft (MS) as web developers had to buy MS products (e.g. IE cannot be used without buying Windows), and it was more profit-making to stay non-compliant (i.e. Microsoft wanted to become the standard excluding other companies).
Therefore many many sites were IE6 compliant only, and as IE was not compliant with web standard, all these web sites was not well rendered on standards compliant browsers. Even worse, many sites required only IE.
However, at this time, Mozilla started Firefox development respecting as much as possible all the web standards (other browser were implemented to render pages as done by IE6). As more and more web developers wanted to use the new web standards features, more and more websites were more supported by Firefox than IE.
When IE market sharing was decreasing, MS realized staying standard incompatible was not a good idea. Therefore MS started to release new IE version (IE8/IE9/IE10) respecting more and more the web standards.
But the issue is all the websites designed for IE6: Microsoft could not release new IE versions incompatible with these old IE6-designed websites. Instead of deducing the IE version a website has been designed, MS requested developers to add extra data (X-UA-Compatible
) in their pages.
Nowadays, IE6 is still used (0.7% in 2016) (4.5% in January 2014), and some internet websites are still IE6-only-compliant. Some intranet website/applications are tested using IE6. Some intranet website are 100% functional only on IE6. These companies/departments prefer to postpone the migration cost: other priorities, nobody no longer knows how the website/application has been implemented, the owner of the legacy website/application went bankrupt...
China represents 50% of IE6 usage in 2013, but it may change in the next years as Chinese Linux distribution is being broadcast.
If you (try to) respect web standard, you can simply always use http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"
. To keep compatibility with old browsers, just avoid using latest web features: use the subset supported by the oldest browser you want to support. Or If you want to go further, you may adopt concepts as Graceful degradation, Progressive enhancement and Unobtrusive JavaScript. (You may also be pleased to read What should a web developer consider?.)
Do do not care about the best IE version rendering: this is not your job as browsers have to be compliant with web standards. If your site is standard compliant and use moderately latest features, therefore browsers have to be compliant with your website.
Moreover, as there are many campaigns to kill IE6 (IE6 no more, MS campaign), nowadays you may avoid wasting time with IE testing!
In 2009-2012, I worked for a company using IE6 as the official single browser allowed. I had to implement an intranet website for IE6 only. I decided to respect web standard but using the IE6-capable subset (HTML/CSS/JS).
It was hard, but when the company switched to IE8, the website was still well rendered because I had used Firefox and firebug to check the web-standard compatibility ;)
The Immediate window is used to debug and evaluate expressions, execute statements, print variable values, and so forth. It allows you to enter expressions to be evaluated or executed by the development language during debugging.
To display Immediate Window, choose Debug >Windows >Immediate or press Ctrl-Alt-I
Here is an example with Immediate Window:
int Sum(int x, int y) { return (x + y);}
void main(){
int a, b, c;
a = 5;
b = 7;
c = Sum(a, b);
char temp = getchar();}
add breakpoint
call commands
Simply you can put a back slash in front of your css link
The column of PARENT table to which you are referring to from child table has to be unique. If it is not, cause an error no 150.
BrixenDK is right.
.ajaxStop()
callback executed when all ajax call completed. This is a best place to put your handler.
$(document).ajaxStop(function(){
window.location.reload();
});
jQuery has JSON-REST plugin with REST style of URI parameter templates. According to its description example of using is the followin: $.Read("/{b}/{a}", { a:'foo', b:'bar', c:3 })
becomes a GET to "/bar/foo?c=3".
Also in your \.git\info
projects directory there is an exclude file that is effectively the same thing as .gitignore
(I think). You can add files and directories to ignore in that.
If SQL Server is running and you still get an error; When SQL Server is opened, instead of the default server name which is displayed you should select the server name ending with \SQLEXPRESS under the Server name-> Browse for more-> Database engine option.
Another alternative that uses an external library is _.has() from Lodash.
E.g.
_.has(a, 'b.c')
is equal to
(a && a.b && a.b.c)
EDIT: As noted in the comments, you lose out on Typescript's type inference when using this method. E.g. Assuming that one's objects are properly typed, one would get a compilation error with (a && a.b && a.b.z) if z is not defined as a field of object b. But using _.has(a, 'b.z'), one would not get that error.
int *pointer[280];
//Creates 280 pointers of type int.
In 32 bit os, 4 bytes for each pointer. so 4 * 280 = 1120 bytes.
int (*pointer)[100][280];
// Creates only one pointer which is used to point an array of [100][280] ints.
Here only 4 bytes.
Coming to your question, int (*pointer)[280];
and int (*pointer)[100][280];
are different though it points to same 2D array of [100][280].
Because if int (*pointer)[280];
is incremented, then it will points to next 1D array, but where as int (*pointer)[100][280];
crosses the whole 2D array and points to next byte. Accessing that byte may cause problem if that memory doen't belongs to your process.
IMPORTANT:
Please notice this solution is from 2015 might be too old and deprecated.
None of the above worked for me so I made a tutorial and wrote it for myself since I lost many hours trying to implement this. Hope this helps someone:
1) Add to your AndroidManifest.xml
file the ACCESS_COARSE_LOCATION
& ACCESS_FINE_LOCATION
:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.appname" >
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application...
2) Go to app/build.gradle
file and add the following dependency (make sure to use the latest available version):
dependencies {
//IMPORTANT: make sure to use the newest version. 11.0.1 is old AF
compile 'com.google.android.gms:play-services-location:11.0.1
}
3) In your activity implement the following:
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.GoogleMap;
public class HomeActivity extends AppCompatActivity implements
ConnectionCallbacks,
OnConnectionFailedListener,
LocationListener {
//Define a request code to send to Google Play services
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private double currentLatitude;
private double currentLongitude;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mGoogleApiClient = new GoogleApiClient.Builder(this)
// The next two lines tell the new client that “this” current class will handle connection stuff
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
//fourth line adds the LocationServices API endpoint from GooglePlayServices
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
@Override
protected void onResume() {
super.onResume();
//Now lets connect to the API
mGoogleApiClient.connect();
}
@Override
protected void onPause() {
super.onPause();
Log.v(this.getClass().getSimpleName(), "onPause()");
//Disconnect from API onPause()
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
/**
* If connected get lat and long
*
*/
@Override
public void onConnected(Bundle bundle) {
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
} else {
//If everything went fine lets get latitude and longitude
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
Toast.makeText(this, currentLatitude + " WORKS " + currentLongitude + "", Toast.LENGTH_LONG).show();
}
}
@Override
public void onConnectionSuspended(int i) {}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.e("Error", "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
/**
* If locationChanges change lat and long
*
*
* @param location
*/
@Override
public void onLocationChanged(Location location) {
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
Toast.makeText(this, currentLatitude + " WORKS " + currentLongitude + "", Toast.LENGTH_LONG).show();
}
}
The Beginner’s Guide to Location in Android
Note: This doesn't seem to work in the emulator but works just fine on a device
As @Cephalopod stated it isn't possible but you can shorten a UUID to 22 characters
public static String encodeUUIDBase64(UUID uuid) {
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
bb.putLong(uuid.getMostSignificantBits());
bb.putLong(uuid.getLeastSignificantBits());
return StringUtils.trimTrailingCharacter(BaseEncoding.base64Url().encode(bb.array()), '=');
}
This is how to set an image into ImageView
using the setImageResource() method:
ImageView myImageView = (ImageView)v.findViewById(R.id.img_play);
// supossing to have an image called ic_play inside my drawables.
myImageView.setImageResource(R.drawable.ic_play);
In Swift 3, there is no need for completion handler when DispatchQueue
finishes one task.
Furthermore you can achieve your goal in different ways
One way is this:
var a: Int?
let queue = DispatchQueue(label: "com.app.queue")
queue.sync {
for i in 0..<10 {
print("??" , i)
a = i
}
}
print("After Queue \(a)")
It will wait until the loop finishes but in this case your main thread will block.
You can also do the same thing like this:
let myGroup = DispatchGroup()
myGroup.enter()
//// Do your task
myGroup.leave() //// When your task completes
myGroup.notify(queue: DispatchQueue.main) {
////// do your remaining work
}
One last thing: If you want to use completionHandler when your task completes using DispatchQueue, you can use DispatchWorkItem
.
Here is an example how to use DispatchWorkItem
:
let workItem = DispatchWorkItem {
// Do something
}
let queue = DispatchQueue.global()
queue.async {
workItem.perform()
}
workItem.notify(queue: DispatchQueue.main) {
// Here you can notify you Main thread
}
If [John Smith]
is in cell A1, then use this formula to do what you want:
=SUBSTITUTE(SUBSTITUTE(A1, "[", ""), "]", "")
The inner SUBSTITUTE replaces all instances of "[" with "" and returns a new string, then the other SUBSTITUTE replaces all instances of "]" with "" and returns the final result.
1. First should understand the error meaning
Error not enough values to unpack (expected 3, got 2)
means:
a 2 part tuple, but assign to 3 values
and I have written demo code to show for you:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Function: Showing how to understand ValueError 'not enough values to unpack (expected 3, got 2)'
# Author: Crifan Li
# Update: 20191212
def notEnoughUnpack():
"""Showing how to understand python error `not enough values to unpack (expected 3, got 2)`"""
# a dict, which single key's value is two part tuple
valueIsTwoPartTupleDict = {
"name1": ("lastname1", "email1"),
"name2": ("lastname2", "email2"),
}
# Test case 1: got value from key
gotLastname, gotEmail = valueIsTwoPartTupleDict["name1"] # OK
print("gotLastname=%s, gotEmail=%s" % (gotLastname, gotEmail))
# gotLastname, gotEmail, gotOtherSomeValue = valueIsTwoPartTupleDict["name1"] # -> ValueError not enough values to unpack (expected 3, got 2)
# Test case 2: got from dict.items()
for eachKey, eachValues in valueIsTwoPartTupleDict.items():
print("eachKey=%s, eachValues=%s" % (eachKey, eachValues))
# same as following:
# Background knowledge: each of dict.items() return (key, values)
# here above eachValues is a tuple of two parts
for eachKey, (eachValuePart1, eachValuePart2) in valueIsTwoPartTupleDict.items():
print("eachKey=%s, eachValuePart1=%s, eachValuePart2=%s" % (eachKey, eachValuePart1, eachValuePart2))
# but following:
for eachKey, (eachValuePart1, eachValuePart2, eachValuePart3) in valueIsTwoPartTupleDict.items(): # will -> ValueError not enough values to unpack (expected 3, got 2)
pass
if __name__ == "__main__":
notEnoughUnpack()
using VSCode
debug effect:
2. For your code
for name, email, lastname in unpaidMembers.items():
but error
ValueError: not enough values to unpack (expected 3, got 2)
means each item(a tuple value) in unpaidMembers
, only have 1 parts:email
, which corresponding above code
unpaidMembers[name] = email
so should change code to:
for name, email in unpaidMembers.items():
to avoid error.
But obviously you expect extra lastname
, so should change your above code to
unpaidMembers[name] = (email, lastname)
and better change to better syntax:
for name, (email, lastname) in unpaidMembers.items():
then everything is OK and clear.
I believe alt is required for strict XHTML compliance.
As others have noted, title is for tooltips (nice to have), alt is for accessibility. Nothing wrong with using both, but alt should always be there.
return false using only if you have some worng in function (by some test) or you want to stop some function, example use return false in end "onsubmit"
If by "restart", you mean to start a new 4 second interval at this moment, then you must stop and restart the timer.
function myFn() {console.log('idle');}
var myTimer = setInterval(myFn, 4000);
// Then, later at some future time,
// to restart a new 4 second interval starting at this exact moment in time
clearInterval(myTimer);
myTimer = setInterval(myFn, 4000);
You could also use a little timer object that offers a reset feature:
function Timer(fn, t) {
var timerObj = setInterval(fn, t);
this.stop = function() {
if (timerObj) {
clearInterval(timerObj);
timerObj = null;
}
return this;
}
// start timer using current settings (if it's not already running)
this.start = function() {
if (!timerObj) {
this.stop();
timerObj = setInterval(fn, t);
}
return this;
}
// start with new or original interval, stop current interval
this.reset = function(newT = t) {
t = newT;
return this.stop().start();
}
}
Usage:
var timer = new Timer(function() {
// your function here
}, 5000);
// switch interval to 10 seconds
timer.reset(10000);
// stop the timer
timer.stop();
// start the timer
timer.start();
Working demo: https://jsfiddle.net/jfriend00/t17vz506/
It's not possible to run a java class from a WAR file. WAR files have a different structure to Jar files.
To find the related java classes, export (preferred way to use ant) them as Jar put it in your web app lib.
Then you can use the jar file as normal to run java program. The same jar was also referred in web app (if you put this jar in web app lib)
I also had similar issue. Had correctly installed the application, had appropriately setup the JAVA_HOME, still it was not able to find the JDK and complains about the ver 1.6.0_17.
I no longer have any such version installed on my machine. After much digging I got onto the "HKEY_LOCAL_MACHINE\software\javasoft\Java Development Kit\
" where I found multiple JDK version being mentioned.
I removed all except 1.8.0_25 that I currently have on my machine. Restarted the Android Studio, and it worked without any problem. May be someone visit this page, facing similar issue, might help.
Ansible has a version_compare
filter since 1.6.
You can do something like below in when
conditional:
when: ansible_distribution_version | version_compare('12.04', '>=')
This will give you support for major & minor versions comparisons and you can compare versions using operators like:
<, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne
You can find more information about this here: Ansible - Version comparison filters
Otherwise if you have really simple case you can use what @ProfHase85 suggested
You can't explicitly clear Scanner's buffer. Internally, it may clear the buffer after a token is read, but that's an implementation detail outside of the porgrammers' reach.
Your status-codes are also a collection, so use Contains
:
var allowedStatus = new[]{ "A", "B", "C" };
var filteredOrders = orders.Order.Where(o => allowedStatus.Contains(o.StatusCode));
or in query syntax:
var filteredOrders = from order in orders.Order
where allowedStatus.Contains(order.StatusCode)
select order;
I had the same problem, and the way I ended up fixing it was like this:
ul, li{
list-style:none;
list-style-type:none;
}
Maybe it's a little extreme, but when I did that, it worked for me.
Try this:
ALTER TABLE product
ADD FOREIGN KEY (product_ID) REFERENCES product(product_ID);
I have a large app that was having problems uploading to the AppStore using the archive method you will find in XCode 4. The activity indicator kept spinning for hours whether I was trying to validate or distribute, so I created a support ticket to Apple. During that process, I found out you could right click on the .app in your Products folder inside the Project Navigator of XCode, and compress the app to submit using the Application Loader 2.5.1. (aka the old method). Only the Debug - iphoneos folder is accessible this way (for now) and once Apple responded, this is what they had to say:
I'm glad to hear that Application Loader has provided you a viable workaround. Discussing this situation internally, we're not sure that submitting the Debug build will pose too much of a problem (so long as it was signed with the App Store distribution profile, as you mentioned it was). The app will likely be slower as the debug switches are turned on and optimizations are turned off for the Debug configuration, though it will still run. App Review will ultimately determine whether or not that's ok, as I'm not sure that's something they check for. You could try reaching out directly to App Review to confirm this, if you wish. However, since App Loader is working for you, I do recommend rebuilding the app with your Release configuration and resubmitting to play it safe. To find your Release build in Xcode 4.x, control-click on the Application Archive on the Archives tab in the organizer, and choose "Show in Finder." Then, control-click on the .xcarchive file in Finder and choose "Show Package Contents." The release built .app file should be located within the /Products/Applications folder.
This was very helpful information for developers who are having problems with the archive method, and my app is now uploading successfully without any concern that it won't run to the best of it's ability.
If you are in a middle of merging you can always abort it
git merge --abort
Anything in Michael Rys blog
Update
My recomendation would be to shred the XML into relations and do searches and joins on the resulted relation, in a set oriented fashion, rather than the procedural fashion of searching specific nodes in the XML. Here is a simple XML query that shreds out the nodes and attributes of interest:
select x.value(N'../../../../@stepId', N'int') as StepID
, x.value(N'../../@id', N'int') as ComponentID
, x.value(N'@nom',N'nvarchar(100)') as Nom
, x.value(N'@valeur', N'nvarchar(100)') as Valeur
from @x.nodes(N'/xml/box/components/component/variables/variable') t(x)
However, if you must use an XPath that retrieves exactly the value of interest:
select x.value(N'@valeur', N'nvarchar(100)') as Valeur
from @x.nodes(N'/xml/box[@stepId=sql:variable("@stepID")]/
components/component[@id = sql:variable("@componentID")]/
variables/variable[@nom="Enabled"]') t(x)
If the stepID and component ID are columns, not variables, the you should use sql:column() instead of sql:variable in the XPath filters. See Binding Relational Data Inside XML Data.
And finaly if all you need is to check for existance you can use the exist() XML method:
select @x.exist(
N'/xml/box[@stepId=sql:variable("@stepID")]/
components/component[@id = sql:variable("@componentID")]/
variables/variable[@nom="Enabled" and @valeur="Yes"]')
You have a couple options. You can include a callback as a second argument, which will be invoked with any error message and the object. This example is straight from the AWS documentation:
s3.getObject(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
Alternatively, you can convert the output to a stream. There's also an example in the AWS documentation:
var s3 = new AWS.S3({apiVersion: '2006-03-01'});
var params = {Bucket: 'myBucket', Key: 'myImageFile.jpg'};
var file = require('fs').createWriteStream('/path/to/file.jpg');
s3.getObject(params).createReadStream().pipe(file);
Don't use $(document).ready() just put the script directly in the head section of the page. Pages are processed top to bottom so things at the top are processed first.
Sending data to some service page.
<form class="form-horizontal" role="form" ng-submit="submit_form()">
<input type="text" name="user_id" ng-model = "formAdata.user_id">
<input type="text" id="name" name="name" ng-model = "formAdata.name">
</form>
$scope.submit_form = function()
{
$http({
url: "http://localhost/services/test.php",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param($scope.formAdata)
}).success(function(data, status, headers, config) {
$scope.status = status;
}).error(function(data, status, headers, config) {
$scope.status = status;
});
}
Assuming you want to change the url to another within the same domain, you can use this:
history.pushState('data', '', 'http://www.yourcurrentdomain.com/new/path');
In onMapReady() Method
change the zoomLevel to any desired value.
float zoomLevel = (float) 18.0;
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoomLevel));
Using regexes for this purpose is the wrong approach. Since you are using python you have a really awesome library available to extract parts from HTML documents: BeautifulSoup.
I'd like to make some changes: In C, you can use the built in qsort command:
int compare( const void* a, const void* b)
{
int int_a = * ( (int*) a );
int int_b = * ( (int*) b );
// an easy expression for comparing
return (int_a > int_b) - (int_a < int_b);
}
qsort( a, 6, sizeof(int), compare )
I just experienced this. I had read the suggestions on this page, as well as the SQL Authority suggestions (which is the same thing) and none of the above worked.
In the end, I removed the account and recreated (with the same username/password). Just like that, all the issues went away.
Sadly, this means I don't know what went wrong so I can't share any thing else.
The answer with for
is correct, but if you really want to use functional style avoiding for
statement - you can use the following instead of your expression:
Array.from(Array(1000000), () => Math.random());
The Array.from() method creates a new Array instance from an array-like or iterable object. The second argument of this method is a map function to call on every element of the array.
Following the same idea you can rewrite it using ES2015 Spread operator:
[...Array(1000000)].map(() => Math.random())
In both examples you can get an index of the iteration if you need, for example:
[...Array(1000000)].map((_, i) => i + Math.random())
2019-05-08 Android Studios needs an upgrade. upgrade Android Studios to 3.3.- and the error with .R; goes away.
Also the above methods also work.
I found this SMSMS Boost addon, which is free and does exactly this among other things. You can right click on the results and select Script data as.
devnull's answer provides a function:
mkfile() { mkdir -p -- "$1" && touch -- "$1"/"$2" }
This function did not work for me as is (I'm running bash 4.3.48 on WSL Ubuntu), but did work once I removed the double dashes. So, this worked for me:
echo 'mkfile() { mkdir -p "$1" && touch "$1"/"$2" }' >> ~/.bash_profile
source ~/.bash_profile
mkfile sample/dir test.file
Add a reference to System.Web.dll and then you can use the System.Web.HtmlUtility class
//From your application set the Console to write to your RichTextkBox
//object:
Console.SetOut(new RichTextBoxWriter(yourRichTextBox));
//To ensure that your RichTextBox object is scrolled down when its text is
//changed add this event:
private void yourRichTextBox_TextChanged(object sender, EventArgs e)
{
yourRichTextBox.SelectionStart = yourRichTextBox.Text.Length;
yourRichTextBox.ScrollToCaret();
}
public delegate void StringArgReturningVoidDelegate(string text);
public class RichTextBoxWriter : TextWriter
{
private readonly RichTextBox _richTextBox;
public RichTextBoxWriter(RichTextBox richTexttbox)
{
_richTextBox = richTexttbox;
}
public override void Write(char value)
{
SetText(value.ToString());
}
public override void Write(string value)
{
SetText(value);
}
public override void WriteLine(char value)
{
SetText(value + Environment.NewLine);
}
public override void WriteLine(string value)
{
SetText(value + Environment.NewLine);
}
public override Encoding Encoding => Encoding.ASCII;
//Write to your UI object in thread safe way:
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (_richTextBox.InvokeRequired)
{
var d = new StringArgReturningVoidDelegate(SetText);
_richTextBox.Invoke(d, text);
}
else
{
_richTextBox.Text += text;
}
}
}
You can use:
ls -lh
Using this command you'll see the apparent space of the directory and true space of the files and in details the names of the files displayed, besides the size and creation date of each.
If I understand you right, you can do this:
<img src="image.png" style="background-color:red;" />
In fact, you can even apply a whole background-image
to the image, resulting in two "layers" without the need for multi-background support in the browser ;)
you need to add jar file in your build path..
commons-dbcp-1.1-RC2.jar
or any version of that..!!!!
ADDED : also make sure you have commons-pool-1.1.jar too in your build path.
ADDED: sorry saw complete list of jar late... may be version clashes might be there.. better check out..!!! just an assumption.
Try adjusting the code at "SqlDbType" to match your DB type if necessary and use this code:
comm.Parameters.Add("@person",SqlDbType.VarChar).Value=MyName;
or:
comm.Parameters.AddWithValue("@person", Myname);
That should work but remember with Command.Parameters.Add(), you can define the specific SqlDbType and with Command.Parameters.AddWithValue(), it will try get the SqlDbType based on parameter value implicitly which can break sometimes if it can not implicitly convert the datatype.
Hope this helps.
Normal money conversions will preserve individual pennies:
SELECT convert(varchar(30), moneyfield, 1)
The last parameter decides what the output format looks like:
0 (default) No commas every three digits to the left of the decimal point, and two digits to the right of the decimal point; for example, 4235.98.
1 Commas every three digits to the left of the decimal point, and two digits to the right of the decimal point; for example, 3,510.92.
2 No commas every three digits to the left of the decimal point, and four digits to the right of the decimal point; for example, 4235.9819.
If you want to truncate the pennies, and count in pounds, you can use rounding to the nearest pound, floor to the lowest whole pound, or ceiling to round up the pounds:
SELECT convert(int, round(moneyfield, 0))
SELECT convert(int, floor(moneyfield))
SELECT convert(int, ceiling(moneyfield))
It probably aimed to select all the informations in your table. If you use this kind of query (for example in PHP) :
mysql_query("SELECT * FROM newsletter WHERE email = '$email'");
The email ' OR 1=1/* will give this kind of query :
mysql_query("SELECT * FROM newsletter WHERE email = '' OR 1=1/*");
So it selects all the rows (because 1=1 is always true and the rest of the query is 'commented'). But it was not successful
I had a large enumerated type I wanted to convert it into an NSDictionary
lookup. I ended up using sed
from OSX terminal as:
$ sed -E 's/^[[:space:]]{1,}([[:alnum:]]{1,}).*$/ @(\1) : @"\1",/g' ObservationType.h
which can be read as: 'capture the first word on the line and output @(word) : @"word",'
This regex converts the enum in a header file named 'ObservationType.h' which contains:
typedef enum : int {
ObservationTypePulse = 1,
ObservationTypeRespRate = 2,
ObservationTypeTemperature = 3,
.
.
}
into something like:
@(ObservationTypePulse) : @"ObservationTypePulse",
@(ObservationTypeRespRate) : @"ObservationTypeRespRate",
@(ObservationTypeTemperature) : @"ObservationTypeTemperature",
.
.
which can then be wrapped in a method using modern objective-c syntax @{ }
(as explained by @yar1vn above) to create a NSDictionary
lookup :
-(NSDictionary *)observationDictionary
{
static NSDictionary *observationDictionary;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
observationDictionary = [[NSDictionary alloc] initWithDictionary:@{
@(ObservationTypePulse) : @"ObservationTypePulse",
@(ObservationTypeRespRate) : @"ObservationTypeRespRate",
.
.
}];
});
return observationDictionary;
}
The dispatch_once
boiler-plate is just to ensure that the static variable is initialised in a thread-safe manner.
Note: I found the sed regex expression on OSX odd - when I tried to use +
to match 'one or more' it didn't work and had to resort to using {1,}
as a replacement
A solution is presented here not exactly for your problem but exactly for the given error.
Start --> All Programs --> Microsoft SQL Server 2005 --> Configuration Tools --> SQL Server Surface Area Configuration
Add New Administrator
Select 'Member of SQL Server SysAdmin role on SQLEXPRESS' and add it to right box.
Click Ok.
A more generalized solution that handles arbitrarily-deeply nested dicts and lists would be:
def dumpclean(obj):
if isinstance(obj, dict):
for k, v in obj.items():
if hasattr(v, '__iter__'):
print k
dumpclean(v)
else:
print '%s : %s' % (k, v)
elif isinstance(obj, list):
for v in obj:
if hasattr(v, '__iter__'):
dumpclean(v)
else:
print v
else:
print obj
This produces the output:
A
color : 2
speed : 70
B
color : 3
speed : 60
I ran into a similar need and developed a more robust function as an exercise for myself. I'm including it here in case it can be of value to another. In running nosetest, I also found it helpful to be able to specify the output stream in the call so that sys.stderr could be used instead.
import sys
def dump(obj, nested_level=0, output=sys.stdout):
spacing = ' '
if isinstance(obj, dict):
print >> output, '%s{' % ((nested_level) * spacing)
for k, v in obj.items():
if hasattr(v, '__iter__'):
print >> output, '%s%s:' % ((nested_level + 1) * spacing, k)
dump(v, nested_level + 1, output)
else:
print >> output, '%s%s: %s' % ((nested_level + 1) * spacing, k, v)
print >> output, '%s}' % (nested_level * spacing)
elif isinstance(obj, list):
print >> output, '%s[' % ((nested_level) * spacing)
for v in obj:
if hasattr(v, '__iter__'):
dump(v, nested_level + 1, output)
else:
print >> output, '%s%s' % ((nested_level + 1) * spacing, v)
print >> output, '%s]' % ((nested_level) * spacing)
else:
print >> output, '%s%s' % (nested_level * spacing, obj)
Using this function, the OP's output looks like this:
{
A:
{
color: 2
speed: 70
}
B:
{
color: 3
speed: 60
}
}
which I personally found to be more useful and descriptive.
Given the slightly less-trivial example of:
{"test": [{1:3}], "test2":[(1,2),(3,4)],"test3": {(1,2):['abc', 'def', 'ghi'],(4,5):'def'}}
The OP's requested solution yields this:
test
1 : 3
test3
(1, 2)
abc
def
ghi
(4, 5) : def
test2
(1, 2)
(3, 4)
whereas the 'enhanced' version yields this:
{
test:
[
{
1: 3
}
]
test3:
{
(1, 2):
[
abc
def
ghi
]
(4, 5): def
}
test2:
[
(1, 2)
(3, 4)
]
}
I hope this provides some value to the next person looking for this type of functionality.
To solve this error, it is enough to add from google.colab import files
in your code!
Maybe use in between better. It worked for me to get range then filter it
<context:property-placeholder location="classpath*:spring/*.properties" />
If you place it somewhere in the classpath in a directory named spring (change names/dirs accordingly), you can access with above
<property name="locations" value ="config/springcontext.properties" />
this will be pointing to web-inf/classes/config/springcontext.properties
Do which sshpass
in your command line to get the absolute path to sshpass
and replace it in the bash script.
You should also probably do the same with the command
you are trying to run.
The problem might be that it is not finding it.
See http://wiki.apache.org/httpd/DistrosDefaultLayout for discussion of where you might find Apache httpd configuration files on various platforms, since this can vary from release to release and platform to platform. The most common answer, however, is either /etc/apache/conf or /etc/httpd/conf
Generically, you can determine the answer by running the command:
httpd -V
(That's a capital V). Or, on systems where httpd is renamed, perhaps apache2ctl -V
This will return various details about how httpd is built and configured, including the default location of the main configuration file.
One of the lines of output should look like:
-D SERVER_CONFIG_FILE="conf/httpd.conf"
which, combined with the line:
-D HTTPD_ROOT="/etc/httpd"
will give you a full path to the default location of the configuration file
I was trying to create a borderless window with WindowStyle="None"
but when I tested it, seems that appears a white bar in the top, after some research it appears to be a "Resize border", here is an image (I remarked in yellow):
After some research over the internet, and lots of difficult non xaml solutions, all the solutions that I found were code behind in C# and lots of code lines, I found indirectly the solution here: Maximum custom window loses drop shadow effect
<WindowChrome.WindowChrome>
<WindowChrome
CaptionHeight="0"
ResizeBorderThickness="5" />
</WindowChrome.WindowChrome>
Note : You need to use .NET 4.5 framework, or if you are using an older version use WPFShell, just reference the shell and use Shell:WindowChrome.WindowChrome
instead.
I used the WindowChrome
property of Window, if you use this that white "resize border" disappears, but you need to define some properties to work correctly.
CaptionHeight: This is the height of the caption area (headerbar) that allows for the Aero snap, double clicking behaviour as a normal title bar does. Set this to 0 (zero) to make the buttons work.
ResizeBorderThickness: This is thickness at the edge of the window which is where you can resize the window. I put to 5 because i like that number, and because if you put zero its difficult to resize the window.
After using this short code the result is this:
And now, the white border disappeared without using ResizeMode="NoResize"
and AllowsTransparency="True"
, also it shows a shadow in the window.
Later I will explain how to make to work the buttons (I didn't used images for the buttons) easily with simple and short code, Im new and i think that I can post to codeproject, because here I didn't find the place to post the tutorial.
Maybe there is another solution (I know that there are hard and difficult solutions for noobs like me) but this works for my personal projects.
Here is the complete code
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Concursos"
mc:Ignorable="d"
Title="Concuros" Height="350" Width="525"
WindowStyle="None"
WindowState="Normal"
ResizeMode="CanResize"
>
<WindowChrome.WindowChrome>
<WindowChrome
CaptionHeight="0"
ResizeBorderThickness="5" />
</WindowChrome.WindowChrome>
<Grid>
<Rectangle Fill="#D53736" HorizontalAlignment="Stretch" Height="35" VerticalAlignment="Top" PreviewMouseDown="Rectangle_PreviewMouseDown" />
<Button x:Name="Btnclose" Content="r" HorizontalAlignment="Right" VerticalAlignment="Top" Width="35" Height="35" Style="{StaticResource TempBTNclose}"/>
<Button x:Name="Btnmax" Content="2" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,0,35,0" Width="35" Height="35" Style="{StaticResource TempBTNclose}"/>
<Button x:Name="Btnmin" Content="0" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,0,70,0" Width="35" Height="35" Style="{StaticResource TempBTNclose}"/>
</Grid>
Thank you!
This is easy method worked for me.
boston = load_boston()
boston_frame = pd.DataFrame(data=boston.data, columns=boston.feature_names)
boston_frame["target"] = boston.target
But this can applied to load_iris as well.
Use:
Random r = new Random();
int x= r.Next(10);//Max range
As the more recent MySQL documentation on view restrictions says:
Before MySQL 5.7.7, subqueries cannot be used in the FROM clause of a view.
This means, that choosing a MySQL v5.7.7 or newer or upgrading the existing MySQL instance to such a version, would remove this restriction on views completely.
However, if you have a current production MySQL version that is earlier than v5.7.7, then the removal of this restriction on views should only be one of the criteria being assessed while making a decision as to upgrade or not. Using the workaround techniques described in the other answers may be a more viable solution - at least on the shorter run.
set encoding=utf-8 " The encoding displayed.
set fileencoding=utf-8 " The encoding written to file.
You may as well set both in your ~/.vimrc
if you always want to work with utf-8.
In HTML5, the
<hr>
tag defines a thematic break. In HTML 4.01, the<hr>
tag represents a horizontal rule.
http://www.w3schools.com/tags/tag_hr.asp
So after definition, I would prefer <hr>
A more general answer would be to import java.util.Date
, then when you need to set a timestamp
equal to the current date, simply set it equal to new Date()
.
You could also use:
request.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
An another way is simply :
if($test){
echo "Yes 1";
}
if(!is_null($test)){
echo "Yes 2";
}
$test = "hello";
if($test){
echo "Yes 3";
}
Will return :
"Yes 3"
The best way is to use isset(), otherwise you can have an error like "undefined $test".
You can do it like this :
if( isset($test) && ($test!==null) )
You'll not have any error because the first condition isn't accepted.
you could use the following for different locales
private void localeDecimalInput(final EditText editText){
DecimalFormat decFormat = (DecimalFormat) DecimalFormat.getInstance(Locale.getDefault());
DecimalFormatSymbols symbols=decFormat.getDecimalFormatSymbols();
final String defaultSeperator=Character.toString(symbols.getDecimalSeparator());
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable editable) {
if(editable.toString().contains(defaultSeperator))
editText.setKeyListener(DigitsKeyListener.getInstance("0123456789"));
else
editText.setKeyListener(DigitsKeyListener.getInstance("0123456789" + defaultSeperator));
}
});
}
another way to access a column by number is to use a mapping dictionary where the key is the column name and the value is the column number
dates = pd.date_range('1/1/2000', periods=8)
df = pd.DataFrame(np.random.randn(8, 4),
index=dates, columns=['A', 'B', 'C', 'D'])
print(df)
dct={'A':0,'B':1,'C':2,'D':3}
columns=df.columns
print(df.iloc[:,dct['D']])
Simple method to sending data using java script and ajex call.
First right your form like this
<form id="frm_details" method="post" name="frm_details">
<input id="email" name="email" placeholder="Your Email id" type="text" />
<button class="subscribe-box__btn" type="submit">Need Assistance</button>
</form>
javascript logic target on form id #frm_details after sumbit
$(function(){
$("#frm_details").on("submit", function(event) {
event.preventDefault();
var formData = {
'email': $('input[name=email]').val() //for get email
};
console.log(formData);
$.ajax({
url: "/tsmisc/api/subscribe-newsletter",
type: "post",
data: formData,
success: function(d) {
alert(d);
}
});
});
})
General
Request URL:https://test.abc
Request Method:POST
Status Code:200
Remote Address:13.76.33.57:443
From Data
email:[email protected]
To use the new date range picker, you can use the mat-date-range-input
and mat-date-range-picker
components.
Example
HTML
<mat-form-field>
<mat-label>Enter a date range</mat-label>
<mat-date-range-input [rangePicker]="picker">
<input matStartDate matInput placeholder="Start date">
<input matEndDate matInput placeholder="End date">
</mat-date-range-input>
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-date-range-picker #picker></mat-date-range-picker>
</mat-form-field>
You can read and learn more about this in their official documentation.
Unfortunately, they still haven't build a timepicker
on this release.
Here is my answer:
def draw_text(text, font_name, size, color, x, y, align="nw"):
font = pg.font.Font(font_name, size)
text_surface = font.render(text, True, color)
text_rect = text_surface.get_rect()
if align == "nw":
text_rect.topleft = (x, y)
if align == "ne":
text_rect.topright = (x, y)
if align == "sw":
text_rect.bottomleft = (x, y)
if align == "se":
text_rect.bottomright = (x, y)
if align == "n":
text_rect.midtop = (x, y)
if align == "s":
text_rect.midbottom = (x, y)
if align == "e":
text_rect.midright = (x, y)
if align == "w":
text_rect.midleft = (x, y)
if align == "center":
text_rect.center = (x, y)
screen.blit(text_surface, text_rect)
Of course, you'll need to import pygame, a font and a screen, but this is just a def to add on to the rest of the code, and then call "draw_text".
here is an alt version that also works for me and has attachments (posted already above but complete version unlike the source link, which people posted they cant get it to work since its missing data)
import java.util.Date;
import java.util.Properties;
import javax.activation.CommandMap;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.MailcapCommandMap;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class Mail extends javax.mail.Authenticator {
private String _user;
private String _pass;
private String[] _to;
private String _from;
private String _port;
private String _sport;
private String _host;
private String _subject;
private String _body;
private boolean _auth;
private boolean _debuggable;
private Multipart _multipart;
public Mail() {
_host = "smtp.gmail.com"; // default smtp server
_port = "465"; // default smtp port
_sport = "465"; // default socketfactory port
_user = ""; // username
_pass = ""; // password
_from = ""; // email sent from
_subject = ""; // email subject
_body = ""; // email body
_debuggable = false; // debug mode on or off - default off
_auth = true; // smtp authentication - default on
_multipart = new MimeMultipart();
// There is something wrong with MailCap, javamail can not find a handler for the multipart/mixed part, so this bit needs to be added.
MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
CommandMap.setDefaultCommandMap(mc);
}
public Mail(String user, String pass) {
this();
_user = user;
_pass = pass;
}
public boolean send() throws Exception {
Properties props = _setProperties();
if(!_user.equals("") && !_pass.equals("") && _to.length > 0 && !_from.equals("") && !_subject.equals("") && !_body.equals("")) {
Session session = Session.getInstance(props, this);
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(_from));
InternetAddress[] addressTo = new InternetAddress[_to.length];
for (int i = 0; i < _to.length; i++) {
addressTo[i] = new InternetAddress(_to[i]);
}
msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);
msg.setSubject(_subject);
msg.setSentDate(new Date());
// setup message body
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(_body);
_multipart.addBodyPart(messageBodyPart);
// Put parts in message
msg.setContent(_multipart);
// send email
Transport.send(msg);
return true;
} else {
return false;
}
}
public void addAttachment(String filename) throws Exception {
BodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
_multipart.addBodyPart(messageBodyPart);
}
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(_user, _pass);
}
private Properties _setProperties() {
Properties props = new Properties();
props.put("mail.smtp.host", _host);
if(_debuggable) {
props.put("mail.debug", "true");
}
if(_auth) {
props.put("mail.smtp.auth", "true");
}
props.put("mail.smtp.port", _port);
props.put("mail.smtp.socketFactory.port", _sport);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
return props;
}
// the getters and setters
public String getBody() {
return _body;
}
public void setBody(String _body) {
this._body = _body;
}
public void setTo(String[] toArr) {
// TODO Auto-generated method stub
this._to=toArr;
}
public void setFrom(String string) {
// TODO Auto-generated method stub
this._from=string;
}
public void setSubject(String string) {
// TODO Auto-generated method stub
this._subject=string;
}
// more of the getters and setters …..
}
and to call it in an activity...
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
Button addImage = (Button) findViewById(R.id.send_email);
addImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Mail m = new Mail("[email protected]", "password");
String[] toArr = {"[email protected]", "[email protected]"};
m.setTo(toArr);
m.setFrom("[email protected]");
m.setSubject("This is an email sent using my Mail JavaMail wrapper from an Android device.");
m.setBody("Email body.");
try {
m.addAttachment("/sdcard/filelocation");
if(m.send()) {
Toast.makeText(MailApp.this, "Email was sent successfully.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MailApp.this, "Email was not sent.", Toast.LENGTH_LONG).show();
}
} catch(Exception e) {
//Toast.makeText(MailApp.this, "There was a problem sending the email.", Toast.LENGTH_LONG).show();
Log.e("MailApp", "Could not send email", e);
}
}
});
}
Here is an approach with customizable equals
function which can be used for primitives as well as for custom objects:
Array.prototype.pushUnique = function(element, equalsPredicate = (l, r) => l == r) {
let res = !this.find(item => equalsPredicate(item, element))
if(res){
this.push(element)
}
return res
}
usage:
//with custom equals for objects
myArrayWithObjects.pushUnique(myObject, (left, right) => left.id == right.id)
//with default equals for primitives
myArrayWithPrimitives.pushUnique(somePrimitive)
Powershell 7 has it. https://toastit.dev/2019/09/25/ternary-operator-powershell-7/
PS C:\Users\js> 0 ? 'yes' : 'no'
no
PS C:\Users\js> 1 ? 'yes' : 'no'
yes
I rely on the Status Bar Frame height to detect if it's an iPhone X :
if UIApplication.shared.statusBarFrame.height >= CGFloat(44) {
// It is an iPhone X
}
This is for application un portrait. You could also check the size according to the device orientation. Also, on other iPhones, the Status Bar may be hidden, so the frame height is 0
. On iPhone X, the Status Bar is never hidden.
I will reuse the data example from @PaulRougieux
x <- data_frame(i = c("a","b","c"), j = 1:3)
y <- data_frame(i = c("b","c","d"), k = 4:6)
z <- data_frame(i = c("c","d","a"), l = 7:9)
Here's a short and sweet solution using purrr
and tidyr
library(tidyverse)
list(x, y, z) %>%
map_df(gather, key=key, value=value, -i) %>%
spread(key, value)
this type of error generally occurs when you have to put characters or values more than that you have specified in Database table like in this case:
you specify
transaction_status varchar(10)
but you actually trying to store
_transaction_status
which contain 19 characters.
that's why you faced this type of error in this code..
<div class="foo">Foo Bar</div>
and in your CSS file:
.foo {
background-image: url("images/foo.png");
}
Color is not data.
The Get.cell technique has flaws.
That does not surprise, since the Get.cell uses an old XML command, i.e. a command from the macro language Excel used before VBA was introduced. At that time, Excel colors were limited to less than 60.
Again: Color is not data.
If you want to color-code your cells, use conditional formatting based on the cell values or based on rules that can be expressed with logical formulas. The logic that leads to conditional formatting can also be used in other places to report on the data, regardless of the color value of the cell.
Nowadays this generator pattern can be a solution in many situations.
Here an example of sequential console prompts in nodejs using async readline.question function:
var main = (function* () {
// just import and initialize 'readline' in nodejs
var r = require('readline')
var rl = r.createInterface({input: process.stdin, output: process.stdout })
// magic here, the callback is the iterator.next
var answerA = yield rl.question('do you want this? ', r=>main.next(r))
// and again, in a sync fashion
var answerB = yield rl.question('are you sure? ', r=>main.next(r))
// readline boilerplate
rl.close()
console.log(answerA, answerB)
})() // <-- executed: iterator created from generator
main.next() // kick off the iterator,
// runs until the first 'yield', including rightmost code
// and waits until another main.next() happens
I know it is very late but following approach can also be used:
<select id="type" name="type" >
<option value="Permanent" id="permanent">I am here to stay.</option>
<option value="toremove" id="toremove">Remove me!</option>
<option value="Other" id="other">Other</option>
</select>
and if I have to remove second option (id=toremove), the script would look like
$('#toremove').hide();
public JSONObject RequestWithHttpUrlConn(String _url, String param){
HttpURLConnection con = null;
URL url;
String response = "";
Scanner inStream = null;
PrintWriter out = null;
try {
url = new URL(_url);
con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
if(param != null){
con.setFixedLengthStreamingMode(param.getBytes().length);
}
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
out = new PrintWriter(con.getOutputStream());
if(param != null){
out.print(param);
}
out.flush();
out.close();
inStream = new Scanner(con.getInputStream());
while(inStream.hasNextLine()){
response+=(inStream.nextLine());
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if(con != null){
con.disconnect();
}if(inStream != null){
inStream.close();
}if(out != null){
out.flush();
out.close();
}
}
}
press start button then type cmd
. - Note you will need to run the command prompt as 'Adminstrator'.
write setx -m path "%path%;C:\Python27"
then press enter.
[here -m
for giving accessing permission to all users and in Python27
27 is version 2.7]
%path%;
will prevent the original value from destroying. C:\Python27 will be appended to the current Path
value.
that's it,you are done.
Remove numbering on x-axis or y-axis:
plot(1:10, xaxt='n')
plot(1:10, yaxt='n')
If you want to remove the labels as well:
plot(1:10, xaxt='n', ann=FALSE)
plot(1:10, yaxt='n', ann=FALSE)
Change your code to
document.write("<td width='74'><button id='button' type='button' onclick='myfunction(\""+ name + "\")'>click</button></td>")
Issue: 'id1' is missing in props validation, eslintreact/prop-types
<div id={props.id1} >
...
</div>
Below solution worked, in a function component:
let { id1 } = props;
<div id={id1} >
...
</div>
Hope that helps.
Sure:
var query = grades.GroupBy(student => student.Name)
.Select(group =>
new { Name = group.Key,
Students = group.OrderByDescending(x => x.Grade) })
.OrderBy(group => group.Students.First().Grade);
Note that you can get away with just taking the first grade within each group after ordering, because you already know the first entry will be have the highest grade.
Then you could display them with:
foreach (var group in query)
{
Console.WriteLine("Group: {0}", group.Name);
foreach (var student in group.Students)
{
Console.WriteLine(" {0}", student.Grade);
}
}
Maybe I write this too late, but I have gotten the similar problem when I have tried to override methods for reading properties.
My problem have been: 1) Read property from env if this property has been set in env 2) Read property from system property if this property have been setted in system property 3) And last, read from application properties.
So, for resolving this problem I go to my bean configuration class
@Validated
@Configuration
@ConfigurationProperties(prefix = ApplicationConfiguration.PREFIX)
@PropertySource(value = "${application.properties.path}", factory = PropertySourceFactoryCustom.class)
@Data // lombok
public class ApplicationConfiguration {
static final String PREFIX = "application";
@NotBlank
private String keysPath;
@NotBlank
private String publicKeyName;
@NotNull
private Long tokenTimeout;
private Boolean devMode;
public void setKeysPath(String keysPath) {
this.keysPath = StringUtils.cleanPath(keysPath);
}
}
And overwrite factory in @PropertySource. And then I have created my own implementation for reading properties.
public class PropertySourceFactoryCustom implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
return name != null ? new PropertySourceCustom(name, resource) : new PropertySourceCustom(resource);
}
}
And created PropertySourceCustom
public class PropertySourceCustom extends ResourcePropertySource {
public LifeSourcePropertySource(String name, EncodedResource resource) throws IOException {
super(name, resource);
}
public LifeSourcePropertySource(EncodedResource resource) throws IOException {
super(resource);
}
public LifeSourcePropertySource(String name, Resource resource) throws IOException {
super(name, resource);
}
public LifeSourcePropertySource(Resource resource) throws IOException {
super(resource);
}
public LifeSourcePropertySource(String name, String location, ClassLoader classLoader) throws IOException {
super(name, location, classLoader);
}
public LifeSourcePropertySource(String location, ClassLoader classLoader) throws IOException {
super(location, classLoader);
}
public LifeSourcePropertySource(String name, String location) throws IOException {
super(name, location);
}
public LifeSourcePropertySource(String location) throws IOException {
super(location);
}
@Override
public Object getProperty(String name) {
if (StringUtils.isNotBlank(System.getenv(name)))
return System.getenv(name);
if (StringUtils.isNotBlank(System.getProperty(name)))
return System.getProperty(name);
return super.getProperty(name);
}
}
So, this has helped me.
Let's suppose you want to find all int
not preceded by unsigned
:
With support for negative look-behind:
(?<!unsigned )int
Without support for negative look-behind:
((?!unsigned ).{9}|^.{0,8})int
Basically idea is to grab n preceding characters and exclude match with negative look-ahead, but also match the cases where there's no preceeding n characters. (where n is length of look-behind).
So the regex in question:
(?<!filename)\.js$
would translate to:
((?!filename).{8}|^.{0,7})\.js$
You might need to play with capturing groups to find exact spot of the string that interests you or you want't to replace specific part with something else.
This was just happening to me, but none of the suggestions above worked. I changed directories ("cd ~/tmp") and suddenly the command
ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"
worked for me. Prior to changing directories I had been in a directory that is a Git repository. Perhaps that was interfering with the ruby and Git commands in the Brew install script.
You should add the ngDefaultControl attribute to your input like this:
<md-input
[(ngModel)]="recipient"
name="recipient"
placeholder="Name"
class="col-sm-4"
(blur)="addRecipient(recipient)"
ngDefaultControl>
</md-input>
Taken from comments in this post:
angular2 rc.5 custom input, No value accessor for form control with unspecified name
Note: For later versions of @angular/material:
Nowadays you should instead write:
<md-input-container>
<input
mdInput
[(ngModel)]="recipient"
name="recipient"
placeholder="Name"
(blur)="addRecipient(recipient)">
</md-input-container>
I think the easiest way is to create an interface to get the data from onpostexecute and run the Ui from interface :
Create an Interface :
public interface AsyncResponse {
void processFinish(String output);
}
Then in asynctask
@Override
protected void onPostExecute(String data) {
delegate.processFinish(data);
}
Then in yout main activity
@Override
public void processFinish(String data) {
// do things
}
the solution here worked for me : https://community.hortonworks.com/articles/4427/fix-under-replicated-blocks-in-hdfs-manually.html
su - <$hdfs_user>
bash-4.1$ hdfs fsck / | grep 'Under replicated' | awk -F':' '{print $1}' >> /tmp/under_replicated_files
-bash-4.1$ for hdfsfile in `cat /tmp/under_replicated_files`; do echo "Fixing $hdfsfile :" ; hadoop fs -setrep 3 $hdfsfile; done
You can create multi-line strings by enclosing them in triple quotes. So you can store your HTML in a string and pass that string to write()
:
html_str = """
<table border=1>
<tr>
<th>Number</th>
<th>Square</th>
</tr>
<indent>
<% for i in range(10): %>
<tr>
<td><%= i %></td>
<td><%= i**2 %></td>
</tr>
</indent>
</table>
"""
Html_file= open("filename","w")
Html_file.write(html_str)
Html_file.close()
You can push your local branch to a new remote branch like so:
git push origin master:test
(Assuming origin
is your remote, master
is your local branch name and test
is the name of the new remote branch, you wish to create.)
If at the same time you want to set up your local branch to track the newly created remote branch, you can do so with -u
(on newer versions of Git) or --set-upstream
, so:
git push -u origin master:test
or
git push --set-upstream origin master:test
...will create a new remote branch, named test
, in remote repository origin
, based on your local master
, and setup your local master
to track it.
It's possible that you've run out of memory or some space elsewhere and it prompted the system to mount an overflow filesystem, and for whatever reason, it's not going away.
Try unmounting the overflow partition:
umount /tmp
or
umount overflow
By sorting the file with sort
first, you can then apply uniq
.
It seems to sort the file just fine:
$ cat test.csv
[email protected],2009-11-27 00:58:29.793000000,xx3.net,255.255.255.0
[email protected],2009-11-27 01:05:47.893000000,xx2.net,127.0.0.1
[email protected],2009-11-27 00:58:29.646465785,2x3.net,256.255.255.0
[email protected],2009-11-27 01:05:47.893000000,xx2.net,127.0.0.1
[email protected],2009-11-27 01:05:47.893000000,xx2.net,127.0.0.1
[email protected],2009-11-27 01:05:47.893000000,xx2.net,127.0.0.1
[email protected],2009-11-27 01:05:47.893000000,xx2.net,127.0.0.1
$ sort test.csv
[email protected],2009-11-27 00:58:29.646465785,2x3.net,256.255.255.0
[email protected],2009-11-27 00:58:29.793000000,xx3.net,255.255.255.0
[email protected],2009-11-27 01:05:47.893000000,xx2.net,127.0.0.1
[email protected],2009-11-27 01:05:47.893000000,xx2.net,127.0.0.1
[email protected],2009-11-27 01:05:47.893000000,xx2.net,127.0.0.1
[email protected],2009-11-27 01:05:47.893000000,xx2.net,127.0.0.1
[email protected],2009-11-27 01:05:47.893000000,xx2.net,127.0.0.1
$ sort test.csv | uniq
[email protected],2009-11-27 00:58:29.646465785,2x3.net,256.255.255.0
[email protected],2009-11-27 00:58:29.793000000,xx3.net,255.255.255.0
[email protected],2009-11-27 01:05:47.893000000,xx2.net,127.0.0.1
[email protected],2009-11-27 01:05:47.893000000,xx2.net,127.0.0.1
[email protected],2009-11-27 01:05:47.893000000,xx2.net,127.0.0.1
You could also do some AWK magic:
$ awk -F, '{ lines[$1] = $0 } END { for (l in lines) print lines[l] }' test.csv
[email protected],2009-11-27 01:05:47.893000000,xx2.net,127.0.0.1
[email protected],2009-11-27 01:05:47.893000000,xx2.net,127.0.0.1
[email protected],2009-11-27 01:05:47.893000000,xx2.net,127.0.0.1
[email protected],2009-11-27 00:58:29.646465785,2x3.net,256.255.255.0
cat 'filename' | grep '[^ ]' | wc -l
should do the trick just fine
awk Version:
awk '/regexp/ { getline; print $0; }' filetosearch
If the items are numerically ordered, use the key() function to determine the index of the current item and compare it to the length. You'd have to use next() or prev() to cycle through items in a while loop instead of a for loop:
$length = sizeOf($arr);
while (key(current($arr)) != $length-1) {
$v = current($arr); doSomething($v); //do something if not the last item
next($myArray); //set pointer to next item
}
No, don't spoil it with a break
. This is the last remaining stronghold for the use of goto
.
In Windows 7 and later, this will do the trick for you
The menu item Copy as Path is not available in Windows XP.
^(0|[1-9][0-9]*)$
It seem like your Resort
method doesn't declare a compareTo
method. This method typically belongs to the Comparable
interface. Make sure your class implements it.
Additionally, the compareTo
method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String
argument, but rather a Resort
.
Alternatively, you can compare the names of the resorts. For example
if (resortList[mid].getResortName().compareTo(resortName)>0)
If the database link option is not available, another route you could take is to link the tables via ODBC to something such as MS Access or Crystal reports and do the join there.
Include this namespace
using System.Net;
Download Asynchronously and put a ProgressBar to show the status of the download within the UI Thread Itself
private void BtnDownload_Click(object sender, RoutedEventArgs e)
{
using (WebClient wc = new WebClient())
{
wc.DownloadProgressChanged += wc_DownloadProgressChanged;
wc.DownloadFileAsync (
// Param1 = Link of file
new System.Uri("http://www.sayka.com/downloads/front_view.jpg"),
// Param2 = Path to save
"D:\\Images\\front_view.jpg"
);
}
}
// Event to track the progress
void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}
Boolean
is threadsafe, so you can consider this factor as well along with all other listed in answers