This works:
''.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))
It will produce:
'abcdgxre'
You can also use a delimiter like a comma to produce:
'a,b,c,d,g,x,r,e'
By using:
','.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))
You are right that CSS positioning is the way to go. Here's a quick run down:
position: relative
will layout an element relative to itself. In other words, the elements is laid out in normal flow, then it is removed from normal flow and offset by whatever values you have specified (top, right, bottom, left). It's important to note that because it's removed from flow, other elements around it will not shift with it (use negative margins instead if you want this behaviour).
However, you're most likely interested in position: absolute
which will position an element relative to a container. By default, the container is the browser window, but if a parent element either has position: relative
or position: absolute
set on it, then it will act as the parent for positioning coordinates for its children.
To demonstrate:
#container {_x000D_
position: relative;_x000D_
border: 1px solid red;_x000D_
height: 100px;_x000D_
}_x000D_
_x000D_
#box {_x000D_
position: absolute;_x000D_
top: 50px;_x000D_
left: 20px;_x000D_
}
_x000D_
<div id="container">_x000D_
<div id="box">absolute</div>_x000D_
</div>
_x000D_
In that example, the top left corner of #box
would be 100px down and 50px left of the top left corner of #container
. If #container
did not have position: relative
set, the coordinates of #box
would be relative to the top left corner of the browser view port.
This is taken from the MVC sample project
@if (ViewBag.ShowRemoveButton)
{
using (Html.BeginForm("RemoveLogin", "Manage"))
{
@Html.AntiForgeryToken()
<div>
@Html.Hidden("company_name", account)
@Html.Hidden("returnUrl", Model.returnUrl)
<input type="submit" class="btn btn-default" value="Remove" title="Remove your email address from @account" />
</div>
}
}
I see some clarification is in order on this. C and C++ do not define types differently. C++ was originally nothing more than an additional set of includes on top of C.
The problem that virtually all C/C++ developers have today, is a) universities are no longer teaching the fundamentals, and b) people don't understand the difference between a definition and a declaration.
The only reason such declarations and definitions exist is so that the linker can calculate address offsets to the fields in the structure. This is why most people get away with code that is actually written incorrectly-- because the compiler is able to determine addressing. The problem arises when someone tries to do something advance, like a queue, or a linked list, or piggying-backing an O/S structure.
A declaration begins with 'struct', a definition begins with 'typedef'.
Further, a struct has a forward declaration label, and a defined label. Most people don't know this and use the forward declaration label as a define label.
Wrong:
struct myStruct
{
int field_1;
...
};
They've just used the forward declaration to label the structure-- so now the compiler is aware of it-- but it isn't an actual defined type. The compiler can calculate the addressing-- but this isn't how it was intended to be used, for reasons I will show momentarily.
People who use this form of declaration, must always put 'struct' in practicly every reference to it-- because it isn't an offical new type.
Instead, any structure that does not reference itself, should be declared and defined this way only:
typedef struct
{
field_1;
...
}myStruct;
Now it's an actual type, and when used you can use at as 'myStruct' without having to prepend it with the word 'struct'.
If you want a pointer variable to that structure, then include a secondary label:
typedef struct
{
field_1;
...
}myStruct,*myStructP;
Now you have a pointer variable to that structure, custom to it.
FORWARD DECLARATION--
Now, here's the fancy stuff, how the forward declaration works. If you want to create a type that refers to itself, like a linked list or queue element, you have to use a forward declaration. The compiler doesn't consider the structure defined until it gets to the semicolon at the very end, so it's just declared before that point.
typedef struct myStructElement
{
myStructElement* nextSE;
field_1;
...
}myStruct;
Now, the compiler knows that although it doesn't know what the whole type is yet, it can still reference it using the forward reference.
Please declare and typedef your structures correctly. There's actually a reason.
This is what The GNU C Library Reference manual says:
You can store the result of
malloc
into any pointer variable without a cast, because ISO C automatically converts the typevoid *
to another type of pointer when necessary. But the cast is necessary in contexts other than assignment operators or if you might want your code to run in traditional C.
And indeed the ISO C11 standard (p347) says so:
The pointer returned if the allocation succeeds is suitably aligned so that it may be assigned to a pointer to any type of object with a fundamental alignment requirement and then used to access such an object or an array of such objects in the space allocated (until the space is explicitly deallocated)
I think all of the answers here cover the core of what the lambda function does in the context of sorted() quite nicely, however I still feel like a description that leads to an intuitive understanding is lacking, so here is my two cents.
For the sake of completeness, I'll state the obvious up front: sorted() returns a list of sorted elements and if we want to sort in a particular way or if we want to sort a complex list of elements (e.g. nested lists or a list of tuples) we can invoke the key argument.
For me, the intuitive understanding of the key argument, why it has to be callable, and the use of lambda as the (anonymous) callable function to accomplish this comes in two parts.
Lambda syntax is as follows:
lambda input_variable(s): tasty one liner
e.g.
In [1]: f00 = lambda x: x/2
In [2]: f00(10)
Out[2]: 5.0
In [3]: (lambda x: x/2)(10)
Out[3]: 5.0
In [4]: (lambda x, y: x / y)(10, 2)
Out[4]: 5.0
In [5]: (lambda: 'amazing lambda')() # func with no args!
Out[5]: 'amazing lambda'
key
argument is that it should take in a set of instructions that will essentially point the 'sorted()' function at those list elements which should used to sort by. When it says key=
, what it really means is: As I iterate through the list one element at a time (i.e. for e in list), I'm going to pass the current element to the function I provide in the key argument and use that to create a transformed list which will inform me on the order of final sorted list. Check it out:
mylist = [3,6,3,2,4,8,23]
sorted(mylist, key=WhatToSortBy)
Base example:
sorted(mylist)
[2, 3, 3, 4, 6, 8, 23] # all numbers are in order from small to large.
Example 1:
mylist = [3,6,3,2,4,8,23]
sorted(mylist, key=lambda x: x%2==0)
[3, 3, 23, 6, 2, 4, 8] # Does this sorted result make intuitive sense to you?
Notice that my lambda function told sorted to check if (e) was even or odd before sorting.
BUT WAIT! You may (or perhaps should) be wondering two things - first, why are my odds coming before my evens (since my key value seems to be telling my sorted function to prioritize evens by using the mod operator in x%2==0
). Second, why are my evens out of order? 2 comes before 6 right? By analyzing this result, we'll learn something deeper about how the sorted() 'key' argument works, especially in conjunction with the anonymous lambda function.
Firstly, you'll notice that while the odds come before the evens, the evens themselves are not sorted. Why is this?? Lets read the docs:
Key Functions Starting with Python 2.4, both list.sort() and sorted() added a key parameter to specify a function to be called on each list element prior to making comparisons.
We have to do a little bit of reading between the lines here, but what this tells us is that the sort function is only called once, and if we specify the key argument, then we sort by the value that key function points us to.
So what does the example using a modulo return? A boolean value: True == 1
, False == 0
. So how does sorted deal with this key? It basically transforms the original list to a sequence of 1s and 0s.
[3,6,3,2,4,8,23] becomes [0,1,0,1,1,1,0]
Now we're getting somewhere. What do you get when you sort the transformed list?
[0,0,0,1,1,1,1]
Okay, so now we know why the odds come before the evens. But the next question is: Why does the 6 still come before the 2 in my final list? Well that's easy - its because sorting only happens once! i.e. Those 1s still represent the original list values, which are in their original positions relative to each other. Since sorting only happens once, and we don't call any kind of sort function to order the original even values from low to high, those values remain in their original order relative to one another.
The final question is then this: How do I think conceptually about how the order of my boolean values get transformed back in to the original values when I print out the final sorted list?
Sorted() is a built-in method that (fun fact) uses a hybrid sorting algorithm called Timsort that combines aspects of merge sort and insertion sort. It seems clear to me that when you call it, there is a mechanic that holds these values in memory and bundles them with their boolean identity (mask) determined by (...!) the lambda function. The order is determined by their boolean identity calculated from the lambda function, but keep in mind that these sublists (of one's and zeros) are not themselves sorted by their original values. Hence, the final list, while organized by Odds and Evens, is not sorted by sublist (the evens in this case are out of order). The fact that the odds are ordered is because they were already in order by coincidence in the original list. The takeaway from all this is that when lambda does that transformation, the original order of the sublists are retained.
So how does this all relate back to the original question, and more importantly, our intuition on how we should implement sorted() with its key argument and lambda?
That lambda function can be thought of as a pointer that points to the values we need to sort by, whether its a pointer mapping a value to its boolean transformed by the lambda function, or if its a particular element in a nested list, tuple, dict, etc., again determined by the lambda function.
Lets try and predict what happens when I run the following code.
mylist = [(3, 5, 8), (6, 2, 8), ( 2, 9, 4), (6, 8, 5)]
sorted(mylist, key=lambda x: x[1])
My sorted
call obviously says, "Please sort this list". The key argument makes that a little more specific by saying, for each element (x) in mylist, return index 1 of that element, then sort all of the elements of the original list 'mylist' by the sorted order of the list calculated by the lambda function. Since we have a list of tuples, we can return an indexed element from that tuple. So we get:
[(6, 2, 8), (3, 5, 8), (6, 8, 5), (2, 9, 4)]
Run that code, and you'll find that this is the order. Try indexing a list of integers and you'll find that the code breaks.
This was a long winded explanation, but I hope this helps to 'sort' your intuition on the use of lambda functions as the key argument in sorted() and beyond.
brew help
will show you the list of commands that are available.
brew list
will show you the list of installed packages. You can also append formulae, for example brew list postgres
will tell you of files installed by postgres (providing it is indeed installed).
brew search <search term>
will list the possible packages that you can install. brew search post
will return multiple packages that are available to install that have post in their name.
brew info <package name>
will display some basic information about the package in question.
You can also search http://searchbrew.com or https://brewformulas.org (both sites do basically the same thing)
You can do this using reprex.
As mt1022 noted, "... good package for producing minimal, reproducible example is "reprex" from tidyverse".
According to Tidyverse:
The goal of "reprex" is to package your problematic code in such a way that other people can run it and feel your pain.
An example is given on tidyverse web site.
library(reprex)
y <- 1:4
mean(y)
reprex()
I think this is the simplest way to create a reproducible example.
In Android Studio 3.5.3, the Device File Explorer can be found in View -> Tool Windows.
It can also be opened using the vertical tabs on the right-hand side of the main window.
Using CSS.
Either inside your <head>
tag (the #search
means "the element with an ID of search
")
<style type="text/css">
input#search
{
width: 20px;
height: 20px;
}
</style>
Or inline, in your <input>
tag
<input type="submit" id="search" value="Search" style="width: 20px; height: 20px;" />
Set up a trap (you can trap several signals with one handler):
signal (SIGQUIT, my_handler); signal (SIGINT, my_handler);
Handle the signal however you want, but be aware of limitations and gotchas:
void my_handler (int sig) { /* Your code here. */ }
i tend to use this calculation a lot in things i make, so i like to add it to the Math object:
Math.dist=function(x1,y1,x2,y2){
if(!x2) x2=0;
if(!y2) y2=0;
return Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
}
Math.dist(0,0, 3,4); //the output will be 5
Math.dist(1,1, 4,5); //the output will be 5
Math.dist(3,4); //the output will be 5
Update:
this approach is especially happy making when you end up in situations something akin to this (i often do):
varName.dist=Math.sqrt( ( (varName.paramX-varX)/2-cx )*( (varName.paramX-varX)/2-cx ) + ( (varName.paramY-varY)/2-cy )*( (varName.paramY-varY)/2-cy ) );
that horrid thing becomes the much more manageable:
varName.dist=Math.dist((varName.paramX-varX)/2, (varName.paramY-varY)/2, cx, cy);
<script language="JavaScript" type="text/javascript">
function HandleBrowseClick()
{
var fileinput = document.getElementById("browse");
fileinput.click();
}
function Handlechange()
{
var fileinput = document.getElementById("browse");
var textinput = document.getElementById("filename");
textinput.value = fileinput.value;
}
</script>
<input type="file" id="browse" name="fileupload" style="display: none" onChange="Handlechange();"/>
<input type="text" id="filename" readonly="true"/>
<input type="button" value="Click to select file" id="fakeBrowse" onclick="HandleBrowseClick();"/>
The issue has been resolved while installation of the maven settings is provided as External in Eclipse. The navigation settings are Window --> Preferences --> Installations. Select the External as installation Type, provide the Installation home and name and click on Finish. Finally select this as default installations.
Just for fun, consider the different question one would get with a very literal interpretation of the OP's description: "Write a query to print the list of names of students who have scored the maximum mark in each subject."
Those who've answered here have written queries to list a student if he or she scored the maximum mark in any one subject, but not necessarily in all subjects. Since the question posed by the OP does not ask for subject names in the output, this is a plausible interpretation.
To list the names of students (if any) who have scored the maximum mark in all subjects (excluding subjects with no marks, since arguably there is then no maximum mark then), I think this works, using column names from Michael's SQL Fiddle, which I've adapted here.
select StudentName
from Student
where not exists (
select * from Subject
where exists (
select * from Mark as M1
where M1.SubjectID = Subject.SubjectID
and M1.StudentID <> Student.StudentID
and not exists (
select * from Mark as M2
where M2.StudentID = Student.StudentID
and M2.SubjectID = M1.SubjectID
and M2.MarkRate >= M1.MarkRate
)
)
)
In other words, select a student X's name if there is no subject in which someone's mark for that subject is not matched or exceeded by some mark belonging to X for the same subject. (This query returns a student's name if the student has received more than one mark in a subject, so long as one of those marks is the highest for the subject.)
I was looking for the same thing and I just found this list
The answer is right, but it will add a listener that will be triggered every time a click occurs on your page. To avoid that, you can add the listener for just one time :
$('a#menu-link').on('click', function(e) {
e.preventDefault();
e.stopPropagation();
$('#menu').toggleClass('open');
$(document).one('click', function closeMenu (e){
if($('#menu').has(e.target).length === 0){
$('#menu').removeClass('open');
} else {
$(document).one('click', closeMenu);
}
});
});
Edit: if you want to avoid the stopPropagation()
on the initial button you can use this
var $menu = $('#menu');
$('a#menu-link').on('click', function(e) {
e.preventDefault();
if (!$menu.hasClass('active')) {
$menu.addClass('active');
$(document).one('click', function closeTooltip(e) {
if ($menu.has(e.target).length === 0 && $('a#menu-link').has(e.target).length === 0) {
$menu.removeClass('active');
} else if ($menu.hasClass('active')) {
$(document).one('click', closeTooltip);
}
});
} else {
$menu.removeClass('active');
}
});
public void getClientNameDropDowndata()
{
getConnection = Connection.SetConnection(); // to connect with data base Configure manager
string ClientName = "Select ClientName from Client ";
SqlCommand ClientNameCommand = new SqlCommand(ClientName, getConnection);
ClientNameCommand.CommandType = CommandType.Text;
SqlDataReader ClientNameData;
ClientNameData = ClientNameCommand.ExecuteReader();
if (ClientNameData.HasRows)
{
DropDownList_ClientName.DataSource = ClientNameData;
DropDownList_ClientName.DataValueField = "ClientName";
DropDownList_ClientName.DataTextField="ClientName";
DropDownList_ClientName.DataBind();
}
else
{
MessageBox.Show("No is found");
CloseConnection = new Connection();
CloseConnection.closeConnection(); // close the connection
}
}
@RequestMapping(value = "/books", method = { RequestMethod.GET,
RequestMethod.POST })
public ModelAndView listBooks(@ModelAttribute("booksFilter") BooksFilter filter,
HttpServletRequest request)
throws ParseException {
//your code
}
This will works for both GET and POST.
For GET if your pojo(BooksFilter) have to contain the attribute which you're using in request parameter
like below
public class BooksFilter{
private String parameter1;
private String parameter2;
//getters and setters
URl should be like below
/books?parameter1=blah
Like this way u can use it for both GET and POST
If you want to stick with java.util.Timer
, you can use it to schedule at large time intervals. You simply pass in the period you are shooting for. Check the documentation here.
You need to run it using bash
executable like this:
Runtime.getRuntime().exec("/bin/bash -c your_command");
Update: As suggested by xav, it is advisable to use ProcessBuilder instead:
String[] args = new String[] {"/bin/bash", "-c", "your_command", "with", "args"};
Process proc = new ProcessBuilder(args).start();
1) Hold Control+ left click on the method you want to see. Then Eclipse will bring you to the Source Not Found page.
4) Navigate to C:\Program Files\Java\jdk-9.0.1\lib\src.zip
You can use array_walk
to apply your preg_match
function to each element of the array.
Note that on OS X, sed -i <pattern> file
, fails. However, if you provide a backup extension, sed -i old <pattern> file
, then file
is modified in place while file.old
is created. You can then delete file.old
in your script.
for me DATENAME was not accessable due to company restrictions.... but this worked very easy too.
FORMAT(date, 'MMMM') AS month
As I read your question, I have tried without success to search on the Internet how Bearer tokens are encrypted or signed. I guess bearer tokens are not hashed (maybe partially, but not completely) because in that case, it will not be possible to decrypt it and retrieve users properties from it.
But your question seems to be trying to find answers on Bearer token functionality:
Suppose I am implementing an authorization provider, can I supply any kind of string for the bearer token? Can it be a random string? Does it has to be a base64 encoding of some attributes? Should it be hashed?
So, I'll try to explain how Bearer tokens and Refresh tokens work:
When user requests to the server for a token sending user and password through SSL, the server returns two things: an Access token and a Refresh token.
An Access token is a Bearer token that you will have to add in all request headers to be authenticated as a concrete user.
Authorization: Bearer <access_token>
An Access token is an encrypted string with all User properties, Claims and Roles that you wish. (You can check that the size of a token increases if you add more roles or claims). Once the Resource Server receives an access token, it will be able to decrypt it and read these user properties. This way, the user will be validated and granted along with all the application.
Access tokens have a short expiration (ie. 30 minutes). If access tokens had a long expiration it would be a problem, because theoretically there is no possibility to revoke it. So imagine a user with a role="Admin" that changes to "User". If a user keeps the old token with role="Admin" he will be able to access till the token expiration with Admin rights. That's why access tokens have a short expiration.
But, one issue comes in mind. If an access token has short expiration, we have to send every short period the user and password. Is this secure? No, it isn't. We should avoid it. That's when Refresh tokens appear to solve this problem.
Refresh tokens are stored in DB and will have long expiration (example: 1 month).
A user can get a new Access token (when it expires, every 30 minutes for example) using a refresh token, that the user had received in the first request for a token. When an access token expires, the client must send a refresh token. If this refresh token exists in DB, the server will return to the client a new access token and another refresh token (and will replace the old refresh token by the new one).
In case a user Access token has been compromised, the refresh token of that user must be deleted from DB. This way the token will be valid only till the access token expires because when the hacker tries to get a new access token sending the refresh token, this action will be denied.
Here is a workaround using a flag:
//outside your event or method, but inside your class
private bool IsExecuted = false;
private async Task MethodA()
{
//Do Stuff Here
IsExecuted = true;
}
.
.
.
//Inside your event or method
{
await MethodA();
while (!isExecuted) Thread.Sleep(200); // <-------
await MethodB();
}
Simple: [boolean](get-variable "Varname" -ErrorAction SilentlyContinue)
See svn diff
in the manual:
svn diff -r 8979:11390 http://svn.collab.net/repos/svn/trunk/fSupplierModel.php
I typically do this sort of thing by defining a custom [Serializable
] settings class and simply serializing it to disk. In your case you could just as easily store it as a string blob in your SQLite database.
In English:
ContentType
: When sending data to the server, use this content type. Default is application/x-www-form-urlencoded; charset=UTF-8
, which is fine for most cases.Accepts
: The content type sent in the request header that tells the server what kind of response it will accept in return. Depends on DataType
.DataType
: The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response. Can be text, xml, html, script, json, jsonp
.It selects all elements where the class name contains the string "span"
somewhere. There's also ^=
for the beginning of a string, and $=
for the end of a string. Here's a good reference for some CSS selectors.
I'm only familiar with the bootstrap classes spanX
where X is an integer, but if there were other selectors that ended in span
, it would also fall under these rules.
It just helps to apply blanket CSS rules.
To be honest I have to add my 2 cents.
You can do it with msbuild.exe. There are many version of the msbuild.exe.
C:\Windows\Microsoft.NET\Framework64\v2.0.50727\msbuild.exe C:\Windows\Microsoft.NET\Framework64\v3.5\msbuild.exe C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe
C:\Windows\Microsoft.NET\Framework\v2.0.50727\msbuild.exe C:\Windows\Microsoft.NET\Framework\v3.5\msbuild.exe C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe
Use version you need. Basically you have to use the last one.
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe
So how to do it.
Run the COMMAND window
Input the path to msbuild.exe
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe
"C:\Users\Clark.Kent\Documents\visual studio 2012\Projects\WpfApplication1\WpfApplication1.sln"
Add any flags you need after the solution path.
Press ENTER
Note you can get help about all possible flags like
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe /help
I believe this is the easiest way to do it, also possible using through the inline style
attribute within the <img>
tag.
.scaled
{
transform: scale(0.7); /* Equal to scaleX(0.7) scaleY(0.7) */
}
<img src="flower.png" class="scaled">
or
<img src="flower.png" style="transform: scale(0.7);">
For XAMMP versions >=7.5.9-0 also change the DocumentRoot in file "/opt/lampp/etc/extra/httpd-ssl.conf" accordingly.
Since these are member functions, call it as a member function on the instance, self
.
def isNear(self, p):
self.distToPoint(p)
...
Since Jackson is being used, you have to configure that as a Jackson property. In the case of Spring Boot REST services, you have to configure it in application.properties
or application.yml
:
spring.jackson.default-property-inclusion = NON_NULL
Best and the simple way of doing is :
Just use the default way from Sequelize
db.Sensors.findAll({
where: {
nodeid: node.nodeid
},
raw : true // <----------- Magic is here
}).success(function (sensors) {
console.log(sensors);
});
Note : [options.raw] : Return raw result. See sequelize.query for more information.
For the nested result/if we have include model , In latest version of sequlize ,
db.Sensors.findAll({
where: {
nodeid: node.nodeid
},
include : [
{ model : someModel }
]
raw : true , // <----------- Magic is here
nest : true // <----------- Magic is here
}).success(function (sensors) {
console.log(sensors);
});
Consider the following situation:
You are in the middle of a large, empty room, when a zombie suddenly attacks you.
You have no weapon.
Luckily, a fellow living human is standing in the doorway of the room.
"Quick!" you shout at him. "Throw me something I can hit the zombie with!"
Now consider:
You didn't specify (nor do you care) exactly what your friend will choose to toss;
...But it doesn't matter, as long as:
It's something that can be tossed (He can't toss you the sofa)
It's something that you can grab hold of (Let's hope he didn't toss a shuriken)
It's something you can use to bash the zombie's brains out (That rules out pillows and such)
It doesn't matter whether you get a baseball bat or a hammer -
as long as it implements your three conditions, you're good.
To sum it up:
When you write an interface, you're basically saying: "I need something that..."
Easiest way is probably
pip3 -V
This will show you where your pip is installed and therefore where your packages are located.
Using LINQ to xml if you are using framework 3.5:
using System.Xml.Linq;
XDocument xmlFile = XDocument.Load("books.xml");
var query = from c in xmlFile.Elements("catalog").Elements("book")
select c;
foreach (XElement book in query)
{
book.Attribute("attr1").Value = "MyNewValue";
}
xmlFile.Save("books.xml");
Contrary to one of the other answers - I had the problem on push using ssh - I switched to https and it was fixed.
git remote remove origin
git remote add origin https://github..com/user/repo
git push --set-upstream origin master
In recent version, The following works fine:
$('.selector').datetimepicker({
maxDate: new Date()
});
maxDate
accepts a Date object as parameter.
The following found in documentation:
Multiple types supported:
Date: A date object containing the minimum date.
Number: A number of days from today. For example 2 represents two days from today and -1 represents yesterday.
String: A string in the format defined by the dateFormat option, or a relative date. Relative dates must contain value and period pairs; valid periods are "y" for years, "m" for months, "w" for weeks, and "d" for days. For example, "+1m +7d" represents one month and seven days from today.
In case of someone else is doing it in Python and it is not working, try to set it before do the imports of pycuda and tensorflow.
I.e.:
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
...
import pycuda.autoinit
import tensorflow as tf
...
As saw here.
foreach (DataRow row in myDataTable.Rows)
{
Console.WriteLine(row["ImagePath"]);
}
I am writing this from memory.
Hope this gives you enough hint to understand the object model.
DataTable
-> DataRowCollection
-> DataRow
(which one can use & look for column contents for that row, either using columnName or ordinal).
-> = contains.
Please check your app.json file in project. if there has not line appKey then you must add it
{
"expo": {
"sdkVersion": "27.0.0",
"appKey": "mydojo"
},
"name": "mydojo",
"displayName": "mydojo"
}
You don't need JavaScript for this. You can change the cursor to anything you want using CSS :
selector {
cursor: url(myimage.jpg), auto;
}
See here for browser support as there are some subtle differences depending on browser
Here's my script that runs as LocalSystem on a machine, but needs credentials of a domaim user to access a network file location. It allows you to store the user's password in a "safe-ish" encrypted file; that can only be read by the user that wrote it.
Setting and changing the password is done by copying a file with the plaintext password in it to the machine. When the script is next run it reads the password, encrypts it, then deletes the plaintext password.
$plaintext_password_file = 'C:\plaintext.txt' # Stores the password in plain text - only used once, then deleted
$encryted_password_file = 'C:\copy_pass.txt' # Stores the password in "safe" encrypted form - used for subsequent runs of the script
# - can only be decrypted by the windows user that wrote it
$file_copy_user = 'OURDOMAIN\A_User'
# Check to see if there is a new plaintext password
if (Test-Path $plaintext_password_file)
{
# Read in plaintext password, convert to a secure-string, convert to an encrypted-string, and write out, for use later
get-content $plaintext_password_file | convertto-securestring -asplaintext -force | convertfrom-securestring | out-file $encryted_password_file
# Now we have encrypted password, remove plain text for safety
Remove-Item $plaintext_password_file
}
# Read in the encrypted password, convert to a secure-string
$pass = get-content $encryted_password_file | convertto-securestring
# create a credential object for the other user, using username and password stored in secure-string
$credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist $file_copy_user,$pass
# Connect to network file location as the other user and map to drive J:
New-PSDrive -Name J -PSProvider FileSystem -Root "\\network\file_directory" -Credential $credentials
# Copy the file to J:
Copy-Item -Force -Verbose -Path "C:\a_file.txt" -Destination "J:\"
As an extra refinement: The username could also be encrypted as well, rather than hardcoded.
Add my two cents, if you're using windows commnad line:
git config --list | findstr user.name
will give username directly.
The findstr
here is quite similar to grep
in linux.
In your case you are having model on same page, but you have it declared after your Component class, so that's you need to use forwardRef
to refer to Class
. Don't prefer to do this, always have model
object in separate file.
export class testWidget {
constructor(@Inject(forwardRef(() => Model)) private service: Model) {}
}
Additionally you have to change you view interpolation to refer to correct object
{{model?.param1}}
Better thing you should do is, you can have your Model
Class define in different file & then import it as an when you require it by doing. Also have export
before you class name, so that you can import it.
import { Model } from './model';
<select name=protect_email size=1 style="background: #009966; color: #FFF;" onChange="this.style.backgroundColor=this.options[this.selectedIndex].style.backgroundColor">
<option value=0 style="background: #009966; color: #FFF;" selected>Protect my email</option>;
<option value=1 style="background: #FF0000; color: #FFF;">Show email on advert</option>;
</select>;
http://pro.org.uk/classified/Directory?act=book&category=120
Tested it in FF,Opera,Konqueror worked fine...
Customizing CORS for Angular 5 and Spring Security (Cookie base solution)
On the Angular side required adding option flag withCredentials: true
for Cookie transport:
constructor(public http: HttpClient) {
}
public get(url: string = ''): Observable<any> {
return this.http.get(url, { withCredentials: true });
}
On Java server-side required adding CorsConfigurationSource
for configuration CORS policy:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
// This Origin header you can see that in Network tab
configuration.setAllowedOrigins(Arrays.asList("http:/url_1", "http:/url_2"));
configuration.setAllowedMethods(Arrays.asList("GET","POST"));
configuration.setAllowedHeaders(Arrays.asList("content-type"));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and()...
}
}
Method configure(HttpSecurity http)
by default will use corsConfigurationSource
for http.cors()
Didn't use eclipse for a while, but there are ATF and Aptana.
If you are writing a web app or single page application (SPA) where routing takes place in the app/browser rather than a round-trip to the server, you can do the following:
window.history.pushState({ prevUrl: window.location.href }, null, "/new/path/in/your/app")
Then, in your new route, you can do the following to retrieve the previous URL:
window.history.state.prevUrl // your previous url
<Image Source="MyRessourceDir\images\addButton.png"/>
You should use POST if there is a lot of data, or sort-of sensitive information (really sensitive stuff needs a secure connection as well).
Use GET if you want people to be able to bookmark your page, because all the data is included with the bookmark.
Just be careful of people hitting REFRESH with the GET method, because the data will be sent again every time without warning the user (POST sometimes warns the user about resending data).
A Python 2+3 compatible solution is:
import sys
if sys.version_info[0] >= 3:
from urllib.request import urlretrieve
else:
# Not Python 3 - today, it is most likely to be Python 2
# But note that this might need an update when Python 4
# might be around one day
from urllib import urlretrieve
# Get file from URL like this:
urlretrieve("http://www-scf.usc.edu/~chiso/oldspice/m-b1-hello.mp3")
When you use git push origin :staleStuff
, it automatically removes origin/staleStuff
, so when you ran git remote prune origin
, you have pruned some branch that was removed by someone else. It's more likely that your co-workers now need to run git prune
to get rid of branches you have removed.
So what exactly git remote prune
does? Main idea: local branches (not tracking branches) are not touched by git remote prune
command and should be removed manually.
Now, a real-world example for better understanding:
You have a remote repository with 2 branches: master
and feature
. Let's assume that you are working on both branches, so as a result you have these references in your local repository (full reference names are given to avoid any confusion):
refs/heads/master
(short name master
)refs/heads/feature
(short name feature
)refs/remotes/origin/master
(short name origin/master
)refs/remotes/origin/feature
(short name origin/feature
)Now, a typical scenario:
feature
, merges it into master
and removes feature
branch from remote repository.git fetch
(or git pull
), no references are removed from your local repository, so you still have all those 4 references.git remote prune origin
.feature
branch no longer exists, so refs/remotes/origin/feature
is a stale branch which should be removed. refs/heads/feature
, because git remote prune
does not remove any refs/heads/*
references.It is possible to identify local branches, associated with remote tracking branches, by branch.<branch_name>.merge
configuration parameter. This parameter is not really required for anything to work (probably except git pull
), so it might be missing.
(updated with example & useful info from comments)
No-one of safe solution work for me so to be safer than Neeraj and easier than Matthew just add:
System.Web.HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
In your controller's method. That work for me.
public IHttpActionResult Get()
{
System.Web.HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
return Ok("value");
}
Case: If you need to ignore the merge commit created by default, follow these steps.
Say, a new feature branch is checked out from master having 2 commits already,
Checkout a new feature_branch
Feature branch then adds two commits-->
Now if you want to merge feature_branch changes to master, Do git merge feature_branch
sitting on the master.
This will add all commits into master branch (4 in master + 2 in feature_branch = total 6) + an extra merge commit something like 'Merge branch 'feature_branch'
' as the master is diverged.
If you really need to ignore these commits (those made in FB) and add the whole changes made in feature_branch as a single commit like 'Integrated feature branch changes into master'
, Run git merge feature_merge --no-commit
.
With --no-commit, it perform the merge and stop just before creating a merge commit, We will have all the added changes in feature branch now in master and get a chance to create a new commit as our own.
Read here for more : https://git-scm.com/docs/git-merge
A other users suggested,
.empty()
is good enought, because it removes all descendant nodes (both tag-nodes and text-nodes) AND all kind of data stored inside those nodes. See the JQuery's API empty documentation.
If you wish to keep data, like event handlers for example, you should use
.detach()
as described on the JQuery's API detach documentation.
The method .remove() could be usefull for similar purposes.
An update to i00g's and Thomas' answers, this time for VS2012 (some names have changed). After copying x86 settings over into an x64 target with the configuration manager, you'll have the problem for the same reason as was the case earlier (lib targets aren't correct in the x64 config). Open your .vcxproj (text editor) and replace MachineX86 with MachineX64 where appropriate. (I still haven't found where this is on the property sheets....) This only seems to be necessary with static libs.
For people using Tiny Core Linux, you also need to install libtool-dev
as it has the *.m4 files needed for libtoolize
.
HTML doesn't have escape characters (as it doesn't use escape-semantics for reserved characters, instead you use SGML entities: &
, <
, >
and "
).
SGML does not have a named-entity for the tab character as it exists in most character sets (i.e. 0x09
in ASCII and UTF-8), rendering it completely unnecessary (i.e. simply press the Tab key on your keyboard). If you're working with code that generates HTML (e.g. a server-side application, e.g. ASP.NET, PHP or Perl, then you might need to escape it then, but only because the server-side language demands it - it has nothing to do with HTML, like so:
echo "<pre>\t\tTABS!\t\t</pre>";
But, you can use SGML entities to represent any ISO-8859-1 character by hexadecimal value, e.g. 	
for a tab character.
Accordling with cl-sah's answer, but this sound better, shorter...
function checkmydate($date) {
$tempDate = explode('-', $date);
return checkdate($tempDate[1], $tempDate[2], $tempDate[0]);
}
Test
checkmydate('2015-12-01');//true
checkmydate('2015-14-04');//false
RHEL and derivatives typically ship older versions of git. You can download a tarball and build from source, or use a 3rd-party repository such as the IUS Community Project to obtain a more recent version of git.
there is good tutorial here. in my case (Centos7 server) after install had to logout and login again.
jQuery.val() and .text() will never return 'undefined' for an empty selection. It always returns an empty string (i.e. ""). .html() will return null if the element doesn't exist though.You need to do:
if(page_name != '')
For other variables that don't come from something like jQuery.val() you would do this though:
if(typeof page_name != 'undefined')
You just have to use the typeof
operator.
You can use RETURNING id after insert query.
INSERT INTO distributors (id, name) VALUES (DEFAULT, 'ALI') RETURNING id;
and result:
id
----
1
In the above example id is auto-increment filed.
This should do it:
import (
"fmt"
"log"
"os"
"path/filepath"
)
func main() {
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
log.Fatal(err)
}
fmt.Println(dir)
}
You could use the Firefox add-on User Agent Overrider. With this add-on you can use whatever user agent you want, for examlpe:
Firefox 28/Android: Mozilla/5.0 (Android; Mobile; rv:28.0) Gecko/24.0 Firefox/28.0
If your website detects mobile devices through the user agent then you can test your layout this way.
Update Nov '17:
Due to the release of Firefox 57 and the introduction of web extension this add-on sadly is no longer available. Alternatively you can edit the Firefox preference general.useragent.override
in your configuration:
about:config
general.useragent.override
Use ROUND
but with num_digits
= -1
=ROUND(A1,-1)
Also applies to ROUNDUP
and ROUNDDOWN
From Excel help:
EDIT:
To get the numbers to always round up use =ROUNDUP(A1,-1)
I know it's been eight years but I wanted to share this piece of code found in MRuby that shows how __declspec()
can bee used at the same level as the export keyword
.
/** Declare a public MRuby API function. */
#if defined(MRB_BUILD_AS_DLL)
#if defined(MRB_CORE) || defined(MRB_LIB)
# define MRB_API __declspec(dllexport)
#else
# define MRB_API __declspec(dllimport)
#endif
#else
# define MRB_API extern
#endif
For some picky web services, the request needs to have the content type set to JSON and the body to be a JSON string. For example:
Invoke-WebRequest -UseBasicParsing http://example.com/service -ContentType "application/json" -Method POST -Body "{ 'ItemID':3661515, 'Name':'test'}"
or the equivalent for XML, etc.
To Create the new certificate for your specific domain:
Open Powershell ISE as admin, run the command:
New-SelfSignedCertificate -DnsName *.mydomain.com, localhost -CertStoreLocation cert:\LocalMachine\My
To trust the new certificate:
To bind the certificate to your site:
Have a look at commons. It uses arrayCopy(), but has nicer syntax. To those answering with the element-by-element code: if this isn't homework, that's trivial and the interesting answer is the one that promotes reuse. To those who propose lists: probably readers know about that too and performance issues should be mentioned.
If you're using Google Maps v2, call checkResize()
on your map after resizing the container. link
UPDATE
Google Maps JavaScript API v2 was deprecated in 2011. It is not available anymore.
To copy whole datatable just do this:
DataGridView sourceGrid = this.dataGridView1;
DataGridView targetGrid = this.dataGridView2;
targetGrid.DataSource = sourceGrid.DataSource;
It depends on the host, but you probably simply can't (you can't on my shared host on Rackspace Cloud Sites - I asked them).
What you can do is set up an environment on your dev machine that roughly matches your shared host, and do all of your management through the command line locally. Then when everything is set (you've pulled in all the dependencies, updated, managed with git, etc.) you can "push" that to your shared host over (s)FTP.
What about npm i -g npm
? Did you try to run this as well?
Method that works nicely in Safari. Also works in Firefox and Opera, but with a warning.
Location: http://[email protected]/
This tells browser to open URL with new username, overriding previous one.
Rectangle bounds = Screen.GetBounds(Point.Empty);
using(Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
{
using(Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
}
bitmap.Save("test.jpg", ImageFormat.Jpeg);
}
for capturing current window use
Rectangle bounds = this.Bounds;
using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(new Point(bounds.Left,bounds.Top), Point.Empty, bounds.Size);
}
bitmap.Save("C://test.jpg", ImageFormat.Jpeg);
}
useHistory
hook:If you have React >= 16.8
and functional components you can use the useHistory
hook from react-router.
import React from 'react';
import { useHistory } from 'react-router-dom';
const YourComponent = () => {
const history = useHistory();
const handleClick = () => {
history.push("/path/to/push");
}
return (
<div>
<button onClick={handleClick} type="button" />
</div>
);
}
export default YourComponent;
withRouter
HOC:As @ambar mentioned in the comments, React-router has changed their code base since their V4. Here are the documentations - official, withRouter
import React, { Component } from 'react';
import { withRouter } from "react-router-dom";
class YourComponent extends Component {
handleClick = () => {
this.props.history.push("path/to/push");
}
render() {
return (
<div>
<button onClick={this.handleClick} type="button">
</div>
);
};
}
export default withRouter(YourComponent);
browserHistory
You can achieve this functionality using react-router BrowserHistory
. Code below:
import React, { Component } from 'react';
import { browserHistory } from 'react-router';
export default class YourComponent extends Component {
handleClick = () => {
browserHistory.push('/login');
};
render() {
return (
<div>
<button onClick={this.handleClick} type="button">
</div>
);
};
}
connected-react-router
If you have connected your component with redux, and have configured connected-react-router all you have to do is
this.props.history.push("/new/url");
ie, you don't need withRouter
HOC to inject history
to the component props.
// reducers.js
import { combineReducers } from 'redux';
import { connectRouter } from 'connected-react-router';
export default (history) => combineReducers({
router: connectRouter(history),
... // rest of your reducers
});
// configureStore.js
import { createBrowserHistory } from 'history';
import { applyMiddleware, compose, createStore } from 'redux';
import { routerMiddleware } from 'connected-react-router';
import createRootReducer from './reducers';
...
export const history = createBrowserHistory();
export default function configureStore(preloadedState) {
const store = createStore(
createRootReducer(history), // root reducer with router state
preloadedState,
compose(
applyMiddleware(
routerMiddleware(history), // for dispatching history actions
// ... other middlewares ...
),
),
);
return store;
}
// set up other redux requirements like for eg. in index.js
import { Provider } from 'react-redux';
import { Route, Switch } from 'react-router';
import { ConnectedRouter } from 'connected-react-router';
import configureStore, { history } from './configureStore';
...
const store = configureStore(/* provide initial state if any */)
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}>
<> { /* your usual react-router v4/v5 routing */ }
<Switch>
<Route exact path="/yourPath" component={YourComponent} />
</Switch>
</>
</ConnectedRouter>
</Provider>,
document.getElementById('root')
);
// YourComponent.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
...
class YourComponent extends Component {
handleClick = () => {
this.props.history.push("path/to/push");
}
render() {
return (
<div>
<button onClick={this.handleClick} type="button">
</div>
);
}
};
}
export default connect(mapStateToProps = {}, mapDispatchToProps = {})(YourComponent);
I think returning 0 for succ/1 for fail (glenn jackman) and olibre's clear and explanatory answer says it all; just to mention a kind of "combo" approach for cases where results are not binary and you'd prefer to set a variable rather than "echoing out" a result (for instance if your function is ALSO suppose to echo something, this approach will not work). What then? (below is Bourne Shell)
# Syntax _w (wrapReturn)
# arg1 : method to wrap
# arg2 : variable to set
_w(){
eval $1
read $2 <<EOF
$?
EOF
eval $2=\$$2
}
as in (yep, the example is somewhat silly, it's just an.. example)
getDay(){
d=`date '+%d'`
[ $d -gt 255 ] && echo "Oh no a return value is 0-255!" && BAIL=0 # this will of course never happen, it's just to clarify the nature of returns
return $d
}
dayzToSalary(){
daysLeft=0
if [ $1 -lt 26 ]; then
daysLeft=`expr 25 - $1`
else
lastDayInMonth=`date -d "`date +%Y%m01` +1 month -1 day" +%d`
rest=`expr $lastDayInMonth - 25`
daysLeft=`expr 25 + $rest`
fi
echo "Mate, it's another $daysLeft days.."
}
# main
_w getDay DAY # call getDay, save the result in the DAY variable
dayzToSalary $DAY
If you are on MEAN (Mongo-Express-AngularJS-Node) stack, run mongod first, and this error message will go away.
If you are in a scenario where you are using one of the latest versions of Ubuntu (or variants like Linux Mint), one which comes with Python 3.8, then you will NOT be able to have Python3.7 distutils
, alias not be able to use pip
or pipenv
with Python 3.7, see:
How to install python-distutils for old python versions
Obviously using Python3.8 is no problem.
The problem is that dataTable
is not defined at the point you are calling this method.
Ensure that you are loading the .js
files in the correct order:
<script src="/Scripts/jquery.dataTables.js"></script>
<script src="/Scripts/dataTables.bootstrap.js"></script>
Sounds like there is something wrong with your configuration, here are a few things you can check:
Make sure that PHP is installed and running correctly. This may sound silly, but you never know. An easy way to check is to run php -v
from a command line and see if returns version information or any errors.
Make sure that the PHP module is listed and uncommented inside of your Apache's httpd.conf This should be something like LoadModule php5_module "c:/php/php5apache2_2.dll"
in the file. Search for LoadModule php
, and make sure that there is no comment (;
) in front of it.
Make sure that Apache's httpd.conf file has the PHP MIME type in it. This should be something like AddType application/x-httpd-php .php
. This tells Apache to run .php
files as PHP. Search for AddType, and then make sure there is an entry for PHP, and that it is uncommented.
Make sure your file has the .php
extension on it, or whichever extension specified in the MIME definition in point #3, otherwise it will not be executed as PHP.
Make sure you are not using short tags in the PHP file (<?
), these are not enabled on all servers by default and their use is discouraged. Use <?php
instead (or enable short tags in your php.ini with short_open_tag=On
if you have code that relies on them).
Make sure you are accessing your file over your webserver using an URL like http://localhost/file.php
not via local file access file://localhost/www/file.php
And lastly check the PHP manual for further setup tips.
Style
svg path {
fill: #000;
}
Script
$(document).ready(function() {
$('img[src$=".svg"]').each(function() {
var $img = jQuery(this);
var imgURL = $img.attr('src');
var attributes = $img.prop("attributes");
$.get(imgURL, function(data) {
// Get the SVG tag, ignore the rest
var $svg = jQuery(data).find('svg');
// Remove any invalid XML tags
$svg = $svg.removeAttr('xmlns:a');
// Loop through IMG attributes and apply on SVG
$.each(attributes, function() {
$svg.attr(this.name, this.value);
});
// Replace IMG with SVG
$img.replaceWith($svg);
}, 'xml');
});
});
The working version of your code (from the errors pointed out by BoltClock):
<?php
$date = '2011-01-01';
$timestamp = strtotime($date);
$weekday= date("l", $timestamp );
$normalized_weekday = strtolower($weekday);
echo $normalized_weekday ;
if (($normalized_weekday == "saturday") || ($normalized_weekday == "sunday")) {
echo "true";
} else {
echo "false";
}
?>
The stray "{" is difficult to see, especially without a decent PHP editor (in my case). So I post the corrected version here.
java.lang.UnsupportedClassVersionError
happens because of a higher JDK during compile time and lower JDK during runtime.
Here's the list of versions:
Java SE 9 = 53,
Java SE 8 = 52,
Java SE 7 = 51,
Java SE 6.0 = 50,
Java SE 5.0 = 49,
JDK 1.4 = 48,
JDK 1.3 = 47,
JDK 1.2 = 46,
JDK 1.1 = 45
As I did not find a proper way I wrote a script to do it and I'm sharing it here for those who need it. The script runs through all user tables and collects the columns. If the column type is any char type then it tries to convert it to the given collation.
Columns has to be index and constraint free for this to work.
If someone still has a better solution to this please post it!
DECLARE @collate nvarchar(100);
DECLARE @table nvarchar(255);
DECLARE @column_name nvarchar(255);
DECLARE @column_id int;
DECLARE @data_type nvarchar(255);
DECLARE @max_length int;
DECLARE @row_id int;
DECLARE @sql nvarchar(max);
DECLARE @sql_column nvarchar(max);
SET @collate = 'Latin1_General_CI_AS';
DECLARE local_table_cursor CURSOR FOR
SELECT [name]
FROM sysobjects
WHERE OBJECTPROPERTY(id, N'IsUserTable') = 1
OPEN local_table_cursor
FETCH NEXT FROM local_table_cursor
INTO @table
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE local_change_cursor CURSOR FOR
SELECT ROW_NUMBER() OVER (ORDER BY c.column_id) AS row_id
, c.name column_name
, t.Name data_type
, c.max_length
, c.column_id
FROM sys.columns c
JOIN sys.types t ON c.system_type_id = t.system_type_id
LEFT OUTER JOIN sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
LEFT OUTER JOIN sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
WHERE c.object_id = OBJECT_ID(@table)
ORDER BY c.column_id
OPEN local_change_cursor
FETCH NEXT FROM local_change_cursor
INTO @row_id, @column_name, @data_type, @max_length, @column_id
WHILE @@FETCH_STATUS = 0
BEGIN
IF (@max_length = -1) OR (@max_length > 4000) SET @max_length = 4000;
IF (@data_type LIKE '%char%')
BEGIN TRY
SET @sql = 'ALTER TABLE ' + @table + ' ALTER COLUMN ' + @column_name + ' ' + @data_type + '(' + CAST(@max_length AS nvarchar(100)) + ') COLLATE ' + @collate
PRINT @sql
EXEC sp_executesql @sql
END TRY
BEGIN CATCH
PRINT 'ERROR: Some index or constraint rely on the column' + @column_name + '. No conversion possible.'
PRINT @sql
END CATCH
FETCH NEXT FROM local_change_cursor
INTO @row_id, @column_name, @data_type, @max_length, @column_id
END
CLOSE local_change_cursor
DEALLOCATE local_change_cursor
FETCH NEXT FROM local_table_cursor
INTO @table
END
CLOSE local_table_cursor
DEALLOCATE local_table_cursor
GO
Yes, you could use a transparent div positioned over the iframe area, with a loader gif as only background.
Then you can attach an onload
event to the iframe:
$(document).ready(function() {
$("iframe#id").load(function() {
$("#loader-id").hide();
});
});
If you want to use Java 8 streams and are allergic to while
loops, you could try this:
public static int countPattern(String references, Pattern referencePattern) {
Matcher matcher = referencePattern.matcher(references);
return Stream.iterate(0, i -> i + 1)
.filter(i -> !matcher.find())
.findFirst()
.get();
}
Disclaimer: this only works for disjoint matches.
Example:
public static void main(String[] args) throws ParseException {
Pattern referencePattern = Pattern.compile("PASSENGER:\\d+");
System.out.println(countPattern("[ \"PASSENGER:1\", \"PASSENGER:2\", \"AIR:1\", \"AIR:2\", \"FOP:2\" ]", referencePattern));
System.out.println(countPattern("[ \"AIR:1\", \"AIR:2\", \"FOP:2\" ]", referencePattern));
System.out.println(countPattern("[ \"AIR:1\", \"AIR:2\", \"FOP:2\", \"PASSENGER:1\" ]", referencePattern));
System.out.println(countPattern("[ ]", referencePattern));
}
This prints out:
2
0
1
0
This is a solution for disjoint matches with streams:
public static int countPattern(String references, Pattern referencePattern) {
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
new Iterator<Integer>() {
Matcher matcher = referencePattern.matcher(references);
int from = 0;
@Override
public boolean hasNext() {
return matcher.find(from);
}
@Override
public Integer next() {
from = matcher.start() + 1;
return 1;
}
},
Spliterator.IMMUTABLE), false).reduce(0, (a, c) -> a + c);
}
loadXMLDoc JS function should return false, otherwise it will result in postback.
When using JavaScript to access an HTML element, there is a good chance that the element is not on the page and therefore not in the dom as far as JavaScript is concerned, when the code to access that element runs.
This problem can occur even though you can visually see the HTML element in the browser window or have the code set to be called in the onload method.
I ran into this problem after writing code to repopulate specific div elements on a page after retrieving the cookies.
What is apparently happening is that even though the HTML has loaded and is outputted by the browser, the JavaScript code is running before the page has completed loading.
The solution to this problem which just may be a JavaScript bug, is to place the code you want to run within a timer that delays the code run by 400 milliseconds or so. You will need to test it to determine how quick you can run the code.
I also made a point to test for the element before attempting to assign values to it.
window.setTimeout(function() {
if( document.getElementById("book") )
{ // Code goes here }, 400 /* but after 400 ms */);
This may or may not help you solve your problem, but keep this in mind and understand that browsers do not always function as expected.
Since -f
caused another problem, I developed another solution.
The -f
flag does not solved my problem because my onbuild
image looks for a file in a folder and had to call like this:
-f foo/bar/Dockerfile foo/bar
instead of
-f foo/bar/Dockerfile .
Also note that this is only solution for some cases as -f
flag
I had a similar issue in Mac where svn was picking mac login as user name and I was getting error as
svn: E170013: Unable to connect to a repository at URL 'https://repo:8443/svn/proj/trunk'
svn: E175013: Access to '/svn/proj/trunk' forbidden
I used the --username
along with svn command to pass the correct username which helped me.
Alternatively, you can delete ~/.subversion/auth
file, after which svn will prompt you for username.
There's interesting stuff on the performance aspects in this question
However I personally would still recommend string.Format
unless performance is critical for readability reasons.
string.Format("{0}: {1}", key, value);
Is more readable than
key + ": " + value
For instance. Also provides a nice separation of concerns. Means you can have
string.Format(GetConfigValue("KeyValueFormat"), key, value);
And then changing your key value format from "{0}: {1}"
to "{0} - {1}"
becomes a config change rather than a code change.
string.Format
also has a bunch of format provision built into it, integers, date formatting, etc.
The accepted answer has a couple of shortcomings:
Considering the above, your options could even have different values, but toggle the same class:
<select class="div-toggle" data-target=".my-info-1">
<option value="orange" data-show=".citrus">Orange</option>
<option value="lemon" data-show=".citrus">Lemon</option>
<option value="apple" data-show=".pome">Apple</option>
<option value="pear" data-show=".pome">Pear</option>
</select>
<div class="my-info-1">
<div class="citrus hide">Citrus is...</div>
<div class="pome hide">A pome is...</div>
</div>
jQuery:
$(document).on('change', '.div-toggle', function() {
var target = $(this).data('target');
var show = $("option:selected", this).data('show');
$(target).children().addClass('hide');
$(show).removeClass('hide');
});
$(document).ready(function(){
$('.div-toggle').trigger('change');
});
CSS:
.hide {
display: none;
}
Here's a JSFiddle to see it in action.
This will insert a 10 second sleep in between every call to foo()
, which is approximately what you asked for should the call complete quickly.
import time
while True:
foo()
time.sleep(10)
To do other things while your foo()
is being called in a background thread
import time
import sys
import threading
def foo():
sys.stdout.write('({}) foo\n'.format(time.ctime()))
def foo_target():
while True:
foo()
time.sleep(10)
t = threading.Thread(target=foo_target)
t.daemon = True
t.start()
print('doing other things...')
you can try using this
System.Web.HttpContext.Current.Server.MapPath(path);
or use HostingEnvironment.MapPath
System.Web.Hosting.HostingEnvironment.MapPath(path);
The message updates you receive via getUpdates
or your webhook will contain the chat ID for the specific message. It will be contained under the message.chat.id
key.
This seems like the only way you are able to retrieve the chat ID. So if you want to write something where the bot initiates the conversation you will probably have to store the chat ID in relation to the user in some sort of key->value store like MemCache or Redis.
I believe their documentation suggests something similar here, https://core.telegram.org/bots#deep-linking-example. You can use deep-linking to initiate a conversation without requiring the user to type a message first.
You can create an RxJS (v.6) Observable that does whatever you like.
<input type="text" (input)="onSearchChange($event.target.value)" />
import { Observable } from 'rxjs';
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';
export class ViewComponent {
searchChangeObserver;
onSearchChange(searchValue: string) {
if (!this.searchChangeObserver) {
Observable.create(observer => {
this.searchChangeObserver = observer;
}).pipe(debounceTime(300)) // wait 300ms after the last event before emitting last event
.pipe(distinctUntilChanged()) // only emit if value is different from previous value
.subscribe(console.log);
}
this.searchChangeObserver.next(searchValue);
}
}
To add to the above correct answer :-
For my case in shell, this code worked (working on sqoop
)
ROOT_PATH="path/to/the/folder"
--options-file $ROOT_PATH/query.txt
This creates a "See Also" heading containing the link, i.e.:
/**
* @see <a href="http://google.com">http://google.com</a>
*/
will render as:
See Also:
http://google.com
whereas this:
/**
* See <a href="http://google.com">http://google.com</a>
*/
will create an in-line link:
Read this thread R - boolean operators && and ||.
Basically, the &
is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. &&
is not, returning a single logical.
Here are a list of colors in a Java class with public static
fields
Usage
System.out.println(ConsoleColors.RED + "RED COLORED" +
ConsoleColors.RESET + " NORMAL");
Note
Don't forget to use the RESET
after printing as the effect will remain if it's not cleared
public class ConsoleColors {
// Reset
public static final String RESET = "\033[0m"; // Text Reset
// Regular Colors
public static final String BLACK = "\033[0;30m"; // BLACK
public static final String RED = "\033[0;31m"; // RED
public static final String GREEN = "\033[0;32m"; // GREEN
public static final String YELLOW = "\033[0;33m"; // YELLOW
public static final String BLUE = "\033[0;34m"; // BLUE
public static final String PURPLE = "\033[0;35m"; // PURPLE
public static final String CYAN = "\033[0;36m"; // CYAN
public static final String WHITE = "\033[0;37m"; // WHITE
// Bold
public static final String BLACK_BOLD = "\033[1;30m"; // BLACK
public static final String RED_BOLD = "\033[1;31m"; // RED
public static final String GREEN_BOLD = "\033[1;32m"; // GREEN
public static final String YELLOW_BOLD = "\033[1;33m"; // YELLOW
public static final String BLUE_BOLD = "\033[1;34m"; // BLUE
public static final String PURPLE_BOLD = "\033[1;35m"; // PURPLE
public static final String CYAN_BOLD = "\033[1;36m"; // CYAN
public static final String WHITE_BOLD = "\033[1;37m"; // WHITE
// Underline
public static final String BLACK_UNDERLINED = "\033[4;30m"; // BLACK
public static final String RED_UNDERLINED = "\033[4;31m"; // RED
public static final String GREEN_UNDERLINED = "\033[4;32m"; // GREEN
public static final String YELLOW_UNDERLINED = "\033[4;33m"; // YELLOW
public static final String BLUE_UNDERLINED = "\033[4;34m"; // BLUE
public static final String PURPLE_UNDERLINED = "\033[4;35m"; // PURPLE
public static final String CYAN_UNDERLINED = "\033[4;36m"; // CYAN
public static final String WHITE_UNDERLINED = "\033[4;37m"; // WHITE
// Background
public static final String BLACK_BACKGROUND = "\033[40m"; // BLACK
public static final String RED_BACKGROUND = "\033[41m"; // RED
public static final String GREEN_BACKGROUND = "\033[42m"; // GREEN
public static final String YELLOW_BACKGROUND = "\033[43m"; // YELLOW
public static final String BLUE_BACKGROUND = "\033[44m"; // BLUE
public static final String PURPLE_BACKGROUND = "\033[45m"; // PURPLE
public static final String CYAN_BACKGROUND = "\033[46m"; // CYAN
public static final String WHITE_BACKGROUND = "\033[47m"; // WHITE
// High Intensity
public static final String BLACK_BRIGHT = "\033[0;90m"; // BLACK
public static final String RED_BRIGHT = "\033[0;91m"; // RED
public static final String GREEN_BRIGHT = "\033[0;92m"; // GREEN
public static final String YELLOW_BRIGHT = "\033[0;93m"; // YELLOW
public static final String BLUE_BRIGHT = "\033[0;94m"; // BLUE
public static final String PURPLE_BRIGHT = "\033[0;95m"; // PURPLE
public static final String CYAN_BRIGHT = "\033[0;96m"; // CYAN
public static final String WHITE_BRIGHT = "\033[0;97m"; // WHITE
// Bold High Intensity
public static final String BLACK_BOLD_BRIGHT = "\033[1;90m"; // BLACK
public static final String RED_BOLD_BRIGHT = "\033[1;91m"; // RED
public static final String GREEN_BOLD_BRIGHT = "\033[1;92m"; // GREEN
public static final String YELLOW_BOLD_BRIGHT = "\033[1;93m";// YELLOW
public static final String BLUE_BOLD_BRIGHT = "\033[1;94m"; // BLUE
public static final String PURPLE_BOLD_BRIGHT = "\033[1;95m";// PURPLE
public static final String CYAN_BOLD_BRIGHT = "\033[1;96m"; // CYAN
public static final String WHITE_BOLD_BRIGHT = "\033[1;97m"; // WHITE
// High Intensity backgrounds
public static final String BLACK_BACKGROUND_BRIGHT = "\033[0;100m";// BLACK
public static final String RED_BACKGROUND_BRIGHT = "\033[0;101m";// RED
public static final String GREEN_BACKGROUND_BRIGHT = "\033[0;102m";// GREEN
public static final String YELLOW_BACKGROUND_BRIGHT = "\033[0;103m";// YELLOW
public static final String BLUE_BACKGROUND_BRIGHT = "\033[0;104m";// BLUE
public static final String PURPLE_BACKGROUND_BRIGHT = "\033[0;105m"; // PURPLE
public static final String CYAN_BACKGROUND_BRIGHT = "\033[0;106m"; // CYAN
public static final String WHITE_BACKGROUND_BRIGHT = "\033[0;107m"; // WHITE
}
To achieve what you are looking for you can use the viewport-percentage length vw
.
Here is a quick example I made on jsfiddle.
HTML:
<div class="square">
<h1>This is a Square</h1>
</div>
CSS:
.square {
background: #000;
width: 50vw;
height: 50vw;
}
.square h1 {
color: #fff;
}
I am sure there are many other ways to do this but this way seemed the best to me.
Same thing, Just start the table name with #
or ##
:
CREATE TABLE #TemporaryTable -- Local temporary table - starts with single #
(
Col1 int,
Col2 varchar(10)
....
);
CREATE TABLE ##GlobalTemporaryTable -- Global temporary table - note it starts with ##.
(
Col1 int,
Col2 varchar(10)
....
);
Temporary table names start with #
or ##
- The first is a local temporary table and the last is a global temporary table.
Here is one of many articles describing the differences between them.
Use ax.yaxis.tick_right()
for example:
from matplotlib import pyplot as plt
f = plt.figure()
ax = f.add_subplot(111)
ax.yaxis.tick_right()
plt.plot([2,3,4,5])
plt.show()
Using Java 8's time API (assuming you are happy to get the year in your system's default time zone), you could use the Year::now
method:
int year = Year.now().getValue();
In my opinion, it would be a cleaner and easier solution to just set a class on the body and set the font-family in css according to that class.
don't know if that's an option in your case though.
You can do something like:
Directory directory = new DirectoryInfo(path);
List<FileInfo> fileInfos = directory.EnumerateFiles("*.*", SearchOption.AllDirectories).ToList();
foreach (FileInfo f in fileInfos)
File.Delete(f.FullName);
Oops... Misunderstood the question...
Pause is the way to go
you can pipe commands into your patch file...
try
build.bat < responsefile.txt
How to tell on Ubuntu if apache2 is running:
sudo service apache2 status
/etc/init.d/apache2 status
ps aux | grep apache
Convert handles DbNull sensibly.
employee.FirstName = Convert.ToString(sqlreader.GetValue(indexFirstName));
I appreciate the help, I do think I have found a solution if someone would comment on the effectiveness I would appreciate it. Essentially what I did is. I realize it is somewhat static in its implementation but I does what I need it to do (forgive incorrect syntax)
SELECT
ordered_item.id as `Id`,
ordered_item.Item_Name as `ItemName`,
Options1.Value
Options2.Value
FROM ORDERED_ITEMS
LEFT JOIN (Ordered_Options as Options1)
ON (Options1.Ordered_Item.ID = Ordered_Options.Ordered_Item_ID
AND Options1.Option_Number = 43)
LEFT JOIN (Ordered_Options as Options2)
ON (Options2.Ordered_Item.ID = Ordered_Options.Ordered_Item_ID
AND Options2.Option_Number = 44);
If you know a variable is empty, you could use it as a comment. Of course if it is not empty it will mess up your command.
ls -l ${1# -F is turned off} -a /etc
Indeed, this is "very complicated in Java":
From: https://jersey.java.net/documentation/latest/client.html
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://foo").path("bar");
Invocation.Builder invocationBuilder = target.request(MediaType.TEXT_PLAIN_TYPE);
Response response = invocationBuilder.get();
I have been writing these and contributing them to BrowserHacks.com since the fall of 2013 -- this one I wrote is very simple and only supported by IE 11.
<style type="text/css">
_:-ms-fullscreen, :root .msie11 { color: blue; }
</style>
and of course the div...
<div class="msie11">
This is an Internet Explorer 11 CSS Hack
<div>
So the text shows up in blue with internet explorer 11. Have fun with it.
-
More IE and other browser CSS hacks on my live test site here:
UPDATED: http://browserstrangeness.bitbucket.io/css_hacks.html
MIRROR: http://browserstrangeness.github.io/css_hacks.html
(If you are also looking for MS Edge CSS Hacks, that is where to go.)
For those experiencing this error on CI/CD, adding the line below worked for me on my GitHub Actions CI/CD workflow right after running pip install pyflakes diff-cover
:
git fetch origin master:refs/remotes/origin/master
This is a snippet of the solution from the diff-cover github repo:
Solution: diff-cover matches source files in the coverage XML report with source files in the git diff. For this reason, it's important that the relative paths to the files match. If you are using coverage.py to generate the coverage XML report, then make sure you run diff-cover from the same working directory.
I got the solution on the links below. It is a documented diff-cover
error.
https://diff-cover.readthedocs.io/en/latest//README.html https://github.com/Bachmann1234/diff_cover/blob/master/README.rst
Hope this helps :-).
for ind in df.index:
print df['c1'][ind], df['c2'][ind]
You don not need to create a $(document).mousemove( function(e) {})
to handle mouse x,y. Get the event in the $.hover
function and from there it is possible to get x and y positions of the mouse. See the code below:
$('foo').hover(function(e){
var pos = [e.pageX-150,e.pageY];
$('foo1').dialog( "option", "position", pos );
$('foo1').dialog('open');
},function(){
$('foo1').dialog('close');
});
The index statistics likely need to be current, but this will return the number of rows for all tables that are not MS_SHIPPED.
select o.name, i.rowcnt
from sys.objects o join sys.sysindexes i
on o.object_id = i.id
where o.is_ms_shipped = 0
and i.rowcnt > 0
order by o.name
Implementing the SearchView without the use of the menu.xml
file and open through button
In your Activity
we need to use the method of the onCreateOptionsMenu
method in which we will programmatically inflate the SearchView
private MenuItem searchMenu;
private String mSearchString="";
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
SearchManager searchManager = (SearchManager) StoreActivity.this.getSystemService(Context.SEARCH_SERVICE);
SearchView mSearchView = new SearchView(getSupportActionBar().getThemedContext());
mSearchView.setQueryHint(getString(R.string.prompt_search)); /// YOUR HINT MESSAGE
mSearchView.setMaxWidth(Integer.MAX_VALUE);
searchMenu = menu.add("searchMenu").setVisible(false).setActionView(mSearchView);
searchMenu.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
assert searchManager != null;
mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
mSearchView.setIconifiedByDefault(false);
SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
public boolean onQueryTextChange(String newText) {
mSearchString = newText;
return true;
}
public boolean onQueryTextSubmit(String query) {
mSearchString = query;
searchMenu.collapseActionView();
return true;
}
};
mSearchView.setOnQueryTextListener(queryTextListener);
return true;
}
And in your Activity class, you can open the SearchView
on any button click on toolbar like below
YOUR_BUTTON.setOnClickListener(view -> {
searchMenu.expandActionView();
});
Try deleting your ASO files.
ASO files are cached compiled versions of your class files. Although the IDE is a lot better at letting go of old caches when changes are made, sometimes you have to manually delete them. To delete ASO files: Control>Delete ASO Files.
This is also the cause of the "I-am-not-seeing-my-changes-so-let-me-add-a-trace-now-everything-works" bug that was introduced in CS3.
docker rm $(docker ps -a -q)
docker rmi $(docker images -q)
MYISAM:
INNODB:
But you could make an own link for every from url.
Example: http://example.com?auth=holasite
In this example your site is: example.com
If somebody open that link it's give you the holasite value for the auth variable.
Then just $_GET['auth'] and you have the variable. But you should have a database to store it, and to authorize.
Like: $holasite = http://holasite.com (You could use mysql too..)
And just match it, and you have the url.
This method is a little bit more complicated, but it works. This method is good for a referral system authentication. But where is the site name, you should write an id, and works with that id.
We can use,
$ rails d migration table_name
Which will delete the migration.
Following applies to IIS 7
The error is trying to tell you that one of two things is not working properly:
See the following link for instructions on how to diagnose and fix the above issues.
http://support.microsoft.com/kb/942062/en-us
If neither of these issues is the problem, another thing to check is to make sure that the application pool configured for your website (under IIS Manager, select your website, and click "Basic Settings" on the far right) is configured with the same .Net framework version (in IIS Manager, under "Application Pools") as the targetFramework configured in your web.config, e.g.:
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<httpRuntime targetFramework="4.0" />
</system.web>
I'm not sure why this would generate such a seemingly unrelated error message, but it did for me.
If you don't mind using system()
, doing system("taskkill /f /im process.exe")
would be significantly easier than these other methods.
The other answers here are very much correct, and valuable. But sometimes you just want simple: to get a plain old parsed value at directive instantiation, without needing updates, and without messing with isolate scope. For instance, it can be handy to provide a declarative payload into your directive as an array or hash-object in the form:
my-directive-name="['string1', 'string2']"
In that case, you can cut to the chase and just use a nice basic angular.$eval(attr.attrName)
.
element.val("value = "+angular.$eval(attr.value));
Working Fiddle.
The standard solution:
expr $d1 - $d2
You can also do:
echo $(( d1 - d2 ))
but beware that this will treat 07
as an octal number! (so 07
is the same as 7
, but 010
is different than 10
).
I use hebrew(RTL language) in strings.xml. I have manually searched the string.xml for this char: ' than I added the escape char \ infront of it (now it looks like \' ) and still got the same error!
I searched again for the char ' and I replaced the char ' with \'(eng writing) , since it shows a right to left it looks like that '\ in the strings.xml !!
Problem solved.
On Android 10, none worked for me.
But I that worked perfectly fine (1st line in oncreate):
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_IMMERSIVE;
decorView.setSystemUiVisibility(uiOptions);
setContentView(....);
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
enjoy :)
If it is not defined in the web service or application or server (apache or IIS) that is hosting the web service consumable then you could create infinite connections until failure
No.
The following solution relies on JavaScript.
<button type="button" onclick="location.href='http://www.stackoverflow.com'">ABC</button>
If the button is to be placed inside an existing <form>
with method="post"
, then ensure the button has the attribute type="button"
otherwise the button will submit the POST operation. In this way you can have a <form>
that contains a mixture of GET and POST operation buttons.
If you use a "text variable" tk.StringVar()
, you can just set()
that.
No need to use the Entry delete and insert. Moreover, those functions don't work when the Entry is disabled or readonly! The text variable method, however, does work under those conditions as well.
import Tkinter as tk
...
entryText = tk.StringVar()
entry = tk.Entry( master, textvariable=entryText )
entryText.set( "Hello World" )
I'm Using Ubuntu and with the following command worked
apt-get install --yes zip unzip
It just doesn't make sense at all to be spending time invoking/defining routings. Even if you do need custom control, it's probably only for some of the time, and for the most bit you want to be able to just create a standard file structure of routings and have a module do it automatically.
Try Route Magic
As you scale your app, the routing invocations will start to form a giant heap of code that serves no purpose. You want to do just 2 lines of code to handle all the app.use
routing invocations with Route Magic like this:
const magic = require('express-routemagic')
magic.use(app, __dirname, '[your route directory]')
For those you want to handle manually, just don't use pass the directory to Magic.
<?php
$start = microtime(true);
for ($i = 0; $i < 10000000; $i++) {
$a = 'a';
$a = NULL;
}
$elapsed = microtime(true) - $start;
echo "took $elapsed seconds\r\n";
$start = microtime(true);
for ($i = 0; $i < 10000000; $i++) {
$a = 'a';
unset($a);
}
$elapsed = microtime(true) - $start;
echo "took $elapsed seconds\r\n";
?>
Per that it seems like "= null" is faster.
PHP 5.4 results:
PHP 5.3 results:
PHP 5.2 results:
PHP 5.1 results:
Things start to look different with PHP 5.0 and 4.4.
5.0:
4.4:
Keep in mind microtime(true) doesn't work in PHP 4.4 so I had to use the microtime_float example given in php.net/microtime / Example #1.
Use the query below to find out pending transaction.
If it returns a value, it means there is a pending transaction.
Here is the query:
select dbms_transaction.step_id from dual
;
References:
http://www.acehints.com/2011/07/how-to-check-pending-transaction-in.html
http://www.acehints.com/p/site-map.html
For full control of ANY (non simplest editor, non head of tree) ui elements I recomend use plugin UI Editor for NetBeans
Unfortunately there is no SELECT statement that will always work regardless of database.
Most databases support:
SELECT 1
Some databases don't support this but have a table called DUAL that you can use when you don't need a table:
SELECT 1 FROM DUAL
MySQL also supports this for compatibility reasons, but not all databases do. A workaround for databases that don't support either of the above is to create a table called DUAL that contains a single row, then the above will work.
HSQLDB supports neither of the above, so you can either create the DUAL table or else use:
SELECT 1 FROM any_table_that_you_know_exists_in_your_database
The error in the Google DevTools are caused Google extensions.
No more errors in the console.
I prefer using the following code to generate a decimal number up to fist decimal point. you can copy paste the 3rd line to add more numbers after decimal point by appending that number in string "combined". You can set the minimum and maximum value by changing the 0 and 9 to your preferred value.
Random r = new Random();
string beforePoint = r.Next(0, 9).ToString();//number before decimal point
string afterPoint = r.Next(0,9).ToString();//1st decimal point
//string secondDP = r.Next(0, 9).ToString();//2nd decimal point
string combined = beforePoint+"."+afterPoint;
decimalNumber= float.Parse(combined);
Console.WriteLine(decimalNumber);
I hope that it helped you.
One way of doing it is to use the ClientScriptManager
:
Page.ClientScript.RegisterStartupScript(
GetType(),
"MyKey",
"Myfunction();",
true);
This error also occurs if you have a block with no statements in it
For example:
def my_function():
for i in range(1,10):
def say_hello():
return "hello"
Notice that the for
block is empty. You can use the pass statement if you want to test the remaining code in the module.
You just have to reset the values you don't want to their defaults. No need to get into a mess by using !important
.
#zoomTarget .slikezamenjanje img {
max-height: auto;
padding-right: 0px;
}
I think the key datum you are missing is that CSS comes with default values. If you want to override a value, set it back to its default, which you can look up.
For example, all CSS height
and width
attributes default to auto
.
You can use either - which means most people opt for "+" as it's more human readable.
You can use the annotate command to place text annotations at any x and y values you want. To place them exactly at the data points you could do this
import numpy
from matplotlib import pyplot
x = numpy.arange(10)
y = numpy.array([5,3,4,2,7,5,4,6,3,2])
fig = pyplot.figure()
ax = fig.add_subplot(111)
ax.set_ylim(0,10)
pyplot.plot(x,y)
for i,j in zip(x,y):
ax.annotate(str(j),xy=(i,j))
pyplot.show()
If you want the annotations offset a little, you could change the annotate
line to something like
ax.annotate(str(j),xy=(i,j+0.5))
In my opinion the other proposed solution is.
This approach will prevent the users to download the file.
The URLs are passed in the request: request.getRequestURL()
.
If you mean other sites that are linking to you? You want to capture the HTTP Referrer, which you can do by calling:
request.getHeader("referer");
If you are working with Ubuntu, sometimes you need to run as sudo
:
For Python2:
sudo python gameover.py
For Python3:
sudo python3 gameover.py
In onclik function replace first line with this line u will definitely get right result.
if (passw1.getText().toString().equalsIgnoreCase("1234") && passw2.getText().toString().equalsIgnoreCase("1234")){
Check the version of your JavaMail lib (mail.jar or javax.mail.jar). Maybe you need a newer one. Download the newest version from here: https://javaee.github.io/javamail/
I had the *.pdb
files in the same folder and used the options from Arindam, but it still didn't work. Turns out I needed to enable Enable native code debugging which can be found under Project properties > Debug.
import ...
declare var $:any;
...
getSomeEndPoint(params:any): Observable<any[]> {
var qStr = $.param(params); //<---YOUR GUY
return this._http.get(this._adUrl+"?"+qStr)
.map((response: Response) => <any[]> response.json())
.catch(this.handleError);
}
provided that you have installed jQuery, I do npm i jquery --save
and include in apps.scripts
in angular-cli.json
Using renamer:
$ renamer --find /^fgh/ --replace jkl * --dry-run
Remove the --dry-run
flag once you're happy the output looks correct.
look at the example
window.history.replaceState({
foo: 'bar'
}, 'Nice URL Title', '/nice_url');
window.onpopstate = function (e) {
if (typeof e.state == "object" && e.state.foo == "bar") {
alert("Blah blah blah");
}
};
window.history.go(-1);
and search location.hash
;
Try this:
import shutil
import os
source_dir = '/path/to/source_folder'
target_dir = '/path/to/dest_folder'
file_names = os.listdir(source_dir)
for file_name in file_names:
shutil.move(os.path.join(source_dir, file_name), target_dir)
If you want to display a single character then you can also use name[0]
instead of using pointer.
It will serve your purpose but if you want to display full string using %c
, you can try this:
#include<stdio.h>
void main()
{
char name[]="siva";
int i;
for(i=0;i<4;i++)
{
printf("%c",*(name+i));
}
}
try this ugly but workable solution:
// use CommonJS to export all keys
module.exports = { a: 1, b: 2, c: 3 };
// import by key
import { a, b, c } from 'commonjs-style-module';
console.log(a, b, c);
You can use ServerXMLHTTP
in a VBA project by adding a reference to MSXML
.
- Open the VBA Editor (usually by editing a Macro)
- Go to the list of Available References
- Check Microsoft XML
- Click OK.
(from Referencing MSXML within VBA Projects)
The ServerXMLHTTP MSDN documentation has full details about all the properties and methods of ServerXMLHTTP.
In short though, it works basically like this:
- Call open method to connect to the remote server
- Call send to send the request.
- Read the response via responseXML, responseText, responseStream or responseBody
If your Gridview
used with AutoGenerateDeleteButton="true"
, you may convert it to LinkButton
:
Click GridView Tasks and then Edit Columns.
Select Delete in Selected fields, and click on Convert this field into a TemplateField. Then click OK:
Now your LinkButton
will be generated. You can add OnClientClick
event to the LinkButton
like this:
OnClientClick="return confirm('Are you sure you want to delete?'); "
The most simple way would be to use the Join() method:
public static void Trail()
{
var list = new List<string> { "lala", "lulu", "lele" };
var data = string.Join(",", list);
}
If you really need the StringBuilder, trim the end comma after the loop:
data.ToString().TrimEnd(',');
This is way more simpler with Maven dependency feature:
Hope this will help!
Use NSLog()
like this:
NSLog(@"The code runs through here!");
Or like this - with placeholders:
float aFloat = 5.34245;
NSLog(@"This is my float: %f \n\nAnd here again: %.2f", aFloat, aFloat);
In NSLog()
you can use it like + (id)stringWithFormat:(NSString *)format, ...
float aFloat = 5.34245;
NSString *aString = [NSString stringWithFormat:@"This is my float: %f \n\nAnd here again: %.2f", aFloat, aFloat];
You can add other placeholders, too:
float aFloat = 5.34245;
int aInteger = 3;
NSString *aString = @"A string";
NSLog(@"This is my float: %f \n\nAnd here is my integer: %i \n\nAnd finally my string: %@", aFloat, aInteger, aString);
SELECT t1.* FROM table t1 JOIN table t2 ON t1.Id=t2.Id WHERE t1.C4=t2.C4;
Giving Accurate Result for me.
Best source of information for all of your DOM woes
http://www.w3.org/TR/dom/#nodes
"Objects implementing the Document, DocumentFragment, DocumentType, Element, Text, ProcessingInstruction, or Comment interface (simply called nodes) participate in a tree."
http://www.w3.org/TR/dom/#element
"Element nodes are simply known as elements."
git add -A
git diff HEAD
Generate patch if required, and then:
git reset HEAD
NOTE: Please check device location latitude & logitude if you are using simulator means. By defaults its none only.
Step 1: Import CoreLocation
framework in .h File
#import <CoreLocation/CoreLocation.h>
Step 2: Add delegate CLLocationManagerDelegate
@interface yourViewController : UIViewController<CLLocationManagerDelegate>
{
CLLocationManager *locationManager;
CLLocation *currentLocation;
}
Step 3: Add this code in class file
- (void)viewDidLoad
{
[super viewDidLoad];
[self CurrentLocationIdentifier]; // call this method
}
Step 4: Method to detect current location
//------------ Current Location Address-----
-(void)CurrentLocationIdentifier
{
//---- For getting current gps location
locationManager = [CLLocationManager new];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
//------
}
Step 5: Get location using this method
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
currentLocation = [locations objectAtIndex:0];
[locationManager stopUpdatingLocation];
CLGeocoder *geocoder = [[CLGeocoder alloc] init] ;
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error)
{
if (!(error))
{
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(@"\nCurrent Location Detected\n");
NSLog(@"placemark %@",placemark);
NSString *locatedAt = [[placemark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "];
NSString *Address = [[NSString alloc]initWithString:locatedAt];
NSString *Area = [[NSString alloc]initWithString:placemark.locality];
NSString *Country = [[NSString alloc]initWithString:placemark.country];
NSString *CountryArea = [NSString stringWithFormat:@"%@, %@", Area,Country];
NSLog(@"%@",CountryArea);
}
else
{
NSLog(@"Geocode failed with error %@", error);
NSLog(@"\nCurrent Location Not Detected\n");
//return;
CountryArea = NULL;
}
/*---- For more results
placemark.region);
placemark.country);
placemark.locality);
placemark.name);
placemark.ocean);
placemark.postalCode);
placemark.subLocality);
placemark.location);
------*/
}];
}
This may be helpful
byte[] bytes = System.Convert.FromBase64String(stringInBase64);
For a quick solution, you can use AtomicInteger or any of the atomic variables which will let you change the value inside the method using the inbuilt methods. Here is sample code:
import java.util.concurrent.atomic.AtomicInteger;
public class PrimitivePassByReferenceSample {
/**
* @param args
*/
public static void main(String[] args) {
AtomicInteger myNumber = new AtomicInteger(0);
System.out.println("MyNumber before method Call:" + myNumber.get());
PrimitivePassByReferenceSample temp = new PrimitivePassByReferenceSample() ;
temp.changeMyNumber(myNumber);
System.out.println("MyNumber After method Call:" + myNumber.get());
}
void changeMyNumber(AtomicInteger myNumber) {
myNumber.getAndSet(100);
}
}
Output:
MyNumber before method Call:0
MyNumber After method Call:100
Oracle XE With Application Express.
If you want vertical sizing proportional to a width set in pixels on an enclosing div, I believe you need an extra element, like so:
#html
<div class="ptest">
<div class="ptest-wrap">
<div class="ptest-inner">
Put content here
</div>
</div>
</div>
#css
.ptest {
width: 200px;
position: relative;
}
.ptest-wrap {
padding-top: 60%;
}
.ptest-inner {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: #333;
}
Here's the 2 div solution that doesn't work. Note the 60% vertical padding is proportional to the window width, not the div.ptest
width:
Here's the example with the code above, which does work:
switch ($method) {
case "GET":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
break;
case "POST":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
break;
case "PUT":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
break;
case "DELETE":
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
break;
}
Try this:
constructor( public router: Router,) {
this.route.params.subscribe(params => this._onRouteGetParams(params));
}
this.router.navigate(['otherRoute']);
The command you have typed is /startup.sh
, if you have to start a shell script you have to fire the command as shown below:
$ cd /home/mpatil/softwares/apache-tomcat-7.0.47/bin
$ sh startup.sh
or
$ ./startup.sh
Please try that, you also have to go to your tomcat's bin-folder (by using the cd-command) to execute this shell script. In your case this is /home/mpatil/softwares/apache-tomcat-7.0.47/bin
.
The simple answer (full browser support):
<link rel="stylesheet" href="style.css" media="print" onload="this.media='all'">
The documented answer (with optional preloading and script-disabled fallback):
<!-- Optional, if we want the stylesheet to get preloaded. Note that this line causes stylesheet to get downloaded, but not applied to the page. Use strategically — while preloading will push this resource up the priority list, it may cause more important resources to be pushed down the priority list. This may not be the desired effect for non-critical CSS, depending on other resources your app needs. -->
<link rel="preload" href="style.css" as="style">
<!-- Media type (print) doesn't match the current environment, so browser decides it's not that important and loads the stylesheet asynchronously (without delaying page rendering). On load, we change media type so that the stylesheet gets applied to screens. -->
<link rel="stylesheet" href="style.css" media="print" onload="this.media='all'">
<!-- Fallback that only gets inserted when JavaScript is disabled, in which case we can't load CSS asynchronously. -->
<noscript><link rel="stylesheet" href="style.css"></noscript>
Preloading and async combined:
If you need preloaded and async CSS, this solution simply combines two lines from the documented answer above, making it slightly cleaner. But this won't work in Firefox until they support the preload keyword. And again, as detailed in the documented answer above, preloading may not actually be beneficial.
<link href="style.css" rel="preload" as="style" onload="this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="style.css"></noscript>
Additional considerations:
Note that, in general, if you're going to load CSS asynchronously, it's generally recommended that you inline critical CSS, since CSS is a render-blocking resource for a reason.
Credit to filament group for their many async CSS solutions.
There is no unique
method for a df, if the number of unique values for each column were the same then the following would work: df.apply(pd.Series.unique)
but if not then you will get an error. Another approach would be to store the values in a dict which is keyed on the column name:
In [111]:
df = pd.DataFrame({'a':[0,1,2,2,4], 'b':[1,1,1,2,2]})
d={}
for col in df:
d[col] = df[col].unique()
d
Out[111]:
{'a': array([0, 1, 2, 4], dtype=int64), 'b': array([1, 2], dtype=int64)}
Specify the type of the pointer to your comparison function as the 3rd type into the map, and provide the function pointer to the map constructor:
map<keyType, valueType, typeOfPointerToFunction> mapName(pointerToComparisonFunction);
Take a look at the example below for providing a comparison function to a map
, with vector
iterator as key and int
as value.
#include "headers.h"
bool int_vector_iter_comp(const vector<int>::iterator iter1, const vector<int>::iterator iter2) {
return *iter1 < *iter2;
}
int main() {
// Without providing custom comparison function
map<vector<int>::iterator, int> default_comparison;
// Providing custom comparison function
// Basic version
map<vector<int>::iterator, int,
bool (*)(const vector<int>::iterator iter1, const vector<int>::iterator iter2)>
basic(int_vector_iter_comp);
// use decltype
map<vector<int>::iterator, int, decltype(int_vector_iter_comp)*> with_decltype(&int_vector_iter_comp);
// Use type alias or using
typedef bool my_predicate(const vector<int>::iterator iter1, const vector<int>::iterator iter2);
map<vector<int>::iterator, int, my_predicate*> with_typedef(&int_vector_iter_comp);
using my_predicate_pointer_type = bool (*)(const vector<int>::iterator iter1, const vector<int>::iterator iter2);
map<vector<int>::iterator, int, my_predicate_pointer_type> with_using(&int_vector_iter_comp);
// Testing
vector<int> v = {1, 2, 3};
default_comparison.insert(pair<vector<int>::iterator, int>({v.end(), 0}));
default_comparison.insert(pair<vector<int>::iterator, int>({v.begin(), 0}));
default_comparison.insert(pair<vector<int>::iterator, int>({v.begin(), 1}));
default_comparison.insert(pair<vector<int>::iterator, int>({v.begin() + 1, 1}));
cout << "size: " << default_comparison.size() << endl;
for (auto& p : default_comparison) {
cout << *(p.first) << ": " << p.second << endl;
}
basic.insert(pair<vector<int>::iterator, int>({v.end(), 0}));
basic.insert(pair<vector<int>::iterator, int>({v.begin(), 0}));
basic.insert(pair<vector<int>::iterator, int>({v.begin(), 1}));
basic.insert(pair<vector<int>::iterator, int>({v.begin() + 1, 1}));
cout << "size: " << basic.size() << endl;
for (auto& p : basic) {
cout << *(p.first) << ": " << p.second << endl;
}
with_decltype.insert(pair<vector<int>::iterator, int>({v.end(), 0}));
with_decltype.insert(pair<vector<int>::iterator, int>({v.begin(), 0}));
with_decltype.insert(pair<vector<int>::iterator, int>({v.begin(), 1}));
with_decltype.insert(pair<vector<int>::iterator, int>({v.begin() + 1, 1}));
cout << "size: " << with_decltype.size() << endl;
for (auto& p : with_decltype) {
cout << *(p.first) << ": " << p.second << endl;
}
with_typedef.insert(pair<vector<int>::iterator, int>({v.end(), 0}));
with_typedef.insert(pair<vector<int>::iterator, int>({v.begin(), 0}));
with_typedef.insert(pair<vector<int>::iterator, int>({v.begin(), 1}));
with_typedef.insert(pair<vector<int>::iterator, int>({v.begin() + 1, 1}));
cout << "size: " << with_typedef.size() << endl;
for (auto& p : with_typedef) {
cout << *(p.first) << ": " << p.second << endl;
}
}
On macOS check also the Mail.app settings, which App is selected as default email App / associated with mailto:
links:
If you ever clicked that notification on Gmail, which allows to open links in Gmail instead your App - and after this reset the Chrome handler, you have to edit this manually in your Mail.app Settings.
The only way to add headers to a request from inside a browser is use the XmlHttpRequest setRequestHeader method.
Using this with "GET" request will download the resource. The trick then is to access the resource in the intended way. Ostensibly you should be able to allow the GET response to be cacheable for a short period, hence navigation to a new URL or the creation of an IMG tag with a src url should use the cached response from the previous "GET". However that is quite likely to fail especially in IE which can be a bit of a law unto itself where the cache is concerned.
Ultimately I agree with Mehrdad, use of query string is easiest and most reliable method.
Another quirky alternative is use an XHR to make a request to a URL that indicates your intent to access a resource. It could respond with a session cookie which will be carried by the subsequent request for the image or link.
if you are using maven:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
In case than you want to store a complex command to compare text result, for example to compare the version of OS, maybe this can help you:
tasks:
- shell: echo $(cat /etc/issue | awk {'print $7'})
register: echo_content
- shell: echo "It works"
when: echo_content.stdout == "12"
register: out
- debug: var=out.stdout_lines
I removed the old web library such that are spring framework libraries. And build a new path of the libraries. Then it works.
In my case, it was working in x86 but not in x64.
It quite ridiculous, but in x64 the following change had to be added before it would work:
x86 -> szDsn = "DRIVER={MICROSOFT ACCESS DRIVER (*.mdb)};
x64 -> szDsn = "DRIVER={MICROSOFT ACCESS DRIVER (*.mdb, *.accdb)};
Note the addition of *.accdb
.
the over partition keyword is as if we are partitioning the data by client_id creation a subset of each client id
select client_id, operation_date,
row_number() count(*) over (partition by client_id order by client_id ) as operationctrbyclient
from client_operations e
order by e.client_id;
this query will return the number of operations done by the client_id
You can use this-> window.location.href = '...';
This would change the page to whatever you want..
SOLVED
Using IntelliJ
Select Build->Rebuild Project will solve it
This is probably the easiest way:
new Date(<your-date-object>.toDateString());
Example: To get the Current Date without time component:
new Date(new Date().toDateString());
gives: Thu Jul 11 2019 00:00:00 GMT-0400 (Eastern Daylight Time)
Note this works universally, because toDateString()
produces date string with your browser's localization (without the time component), and the new Date()
uses the same localization to parse that date string.
Simply this will return an array of enum values:
Object.values(myEnum);
You can use Line height a big as height of the div.
But for me best solution is this --> position:relative; top:50%; transform:translate(0,50%);
Here's one of my favorite places to use the **
syntax as in Dave Webb's final example:
mynum = 1000
mystr = 'Hello World!'
print("{mystr} New-style formatting is {mynum}x more fun!".format(**locals()))
I'm not sure if it's terribly fast when compared to just using the names themselves, but it's a lot easier to type!
On Windows 2003 and later, type this command in cmd:
cmd> where MSBuild
Sample result: C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe
If nothing appears, it means that .NET framework is not included in the system PATH. The MSBuild should be in the .NET installation folder, along with .NET compilers (vbc.exe, csc.exe)
I solved it by editing styles.xml:
<style name="ToolbarColoredBackArrow" parent="AppTheme">
<item name="android:textColorSecondary">INSERT_COLOR_HERE</item>
</style>
...then referencing the style in the Toolbar definition in the activity:
<LinearLayout
android:id="@+id/main_parent_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
app:theme="@style/ToolbarColoredBackArrow"
app:popupTheme="@style/AppTheme"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"/>
Try this
getExternalFilesDir(Environment.getDataDirectory().getAbsolutePath()).getAbsolutePath()