You can use markersize to specify the size of the circle in plot method
import numpy as np
import matplotlib.pyplot as plt
x1 = np.random.randn(20)
x2 = np.random.randn(20)
plt.figure(1)
# you can specify the marker size two ways directly:
plt.plot(x1, 'bo', markersize=20) # blue circle with size 10
plt.plot(x2, 'ro', ms=10,) # ms is just an alias for markersize
plt.show()
From here
Use MySQL Workbench. create SQL dump file of your database
Follow below steps:
Fistly, Code Blocks is not a compiler. It is just an integrated development environment.
So, you must show the path of your compiler at first, (if you dont have a compiler you have to download an install, it is not difficult to find. f.e. GCC is good one.) If code blocks could not find automatically the path of compiler it is an obligation to show it yourself.
But when you install, probably Code Blocks automatically find your compiler.
Enjoy.
There are two totally conflicting answers with large number of votes one is 160px@1024 the other is 180px@1024. So witch one?
I ran some experiments and I think that it is 180px@1024 so drbarnard is correct.
I downloaded iTunes U icon from the App Store it's 175x175px I upscaled it in photoshop to 1024px and put two shapes on it, one with 160px radius and one with 180px.
As you can see below the shape (thin gray line) with 160px (the 1st one) is a bit off whereas the one with 180px looks just fine.
This is what I do now in PhotoShop:
Suppose for some reason Ctrl+Z is also not working, go to another terminal, find the process id (using ps
) and run:
kill -SIGSTOP PID
kill -SIGCONT PID
SIGSTOP
will suspend the process and SIGCONT
will resume the process, in background. So now, closing both your terminals won't stop your process.
According to the documentation :
If the separator parameter is null or contains no characters, white-space characters are assumed to be the delimiters. White-space characters are defined by the Unicode standard and return true if they are passed to the Char.IsWhiteSpace method.
So just call myStr.Split();
There's no need to pass in anything because separator is a params
array.
If the --args
parameter is not working on your machine (i.e. on Solaris 8), you may start gdb like
gdb -ex "set args <arg 1> <arg 2> ... <arg n>"
And you can combine this with inputting a file to stdin and "running immediatelly":
gdb -ex "set args <arg 1> <arg 2> ... <arg n> < <input file>" -ex "r"
So the answer seems to be to NOT use the Solution Explorer search box.
Rather, open any file in the solution, then use the control-f search pop-up to search all files by:
Not sure if this works for cells with functions but I found this code elsewhere for single cell entries and modified it for my use. If done properly, you do not need to worry about entering a function in a cell or the file changing the dates to that day's date every time it is opened.
Copy/Paste Code below:
Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Range("D:D")) Is Nothing Then Exit Sub
Target.Offset(0, 2) = Date
End Sub
Good luck...
Try this
var div = document.getElementById("test");
var spans = div.getElementsByTagName("span");
for(i=0;i<spans.length;i++)
{
alert(spans[i].innerHTML);
}
df.apply(pd.value_counts).fillna(0)
value_counts - Returns object containing counts of unique values
apply - count frequency in every column. If you set axis=1
, you get frequency in every row
fillna(0) - make output more fancy. Changed NaN to 0
Incase you you're like me and you landed here trying to find a way to tell if your PowerShell variable is this particular flavor of non-existent:
COM object that has been separated from its underlying RCW cannot be used.
Then here's some code that worked for me:
function Count-RCW([__ComObject]$ComObj){
try{$iuk = [System.Runtime.InteropServices.Marshal]::GetIUnknownForObject($ComObj)}
catch{return 0}
return [System.Runtime.InteropServices.Marshal]::Release($iuk)-1
}
example usage:
if((Count-RCW $ExcelApp) -gt 0){[System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($ExcelApp)}
mashed together from other peoples' better answers:
and some other cool things to know:
There are two ways to take a photo:
1 - Using an Intent to make a photo
2 - Using the camera API
I think you should use the second way and there is a sample code here for two of them.
Here is something to try, using interface and destructuring with default values. Please note that "lastName" is optional.
interface IName {
firstName: string
lastName?: string
}
function sayName(params: IName) {
const { firstName, lastName = "Smith" } = params
const fullName = `${firstName} ${lastName}`
console.log("FullName-> ", fullName)
}
sayName({ firstName: "Bob" })
You can use something like this :
SELECT
Books.BookTitle,
Books.Edition,
Books.Year,
Books.Pages,
Books.Rating,
Categories.Category,
Publishers.Publisher,
Writers.LastName
FROM Books
INNER JOIN Categories_Books ON Categories_Books._Books_ISBN = Books._ISBN
INNER JOIN Categories ON Categories._CategoryID = Categories_Books._Categories_Category_ID
INNER JOIN Publishers ON Publishers._Publisherid = Books.PublisherID
INNER JOIN Writers_Books ON Writers_Books._Books_ISBN = Books._ISBN
INNER JOIN Writers ON Writers.Writers_Books = _Writers_WriterID.
This problem occurs when the controller or directive are not specified as a array of dependencies and function. For example
angular.module("appName").directive('directiveName', function () {
return {
restrict: 'AE',
templateUrl: 'calender.html',
controller: function ($scope) {
$scope.selectThisOption = function () {
// some code
};
}
};
});
When minified The '$scope' passed to the controller function is replaced by a single letter variable name . This will render angular clueless of the dependency . To avoid this pass the dependency name along with the function as a array.
angular.module("appName").directive('directiveName', function () {
return {
restrict: 'AE',
templateUrl: 'calender.html'
controller: ['$scope', function ($scope) { //<-- difference
$scope.selectThisOption = function () {
// some code
};
}]
};
});
Use ByteArrayInputStream
:
InputStream is = new ByteArrayInputStream(decodedBytes);
Why don't you just use CopyToDataTable
DataTable dt = (DataTable)Session["dtAllOrders"];
DataTable dtSpecificOrders = new DataTable();
DataTable orderRows = dt.Select("CustomerID = 2").CopyToDataTable();
If the result is for humans to read and the elements of the array have a proper toString()
defined...
outputString.write(Arrays.toString(array));
Found this approach on another site. It works with the new larger sizes of Excel and doesn't require you to hardcode the max number of rows and columns.
iLastRow = Cells(Rows.Count, "a").End(xlUp).Row
iLastCol = Cells(i, Columns.Count).End(xlToLeft).Column
Just change your port,might be your current port is in use by iis or some other server.
selector{
overflow-y: scroll;
overflow-x: hidden;
}
Working example with snippet and jsfiddle link https://jsfiddle.net/sx8u82xp/3/
.container{_x000D_
height:100vh;_x000D_
overflow-y:scroll;_x000D_
overflow-x: hidden;_x000D_
background:yellow;_x000D_
}
_x000D_
<div class="container">_x000D_
_x000D_
<p>_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
_x000D_
Why do we use it?_x000D_
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like)._x000D_
</p>_x000D_
_x000D_
<p>_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
_x000D_
Why do we use it?_x000D_
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like)._x000D_
</p>_x000D_
_x000D_
<p>_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
_x000D_
Why do we use it?_x000D_
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like)._x000D_
</p>_x000D_
_x000D_
<p>_x000D_
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
_x000D_
Why do we use it?_x000D_
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like)._x000D_
</p>_x000D_
_x000D_
</div>
_x000D_
To install the prerequisites for GPU support in TensorFlow 2.1:
pip install tensorflow
.The "Premature end of script headers" error message is probably the most loathed and common error message you'll find. What the error actually means, is that the script stopped for whatever reason before it returned any output to the web server. A common cause of this for script writers is to fail to set a content type before printing output code. In Perl for example, before printing any HTML it is necessary to tell the Perl script to set the content type to text/html, this is done by sending a header, like so:
print "Content-type: text/html\n\n";
You should be able to just check out the one file you want to restore. Try something like svn co svn://your_repos/path/to/file/you/want/to/restore@rev
where rev
is the last revision at which the file existed.
I had to do exactly this a little while ago and if I remember correctly, using the -r
option to svn
didn't work; I had to use the :rev
syntax. (Although I might have remembered it backwards...)
The Symfony documentation now explicitly shows how to do this:
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'SELECT p
FROM AppBundle:Product p
WHERE p.price > :price
ORDER BY p.price ASC'
)->setParameter('price', '19.99');
$products = $query->getResult();
From http://symfony.com/doc/2.8/book/doctrine.html#querying-for-objects-with-dql
If you only need it once, it's overkill to load a plugin.
For a date "dd/mm/yyyy", this works for me:
new Date(d.date.substring(6, 10),d.date.substring(3, 5)-1,d.date.substring(0, 2));
Just invert month and day for mm/dd/yyyy, the syntax is
new Date(y,m,d)
Take a form-control
, and add is-valid
to its class. Notice how the control turns green, but more importantly, notice the checkmark icon on the right of the control? This is what we want!
Example:
.my-icon {_x000D_
padding-right: calc(1.5em + .75rem);_x000D_
background-image: url('https://use.fontawesome.com/releases/v5.8.2/svgs/regular/calendar-alt.svg');_x000D_
background-repeat: no-repeat;_x000D_
background-position: center right calc(.375em + .1875rem);_x000D_
background-size: calc(.75em + .375rem) calc(.75em + .375rem);_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>_x000D_
<div class="container">_x000D_
<div class="col-md-5">_x000D_
<input type="text" id="date" class="form-control my-icon" placeholder="Select...">_x000D_
</div>_x000D_
</div>
_x000D_
A Monitor is an object designed to be accessed from multiple threads. The member functions or methods of a monitor object will enforce mutual exclusion, so only one thread may be performing any action on the object at a given time. If one thread is currently executing a member function of the object then any other thread that tries to call a member function of that object will have to wait until the first has finished.
A Semaphore is a lower-level object. You might well use a semaphore to implement a monitor. A semaphore essentially is just a counter. When the counter is positive, if a thread tries to acquire the semaphore then it is allowed, and the counter is decremented. When a thread is done then it releases the semaphore, and increments the counter.
If the counter is already zero when a thread tries to acquire the semaphore then it has to wait until another thread releases the semaphore. If multiple threads are waiting when a thread releases a semaphore then one of them gets it. The thread that releases a semaphore need not be the same thread that acquired it.
A monitor is like a public toilet. Only one person can enter at a time. They lock the door to prevent anyone else coming in, do their stuff, and then unlock it when they leave.
A semaphore is like a bike hire place. They have a certain number of bikes. If you try and hire a bike and they have one free then you can take it, otherwise you must wait. When someone returns their bike then someone else can take it. If you have a bike then you can give it to someone else to return --- the bike hire place doesn't care who returns it, as long as they get their bike back.
With Z I assume you mean Integers , i.e 3,-5,77 not 3.14, 4.02 etc.
A regular expression may help:
Pattern isInteger = Pattern.compile("\\d+");
code below allows user to input items until they press enter key to stop:
In [1]: items=[]
...: i=0
...: while 1:
...: i+=1
...: item=input('Enter item %d: '%i)
...: if item=='':
...: break
...: items.append(item)
...: print(items)
...:
Enter item 1: apple
Enter item 2: pear
Enter item 3: #press enter here
['apple', 'pear']
In [2]:
Your footer container is constricting the width of the inner element with an explicit width on itself, which sees the text clipped at the end and wrapped onto a new line, so change that:
div#fv2-footer-container {
width: 1090px;
...
One solution is to make another process to perform your read of the process, or make a thread of the process with a timeout.
Here's the threaded version of a timeout function:
http://code.activestate.com/recipes/473878/
However, do you need to read the stdout as it's coming in? Another solution may be to dump the output to a file and wait for the process to finish using p.wait().
f = open('myprogram_output.txt','w')
p = subprocess.Popen('myprogram.exe', stdout=f)
p.wait()
f.close()
str = open('myprogram_output.txt','r').read()
Store it anywhere in an accessible location except of the IDE's project folder aka the server's deploy folder, for reasons mentioned in the answer to Uploaded image only available after refreshing the page:
Changes in the IDE's project folder does not immediately get reflected in the server's work folder. There's kind of a background job in the IDE which takes care that the server's work folder get synced with last updates (this is in IDE terms called "publishing"). This is the main cause of the problem you're seeing.
In real world code there are circumstances where storing uploaded files in the webapp's deploy folder will not work at all. Some servers do (either by default or by configuration) not expand the deployed WAR file into the local disk file system, but instead fully in the memory. You can't create new files in the memory without basically editing the deployed WAR file and redeploying it.
Even when the server expands the deployed WAR file into the local disk file system, all newly created files will get lost on a redeploy or even a simple restart, simply because those new files are not part of the original WAR file.
It really doesn't matter to me or anyone else where exactly on the local disk file system it will be saved, as long as you do not ever use getRealPath()
method. Using that method is in any case alarming.
The path to the storage location can in turn be definied in many ways. You have to do it all by yourself. Perhaps this is where your confusion is caused because you somehow expected that the server does that all automagically. Please note that @MultipartConfig(location)
does not specify the final upload destination, but the temporary storage location for the case file size exceeds memory storage threshold.
So, the path to the final storage location can be definied in either of the following ways:
Hardcoded:
File uploads = new File("/path/to/uploads");
Environment variable via SET UPLOAD_LOCATION=/path/to/uploads
:
File uploads = new File(System.getenv("UPLOAD_LOCATION"));
VM argument during server startup via -Dupload.location="/path/to/uploads"
:
File uploads = new File(System.getProperty("upload.location"));
*.properties
file entry as upload.location=/path/to/uploads
:
File uploads = new File(properties.getProperty("upload.location"));
web.xml
<context-param>
with name upload.location
and value /path/to/uploads
:
File uploads = new File(getServletContext().getInitParameter("upload.location"));
If any, use the server-provided location, e.g. in JBoss AS/WildFly:
File uploads = new File(System.getProperty("jboss.server.data.dir"), "uploads");
Either way, you can easily reference and save the file as follows:
File file = new File(uploads, "somefilename.ext");
try (InputStream input = part.getInputStream()) {
Files.copy(input, file.toPath());
}
Or, when you want to autogenerate an unique file name to prevent users from overwriting existing files with coincidentally the same name:
File file = File.createTempFile("somefilename-", ".ext", uploads);
try (InputStream input = part.getInputStream()) {
Files.copy(input, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
How to obtain part
in JSP/Servlet is answered in How to upload files to server using JSP/Servlet? and how to obtain part
in JSF is answered in How to upload file using JSF 2.2 <h:inputFile>? Where is the saved File?
Note: do not use Part#write()
as it interprets the path relative to the temporary storage location defined in @MultipartConfig(location)
.
PowerShell solution
Using Posh-SSH:
New-SSHSession -ComputerName 0.0.0.0 -Credential $cred | Out-Null
Invoke-SSHCommand -SessionId 1 -Command "nohup sleep 5 >> abs.log &" | Out-Null
Yes, there is one. It is an eclipse-plugin called Visual Editor. You can download it here
"Never use two dots with COM objects" is a great rule of thumb to avoid leakage of COM references, but Excel PIA can lead to leakage in more ways than apparent at first sight.
One of these ways is subscribing to any event exposed by any of the Excel object model's COM objects.
For example, subscribing to the Application class's WorkbookOpen event.
COM classes expose a group of events through call-back interfaces. In order to subscribe to events, the client code can simply register an object implementing the call-back interface and the COM class will invoke its methods in response to specific events. Since the call-back interface is a COM interface, it is the duty of the implementing object to decrement the reference count of any COM object it receives (as a parameter) for any of the event handlers.
Excel PIA exposes COM events of Excel Application class as conventional .NET events. Whenever the client code subscribes to a .NET event (emphasis on 'a'), PIA creates an instance of a class implementing the call-back interface and registers it with Excel.
Hence, a number of call-back objects get registered with Excel in response to different subscription requests from the .NET code. One call-back object per event subscription.
A call-back interface for event handling means that, PIA has to subscribe to all interface events for every .NET event subscription request. It cannot pick and choose. On receiving an event call-back, the call-back object checks if the associated .NET event handler is interested in the current event or not and then either invokes the handler or silently ignores the call-back.
All these call-back objects do not decrement the reference count of any of the COM objects they receive (as parameters) for any of the call-back methods (even for the ones that are silently ignored). They rely solely on the CLR garbage collector to free up the COM objects.
Since GC run is non-deterministic, this can lead to the holding off of Excel process for a longer duration than desired and create an impression of a 'memory leak'.
The only solution as of now is to avoid the PIA’s event provider for the COM class and write your own event provider which deterministically releases COM objects.
For the Application class, this can be done by implementing the AppEvents interface and then registering the implementation with Excel by using IConnectionPointContainer interface. The Application class (and for that matter all COM objects exposing events using callback mechanism) implements the IConnectionPointContainer interface.
its better to bind a click handler to the entire table and then use event.target to get the clicked TD. Thats all i can add to this as its 1:20am
In addition to the excellent answers above, the following shows how to add text to each page of a multi-page document:
using (var reader = new PdfReader(@"C:\Input.pdf"))
{
using (var fileStream = new FileStream(@"C:\Output.pdf", FileMode.Create, FileAccess.Write))
{
var document = new Document(reader.GetPageSizeWithRotation(1));
var writer = PdfWriter.GetInstance(document, fileStream);
document.Open();
for (var i = 1; i <= reader.NumberOfPages; i++)
{
document.NewPage();
var baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
var importedPage = writer.GetImportedPage(reader, i);
var contentByte = writer.DirectContent;
contentByte.BeginText();
contentByte.SetFontAndSize(baseFont, 12);
var multiLineString = "Hello,\r\nWorld!".Split('\n');
foreach (var line in multiLineString)
{
contentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, line, 200, 200, 0);
}
contentByte.EndText();
contentByte.AddTemplate(importedPage, 0, 0);
}
document.Close();
writer.Close();
}
}
Building on allcaps suggestion. Here is the font-awesome background method with the least amount of HTML:
<div class="wrapper"><input></div>
.wrapper {
position: relative;
}
input { padding-left: 20px; }
.wrapper:before {
font-family: 'FontAwesome';
position: absolute;
top: 2px;
left: 3px;
content: "\f007";
}
Before killing sessions, if possible do
ALTER SYSTEM ENABLE RESTRICTED SESSION;
to stop new sessions from connecting.
There is no method call size()
with array
. you can use array.length
Another short, potentially more performant than split, solution is:
const lines = (str.match(/\n/g) || '').length + 1
In C everything is pass-by-value. The use of pointers gives us the illusion that we are passing by reference because the value of the variable changes. However, if you were to print out the address of the pointer variable, you will see that it doesn't get affected. A copy of the value of the address is passed-in to the function. Below is a snippet illustrating that.
void add_number(int *a) {
*a = *a + 2;
}
int main(int argc, char *argv[]) {
int a = 2;
printf("before pass by reference, a == %i\n", a);
add_number(&a);
printf("after pass by reference, a == %i\n", a);
printf("before pass by reference, a == %p\n", &a);
add_number(&a);
printf("after pass by reference, a == %p\n", &a);
}
before pass by reference, a == 2
after pass by reference, a == 4
before pass by reference, a == 0x7fff5cf417ec
after pass by reference, a == 0x7fff5cf417ec
Note that since early December 2012, you can create new files directly from GitHub:
ProTip™: You can pre-fill the filename field using just the URL.
Typing?filename=yournewfile.txt
at the end of the URL will pre-fill the filename field with the nameyournewfile.txt
.
The default output format (which originally comes from a program known as diff
if you want to look for more info) is known as a “unified diff”. It contains essentially 4 different types of lines:
+
,-
, andI advise that you practice reading diffs between two versions of a file where you know exactly what you changed. Like that you'll recognize just what is going on when you see it.
Here's a solution that has been vetted with a complex Rails app (the one powering Square)
def all_models
# must eager load all the classes...
Dir.glob("#{RAILS_ROOT}/app/models/**/*.rb") do |model_path|
begin
require model_path
rescue
# ignore
end
end
# simply return them
ActiveRecord::Base.send(:subclasses)
end
It takes the best parts of the answers in this thread and combines them in the simplest and most thorough solution. This handle cases where your models are in subdirectories, use set_table_name etc.
As the question is generic, let's try to sum up possible solutions for the answer:
Simple plain JavaScript Solution:
The easiest way is a one line solution placed in an appropriate way:
location.reload();
What many people are missing here, because they hope to get some "points" is that the reload() function itself offers a Boolean as a parameter (details: https://developer.mozilla.org/en-US/docs/Web/API/Location/reload).
The Location.reload() method reloads the resource from the current URL. Its optional unique parameter is a Boolean, which, when it is true, causes the page to always be reloaded from the server. If it is false or not specified, the browser may reload the page from its cache.
This means there are two ways:
Solution1: Force reloading the current page from the server
location.reload(true);
Solution2: Reloading from cache or server (based on browser and your config)
location.reload(false);
location.reload();
And if you want to combine it with jQuery an listening to an event, I would recommend using the ".on()" method instead of ".click" or other event wrappers, e.g. a more proper solution would be:
$('#reloadIt').on('eventXyZ', function() {
location.reload(true);
});
No, there isn't, but you can easily make one:
#Your ascii.py program:
def charlist(begin, end):
charlist = []
for i in range(begin, end):
charlist.append(chr(i))
return ''.join(charlist)
#Python shell:
#import ascii
#print(ascii.charlist(50, 100))
#Comes out as:
#23456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abc
var htmlEnDeCode = (function() {
var charToEntityRegex,
entityToCharRegex,
charToEntity,
entityToChar;
function resetCharacterEntities() {
charToEntity = {};
entityToChar = {};
// add the default set
addCharacterEntities({
'&' : '&',
'>' : '>',
'<' : '<',
'"' : '"',
''' : "'"
});
}
function addCharacterEntities(newEntities) {
var charKeys = [],
entityKeys = [],
key, echar;
for (key in newEntities) {
echar = newEntities[key];
entityToChar[key] = echar;
charToEntity[echar] = key;
charKeys.push(echar);
entityKeys.push(key);
}
charToEntityRegex = new RegExp('(' + charKeys.join('|') + ')', 'g');
entityToCharRegex = new RegExp('(' + entityKeys.join('|') + '|&#[0-9]{1,5};' + ')', 'g');
}
function htmlEncode(value){
var htmlEncodeReplaceFn = function(match, capture) {
return charToEntity[capture];
};
return (!value) ? value : String(value).replace(charToEntityRegex, htmlEncodeReplaceFn);
}
function htmlDecode(value) {
var htmlDecodeReplaceFn = function(match, capture) {
return (capture in entityToChar) ? entityToChar[capture] : String.fromCharCode(parseInt(capture.substr(2), 10));
};
return (!value) ? value : String(value).replace(entityToCharRegex, htmlDecodeReplaceFn);
}
resetCharacterEntities();
return {
htmlEncode: htmlEncode,
htmlDecode: htmlDecode
};
})();
This is from ExtJS source code.
Go to data_dir
and remove the Your_table.TMP
file after repairing <Your_table>
table.
Create a new file, copy lines from the old to the new, and do the replacing before you write the lines to the new file.
One option would be to set up a windows service and get that to call your scheduled task.
In winforms I've used Timers put don't think this would work well in ASP.NET
For CGSize
CGSize(width: self.view.frame.width * 3, height: self.view.frame.size.height)
The advantage of IEnumerable is deferred execution (usually with databases). The query will not get executed until you actually loop through the data. It's a query waiting until it's needed (aka lazy loading).
If you call ToList, the query will be executed, or "materialized" as I like to say.
There are pros and cons to both. If you call ToList, you may remove some mystery as to when the query gets executed. If you stick to IEnumerable, you get the advantage that the program doesn't do any work until it's actually required.
possible duplicate , best way to achieve same as stated below:
function getKey(key) {
return `${key}`;
}
var obj = {key1: "value1", key2: "value2", [getKey('key3')]: "value3"};
I was trying to find the meaning of GRANT USAGE on *.* TO
and found here. I can clarify that GRANT USAGE on *.* TO user IDENTIFIED BY PASSWORD password
will be granted when you create the user with the following command (CREATE
):
CREATE USER 'user'@'localhost' IDENTIFIED BY 'password';
When you grant privilege with GRANT
, new privilege s will be added on top of it.
I've not tried it myself, but Visual Studio 2005 (and later) support the concept of Debugger Visualizers. This allows you to customize how an object is shown in the IDE. Check out this article for more details.
http://davidhayden.com/blog/dave/archive/2005/12/26/2645.aspx
It's definitely conceivable but I am not sure we're there yet. In the meantime, I'd recommend using something like Silverlight with IIS Smooth Streaming. Silverlight is plugin-based, but it works on Windows/OSX/Linux. Some day the HTML5 <video>
element will be the way to go, but that will lack support for a little while.
In your input tag, place the following:
onFocus="this.select()"
Spinner don't support Hint, i recommend you to make a custom spinner adapter.
check this link : https://stackoverflow.com/a/13878692/1725748
If you have Windows 10 with the OpenSSH client you may be able to generate the key, but you will have trouble copying it to the target Linux box as the ssh-copy-id command is not part of the client toolset.
Having has this problem I wrote a small PowerShell function to address this, that you add to your profile.
function ssh-copy-id([string]$userAtMachine, [string]$port = 22) {
# Get the generated public key
$key = "$ENV:USERPROFILE" + "/.ssh/id_rsa.pub"
# Verify that it exists
if (!(Test-Path "$key")) {
# Alert user
Write-Error "ERROR: '$key' does not exist!"
}
else {
# Copy the public key across
& cat "$key" | ssh $userAtMachine -p $port "umask 077; test -d .ssh || mkdir .ssh ; cat >> .ssh/authorized_keys || exit 1"
}
}
You can get the gist here
I have a brief write up about it here
You can try viewport units (CSS3):
div {
height: 95vh;
width: 95vw;
}
Method with boolean argument :
request.getSession(true);
returns new session, if the session is not associated with the request
request.getSession(false);
returns null, if the session is not associated with the request.
Method without boolean argument :
request.getSession();
returns new session, if the session is not associated with the request and returns the existing session, if the session is associated with the request.It won't return null.
What I did in my case was to update
"lib": [
"es2020",
"dom"
]
with
"lib": [
"es2016",
"dom"
]
in my tsconfig.json file
Using different syntax (flags ...), can cause this problem from version to another in webpack (3,4,5...), you have to read new webpack configuration updated and deprecated features.
The code
my_list = [(1, 2), (3, 4), (5, 6)]
for t in my_list:
print t
prints
(1, 2)
(3, 4)
(5, 6)
The loop iterates over my_list
, and assigns the elements of my_list
to t
one after the other. The elements of my_list
happen to be tuples, so t
will always be a tuple. To access the first element of the tuple t
, use t[0]
:
for t in my_list:
print t[0]
To access the first element of the tuple at the given index i
in the list, you can use
print my_list[i][0]
I know its bit old post. Still, it might help some one.
Instead of tag,if possible you can this as well.
<script type="text/javascript">
function IsItWorking() {
// Do your stuff here ...
alert("YES, It Works...!!!");
}
</script>
`<asp:HyperLinkID="Link1"NavigateUrl="javascript:IsItWorking();"` `runat="server">IsItWorking?</asp:HyperLink>`
Any comments on this?
Another example of the same concept - but say - you have 2 different columns - and you want to apply different agg functions to each of them i.e
f.groupBy("col1").agg(sum("col2").alias("col2"), avg("col3").alias("col3"), ...)
Here is the way to achieve it - though I do not yet know how to add the alias in this case
See the example below - Using Maps
val Claim1 = StructType(Seq(StructField("pid", StringType, true),StructField("diag1", StringType, true),StructField("diag2", StringType, true), StructField("allowed", IntegerType, true), StructField("allowed1", IntegerType, true)))
val claimsData1 = Seq(("PID1", "diag1", "diag2", 100, 200), ("PID1", "diag2", "diag3", 300, 600), ("PID1", "diag1", "diag5", 340, 680), ("PID2", "diag3", "diag4", 245, 490), ("PID2", "diag2", "diag1", 124, 248))
val claimRDD1 = sc.parallelize(claimsData1)
val claimRDDRow1 = claimRDD1.map(p => Row(p._1, p._2, p._3, p._4, p._5))
val claimRDD2DF1 = sqlContext.createDataFrame(claimRDDRow1, Claim1)
val l = List("allowed", "allowed1")
val exprs = l.map((_ -> "sum")).toMap
claimRDD2DF1.groupBy("pid").agg(exprs) show false
val exprs = Map("allowed" -> "sum", "allowed1" -> "avg")
claimRDD2DF1.groupBy("pid").agg(exprs) show false
if you open localhost/phpmyadmin
you will find a tab called "User accounts". There you can define all your users that can access the mysql database, set their rights and even limit from where they can connect.
I have done it like that
<%= form_for :user, url: {action: "update", params: {id: @user.id}} do |f| %>
Note the optional parameter id
set to user instance id attribute.
Short answer: They are now supported nicely, if you can enable developer mode.
From https://blogs.windows.com/buildingapps/2016/12/02/symlinks-windows-10/
Now in Windows 10 Creators Update, a user (with admin rights) can first enable Developer Mode, and then any user on the machine can run the mklink command without elevating a command-line console.
What drove this change? The availability and use of symlinks is a big deal to modern developers:
Many popular development tools like git and package managers like npm recognize and persist symlinks when creating repos or packages, respectively. When those repos or packages are then restored elsewhere, the symlinks are also restored, ensuring disk space (and the user’s time) isn’t wasted.
Easy to overlook with all the other announcements of the "Creator's update", but if you enable Developer Mode, you can create symlinks without elevated privileges. You might have to re-install git and make sure symlink support is enabled, as it's not by default.
1) You can use standard java utility xjc - ([your java home dir]\bin\xjc.exe). But you need to create .bat (or .sh) script for using it.
e.g. generate.bat:
[your java home dir]\bin\xjc.exe %1 %2 %3
e.g. test-scheme.xsd:
<?xml version="1.0"?>
<xs:schema version="1.0"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified"
targetNamespace="http://myprojects.net/xsd/TestScheme"
xmlns="http://myprojects.net/xsd/TestScheme">
<xs:element name="employee" type="PersonInfoType"/>
<xs:complexType name="PersonInfoType">
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
Run .bat file with parameters: generate.bat test-scheme.xsd -d [your src dir]
For more info use this documentation - http://docs.oracle.com/javaee/5/tutorial/doc/bnazg.html
and this - http://docs.oracle.com/javase/6/docs/technotes/tools/share/xjc.html
2) JAXB (xjc utility) is installed together with JDK6 by default.
The const with the int on either sides will make pointer to constant int:
const int *ptr=&i;
or:
int const *ptr=&i;
const
after *
will make constant pointer to int:
int *const ptr=&i;
In this case all of these are pointer to constant integer, but none of these are constant pointer:
const int *ptr1=&i, *ptr2=&j;
In this case all are pointer to constant integer and ptr2 is constant pointer to constant integer. But ptr1 is not constant pointer:
int const *ptr1=&i, *const ptr2=&j;
In Kotlin
evLoginPassword.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
doTheLoginWork()
}
true
}
Partial Xml Code
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:paddingLeft="24dp"
android:paddingRight="24dp">
<EditText
android:id="@+id/evLoginUserEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/email"
android:inputType="textEmailAddress"
android:textColor="@color/black_54_percent" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:paddingLeft="24dp"
android:paddingRight="24dp">
<EditText
android:id="@+id/evLoginPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/password"
android:inputType="textPassword"
android:imeOptions="actionDone"
android:textColor="@color/black_54_percent" />
</android.support.design.widget.TextInputLayout>
</LinearLayout>
Here is what I've been using:
$("[tabindex]").addClass("TabOnEnter");
$(document).on("keypress", ".TabOnEnter", function (e) {
//Only do something when the user presses enter
if (e.keyCode == 13) {
var nextElement = $('[tabindex="' + (this.tabIndex + 1) + '"]');
console.log(this, nextElement);
if (nextElement.length)
nextElement.focus()
else
$('[tabindex="1"]').focus();
}
});
Pays attention to the tabindex and is not specific to the form but to the whole page.
Note live
has been obsoleted by jQuery, now you should be using on
The code you tried is in fact two statements. A DELETE
followed by a SELECT
.
You don't define TOP
as ordered by what.
For a specific ordering criteria deleting from a CTE or similar table expression is the most efficient way.
;WITH CTE AS
(
SELECT TOP 1000 *
FROM [mytab]
ORDER BY a1
)
DELETE FROM CTE
As @David Heffeman indicates the recommendation is to use .yaml
when possible, and the recommendation has been that way since September 2006.
That some projects use .yml
is mostly because of ignorance of the implementers/documenters: they wanted to use YAML because of readability, or some other feature not available in other formats, were not familiar with the recommendation and and just implemented what worked, maybe after looking at some other project/library (without questioning whether what was done is correct).
The best way to approach this is to be rigorous when creating new files (i.e. use .yaml
) and be permissive when accepting input (i.e. allow .yml
when you encounter it), possible automatically upgrading/correcting these errors when possible.
The other recommendation I have is to document the argument(s) why you have to use .yml
, when you think you have to. That way you don't look like an ignoramus, and give others the opportunity to understand your reasoning. Of course "everybody else is doing it" and "On Google .yml
has more pages than .yaml
" are not arguments, they are just statistics about the popularity of project(s) that have it wrong or right (with regards to the extension of YAML files). You can try to prove that some projects are popular, just because they use a .yml
extension instead of the correct .yaml
, but I think you will be hard pressed to do so.
Some projects realize (too late) that they use the incorrect extension (e.g. originally docker-compose
used .yml
, but in later versions started to use .yaml
, although they still support .yml
). Others still seem ignorant about the correct extension, like AppVeyor early 2019, but allow you to specify the configuration file for a project, including extension. This allows you to get the configuration file out of your face as well as giving it the proper extension: I use .appveyor.yaml
instead of appveyor.yml
for building the windows wheels of my YAML parser for Python).
On the other hand:
The Yaml (sic!) component of Symfony2 implements a selected subset of features defined in the YAML 1.2 version specification.
So it seems fitting that they also use a subset of the recommended extension.
One can also bind a function with ng-change
event listener, if they need to run a bit more complex logic.
<div ng-app="myApp" ng-controller="myCtrl">
<input type='text' ng-model='name' ng-change='change()'>
<br/> <span>changed {{counter}} times </span>
</div>
...
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = 'Australia';
$scope.counter = 0;
$scope.change = function() {
$scope.counter++;
};
});
Try this
HTML
<select class="form-control"name="country">
<option class="servce_pro_disabled">Select Country</option>
<option class="servce_pro_disabled" value="Aruba" id="cl_country_option">Aruba</option>
</select>
CSS
.form-control option:first-child {
display: none;
}
Javier covered Notifications and current limitations.
My suggestion: window.postMessage
while we wait for the handicapped browser to catch up, else Worker.postMessage()
to still be operating with Web Workers.
These can be the fallback option with dialog box message display handler, for when a Notification feature test fails or permission is denied.
Notification has-feature and denied-permission check:
if (!("Notification" in window) || (Notification.permission === "denied") ) {
// use (window||Worker).postMessage() fallback ...
}
How about pdf2tiff? http://python.net/~gherman/pdf2tiff.html
We can directly subtract dates to get difference in Days.
SET SERVEROUTPUT ON ;
DECLARE
V_VAR NUMBER;
BEGIN
V_VAR:=TO_DATE('2000-01-02', 'YYYY-MM-DD') - TO_DATE('2000-01-01', 'YYYY-MM-DD') ;
DBMS_OUTPUT.PUT_LINE(V_VAR);
END;
For JavaFx based applications.
//returns System Clipboard
final Clipboard clipboard = Clipboard.getSystemClipboard();
// ClipboardContent provides flexibility to store data in different formats
final ClipboardContent content = new ClipboardContent();
content.putString("Some text");
content.putHtml("<b>Some</b> text");
//this will be replaced by previous putString
content.putString("Some different text");
//set the content to clipboard
clipboard.setContent(content);
// validate before retrieving it
if(clipboard.hasContent(DataFormat.HTML)){
System.out.println(clipboard.getHtml());
}
if(clipboard.hasString()){
System.out.println(clipboard.getString());
}
ClipboardContent can save multiple data in several data formats like(html,url,plain text,image).
For more information see official documentation
The most underrated method is insertAdjacentElement
.
You can literally add your HTML using one single line.
document.body.insertAdjacentElement('beforeend', html)
Read about it here - https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentElement
Angular4 - Using Enum in HTML Template ngSwitch / ngSwitchCase
Solution here: https://stackoverflow.com/a/42464835/802196
credit: @snorkpete
In your component, you have
enum MyEnum{
First,
Second
}
Then in your component, you bring in the Enum type via a member 'MyEnum', and create another member for your enum variable 'myEnumVar' :
export class MyComponent{
MyEnum = MyEnum;
myEnumVar:MyEnum = MyEnum.Second
...
}
You can now use myEnumVar and MyEnum in your .html template. Eg, Using Enums in ngSwitch:
<div [ngSwitch]="myEnumVar">
<div *ngSwitchCase="MyEnum.First"><app-first-component></app-first-component></div>
<div *ngSwitchCase="MyEnum.Second"><app-second-component></app-second-component></div>
<div *ngSwitchDefault>MyEnumVar {{myEnumVar}} is not handled.</div>
</div>
I'd set up your HTML like so:
<img src="../images/bottle.jpg" alt="bottle" class="thumbnails" id="bottle" />
Then use the following code:
<script>
var images = document.getElementsByTagName("img");
for(var i = 0; i < images.length; i++) {
var image = images[i];
image.onclick = function(event) {
window.location.href = this.id + '.html';
};
}
</script>
That assigns an onclick
event handler to every image on the page (this may not be what you want, you can limit it further if necessary) that changes the current page to the value of the images id
attribute plus the .html
extension. It's essentially the pure Javascript implementation of @JanPöschko's jQuery answer.
Use the logging
module:
import logging as log
…
args = p.parse_args()
if args.verbose:
log.basicConfig(format="%(levelname)s: %(message)s", level=log.DEBUG)
log.info("Verbose output.")
else:
log.basicConfig(format="%(levelname)s: %(message)s")
log.info("This should be verbose.")
log.warning("This is a warning.")
log.error("This is an error.")
All of these automatically go to stderr
:
% python myprogram.py
WARNING: This is a warning.
ERROR: This is an error.
% python myprogram.py -v
INFO: Verbose output.
INFO: This should be verbose.
WARNING: This is a warning.
ERROR: This is an error.
For more info, see the Python Docs and the tutorials.
On Windows when you are using PowerShell you have to enclose all parameters with quotes.
So if you want to create a maven webapp archetype you would do as follows:
Prerequisites:
Howto:
Note: This is tested only on windows 10 powershell
Try this:
var divFirst = document.getElementById("divFirst");
divFirst.style.visibility = 'visible';
divFirst.style.display = 'block';
divFirst.tabIndex = "-1";
divFirst.focus();
e.g @:
Java is giving you the choice to restrict exceptions in the parent class, because it's assuming the client will restrict what is caught. IMHO you should essentially never use this "feature", because your clients may need flexibility down the road.
Java is an old language that is poorly designed. Modern languages don't have such restrictions.
The easiest way around this flaw is make your base class throw Exception
always. Clients can throw more specific Exceptions but make your base classes really broad.
To avoid problems try intval($var)
. Some examples:
<?php
echo intval(42); // 42
echo intval(4.2); // 4
echo intval('42'); // 42
echo intval('+42'); // 42
echo intval('-42'); // -42
echo intval(042); // 34 (octal as starts with zero)
echo intval('042'); // 42
echo intval(1e10); // 1410065408
echo intval('1e10'); // 1
echo intval(0x1A); // 26 (hex as starts with 0x)
echo intval(42000000); // 42000000
echo intval(420000000000000000000); // 0
echo intval('420000000000000000000'); // 2147483647
echo intval(42, 8); // 42
echo intval('42', 8); // 34
echo intval(array()); // 0
echo intval(array('foo', 'bar')); // 1
?>
You need to change permissions on the folder bootstrap/css. Your super user may be able to access it but it doesn't mean apache or nginx have access to it, that's why you still need to change the permissions.
Tip: I usually make the apache/nginx's user group owner of that kind of folders and give 775 permission to it.
@cr05s19xx suggested on a duplicate question:
JavaScript is a bit funny when it comes to numbers and addition.
Giving the following
'20' - '30' = 10; // returns 10 as a number '20' + '30' = '2030'; // Returns them as a string The values returned from document.getElementById are strings, so it's better to parse them all (even the one that works) to number, before proceeding with the addition or subtraction. Your code can be:
function myFunction() {
var per = parseInt(document.getElementById('input1').value);
var num = parseInt(document.getElementById('input2').value);
var sum = (num / 100) * per;
var output = num - sum;
console.log(output);
document.getElementById('demo').innerHTML = output;
}
function myFunction2() {
var per = parseInt(document.getElementById('input3').value);
var num = parseInt(document.getElementById('input4').value);
var sum = (num / 100) * per;
var output = sum + num;
console.log(output);
document.getElementById('demo1').innerHTML = output;
}
How to flush output of Python print?
I suggest five ways of doing this:
print(..., flush=True)
(the flush argument is not available in Python 2's print function, and there is no analogue for the print statement).file.flush()
on the output file (we can wrap python 2's print function to do this), for example, sys.stdout
print = partial(print, flush=True)
applied to the module global.-u
) passed to the interpreter commandPYTHONUNBUFFERED=TRUE
(and unset the variable to undo this).Using Python 3.3 or higher, you can just provide flush=True
as a keyword argument to the print
function:
print('foo', flush=True)
They did not backport the flush
argument to Python 2.7 So if you're using Python 2 (or less than 3.3), and want code that's compatible with both 2 and 3, may I suggest the following compatibility code. (Note the __future__
import must be at/very "near the top of your module"):
from __future__ import print_function
import sys
if sys.version_info[:2] < (3, 3):
old_print = print
def print(*args, **kwargs):
flush = kwargs.pop('flush', False)
old_print(*args, **kwargs)
if flush:
file = kwargs.get('file', sys.stdout)
# Why might file=None? IDK, but it works for print(i, file=None)
file.flush() if file is not None else sys.stdout.flush()
The above compatibility code will cover most uses, but for a much more thorough treatment, see the six
module.
Alternatively, you can just call file.flush()
after printing, for example, with the print statement in Python 2:
import sys
print 'delayed output'
sys.stdout.flush()
flush=True
You can change the default for the print function by using functools.partial on the global scope of a module:
import functools
print = functools.partial(print, flush=True)
if you look at our new partial function, at least in Python 3:
>>> print = functools.partial(print, flush=True)
>>> print
functools.partial(<built-in function print>, flush=True)
We can see it works just like normal:
>>> print('foo')
foo
And we can actually override the new default:
>>> print('foo', flush=False)
foo
Note again, this only changes the current global scope, because the print name on the current global scope will overshadow the builtin print
function (or unreference the compatibility function, if using one in Python 2, in that current global scope).
If you want to do this inside a function instead of on a module's global scope, you should give it a different name, e.g.:
def foo():
printf = functools.partial(print, flush=True)
printf('print stuff like this')
If you declare it a global in a function, you're changing it on the module's global namespace, so you should just put it in the global namespace, unless that specific behavior is exactly what you want.
I think the best option here is to use the -u
flag to get unbuffered output.
$ python -u script.py
or
$ python -um package.module
From the docs:
Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and stderr in binary mode.
Note that there is internal buffering in file.readlines() and File Objects (for line in sys.stdin) which is not influenced by this option. To work around this, you will want to use file.readline() inside a while 1: loop.
You can get this behavior for all python processes in the environment or environments that inherit from the environment if you set the environment variable to a nonempty string:
e.g., in Linux or OSX:
$ export PYTHONUNBUFFERED=TRUE
or Windows:
C:\SET PYTHONUNBUFFERED=TRUE
from the docs:
PYTHONUNBUFFERED
If this is set to a non-empty string it is equivalent to specifying the -u option.
Here's the help on the print function from Python 2.7.12 - note that there is no flush
argument:
>>> from __future__ import print_function
>>> help(print)
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
just to add a detail to what Tamlyn wrote,
instead of
$('form').get(0).setAttribute('action', 'baz'); //this works
$('form')[0].setAttribute('action', 'baz');
works equally well
I ran this test before stumbling upon the discussion here. However, having run it I thought I'd at least post my results.
I stole and bastardized the example in Jeff Friedl's "Mastering Regular Expressions". This is on a macbook running OSX 10.6 (2Ghz intel core 2 duo, 4GB ram). Python version is 2.6.1.
Run 1 - using re.compile
import re
import time
import fpformat
Regex1 = re.compile('^(a|b|c|d|e|f|g)+$')
Regex2 = re.compile('^[a-g]+$')
TimesToDo = 1000
TestString = ""
for i in range(1000):
TestString += "abababdedfg"
StartTime = time.time()
for i in range(TimesToDo):
Regex1.search(TestString)
Seconds = time.time() - StartTime
print "Alternation takes " + fpformat.fix(Seconds,3) + " seconds"
StartTime = time.time()
for i in range(TimesToDo):
Regex2.search(TestString)
Seconds = time.time() - StartTime
print "Character Class takes " + fpformat.fix(Seconds,3) + " seconds"
Alternation takes 2.299 seconds
Character Class takes 0.107 seconds
Run 2 - Not using re.compile
import re
import time
import fpformat
TimesToDo = 1000
TestString = ""
for i in range(1000):
TestString += "abababdedfg"
StartTime = time.time()
for i in range(TimesToDo):
re.search('^(a|b|c|d|e|f|g)+$',TestString)
Seconds = time.time() - StartTime
print "Alternation takes " + fpformat.fix(Seconds,3) + " seconds"
StartTime = time.time()
for i in range(TimesToDo):
re.search('^[a-g]+$',TestString)
Seconds = time.time() - StartTime
print "Character Class takes " + fpformat.fix(Seconds,3) + " seconds"
Alternation takes 2.508 seconds
Character Class takes 0.109 seconds
Swift 3.0:
let userInterface = UIDevice.current.userInterfaceIdiom
if(userInterface == .pad){
//iPads
}else if(userInterface == .phone){
//iPhone
}else if(userInterface == .carPlay){
//CarPlay
}else if(userInterface == .tv){
//AppleTV
}
I can't comment yet, but it should be mentioned that if you use numpy array with more than one element this will fail:
if l:
print "list has items"
elif not l:
print "list is empty"
the error will be:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
I found the root cause of this (we got both "adding window failed" and file descriptor leak as mvds says).
There is a bug in BitmapFactory.decodeFileDescriptor()
of Android 4.4.
It only occurs when inPurgeable
and inInputShareable
of BitmapOptions
are set to true
. This causes many problem in many places interact with files.
Note that the method is also called from MediaStore.Images.Thumbnails.getThumbnail()
.
Universal Image Loader is affected by this issue. Picasso and Glide seems to be not affected. https://github.com/nostra13/Android-Universal-Image-Loader/issues/1020
While AngularJS allows you to get a hand on a click event (and thus a target of it) with the following syntax (note the $event
argument to the setMaster
function; documentation here: http://docs.angularjs.org/api/ng.directive:ngClick):
function AdminController($scope) {
$scope.setMaster = function(obj, $event){
console.log($event.target);
}
}
this is not very angular-way of solving this problem. With AngularJS the focus is on the model manipulation. One would mutate a model and let AngularJS figure out rendering.
The AngularJS-way of solving this problem (without using jQuery and without the need to pass the $event
argument) would be:
<div ng-controller="AdminController">
<ul class="list-holder">
<li ng-repeat="section in sections" ng-class="{active : isSelected(section)}">
<a ng-click="setMaster(section)">{{section.name}}</a>
</li>
</ul>
<hr>
{{selected | json}}
</div>
where methods in the controller would look like this:
$scope.setMaster = function(section) {
$scope.selected = section;
}
$scope.isSelected = function(section) {
return $scope.selected === section;
}
Here is the complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/WXJ3p/15/
In both: Anaconda prompt and the old cmd.exe, you change your directory by first changing to the drive you want, by simply writing its name followed by a ':
', exe: F:
, which will take you to the drive named 'F' on your machine. Then using the command cd
to navigate your way inside that drive as you normally would.
I always used the FileSystemObject
for this sort of thing. Here's a little wrapper function I used. Be sure to reference the Microsoft Scripting Runtime
.
Function StripFilename(sPathFile As String) As String
'given a full path and file, strip the filename off the end and return the path
Dim filesystem As New FileSystemObject
StripFilename = filesystem.GetParentFolderName(sPathFile) & "\"
Exit Function
End Function
EDIT
Here are two versions. One using ArrayList
and other using HashSet
Compare them and create your own version from this, until you get what you need.
This should be enough to cover the:
P.S: It is not a school assignment :) So if you just guide me it will be enough
part of your question.
continuing with the original answer:
You may use a java.util.Collection
and/or java.util.ArrayList
for that.
The retainAll method does the following:
Retains only the elements in this collection that are contained in the specified collection
see this sample:
import java.util.Collection;
import java.util.ArrayList;
import java.util.Arrays;
public class Repeated {
public static void main( String [] args ) {
Collection listOne = new ArrayList(Arrays.asList("milan","dingo", "elpha", "hafil", "meat", "iga", "neeta.peeta"));
Collection listTwo = new ArrayList(Arrays.asList("hafil", "iga", "binga", "mike", "dingo"));
listOne.retainAll( listTwo );
System.out.println( listOne );
}
}
EDIT
For the second part ( similar values ) you may use the removeAll method:
Removes all of this collection's elements that are also contained in the specified collection.
This second version gives you also the similar values and handles repeated ( by discarding them).
This time the Collection
could be a Set
instead of a List
( the difference is, the Set doesn't allow repeated values )
import java.util.Collection;
import java.util.HashSet;
import java.util.Arrays;
class Repeated {
public static void main( String [] args ) {
Collection<String> listOne = Arrays.asList("milan","iga",
"dingo","iga",
"elpha","iga",
"hafil","iga",
"meat","iga",
"neeta.peeta","iga");
Collection<String> listTwo = Arrays.asList("hafil",
"iga",
"binga",
"mike",
"dingo","dingo","dingo");
Collection<String> similar = new HashSet<String>( listOne );
Collection<String> different = new HashSet<String>();
different.addAll( listOne );
different.addAll( listTwo );
similar.retainAll( listTwo );
different.removeAll( similar );
System.out.printf("One:%s%nTwo:%s%nSimilar:%s%nDifferent:%s%n", listOne, listTwo, similar, different);
}
}
Output:
$ java Repeated
One:[milan, iga, dingo, iga, elpha, iga, hafil, iga, meat, iga, neeta.peeta, iga]
Two:[hafil, iga, binga, mike, dingo, dingo, dingo]
Similar:[dingo, iga, hafil]
Different:[mike, binga, milan, meat, elpha, neeta.peeta]
If it doesn't do exactly what you need, it gives you a good start so you can handle from here.
Question for the reader: How would you include all the repeated values?
I tried Marco's steps but no luck. Instead if you just get the latest m2e plugin from the link he provides and one by one right click on each project -> Maven -> Update Dependencies the error still pops up but the issue is resolved. That is to say the warnings disappear in the Markers view. I encountered this issue after importing some projects into SpringSource Tool Suite (STS). When I returned to my Eclipse Juno installation the warnings were displaying. Seeing that I had m2e 1.1 already installed I tried Marco's steps to no avail. Getting the latest version fixed it however.
Comparison of strings is very easy in Ruby:
v1 = "string1"
v2 = "string2"
puts v1 == v2 # prints false
puts "hello"=="there" # prints false
v1 = "string2"
puts v1 == v2 # prints true
Make sure your var2 is not an array (which seems to be like)
Same issue with mine.
New to Flutter. I'm using VS build-in terminal to do flutter run
, to run the app in iPhone. It gives me error Error when reading 'lib/student_model.dart': No such file...
, which is an old code version in my code. I have changed it to lib/model/student_model.dart
.
And I search this line 'lib/student_model.dart'in the project, it appears file
kernel_snapshot.d` containing it. So, it build the project with old code version.
For me, Flutter clean
is not working. Restart VS fix the issue, not sure the problem is due to Flutter or VS?
And I'm wondering if there is some command to just build flutter project without run?
I would try to solve this without VBA. Just select this space and use replace (change to nothing) on that worksheet you're trying to get rid off those spaces.
If you really want to use VBA I believe you could select first character
strSpace = left(range("A1").Value,1)
and use replace function in VBA the same way
Range("A1").Value = Replace(Range("A1").Value, strSpace, "")
or
for each cell in selection.cells
cell.value = replace(cell.value, strSpace, "")
next
I needed to enable the JUnit plugin, after I linked my project with the jar files.
To enable the JUnit plugin, go to File->Settings, type "JUnit" in the search bar, and under "Plugins," check "JUnit.
vikingsteve's advice above will probably get the libraries linked right. Otherwise, open File->Project Structure, go to Libraries, hit the plus, and then browse to
C:\Program Files (x86)\JetBrains\IntelliJ IDEA Community Edition 14.1.1\lib\
and add these jar files:
hamcrest-core-1.3.jar
junit-4.11.jar
junit.jar
I had the same issue when starting a ms c++ 2010 project from scratch - I removed all of the header files generated by ms and but used:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main() {
cout << "hey" << endl;
return 0;
}
I had to include stdafx.h
as it caused an error not having it in.
git log --format="%H" -n 1
Use the above command to get the commitid, hope this helps.
Submit a form that contains an input with value of canvas toDataURL('image/png') e.g
//JAVASCRIPT
var canvas = document.getElementById("canvas");
var url = canvas.toDataUrl('image/png');
Insert the value of the url to your hidden input on form element.
//PHP
$data = $_POST['photo'];
$data = str_replace('data:image/png;base64,', '', $data);
$data = base64_decode($data);
file_put_contents("i". rand(0, 50).".png", $data);
update TABLENAME
set COLUMNNAME = COLUMNNAME + 1
where id = 'YOURID'
Try this:
HTML:
<input type="submit" value="submit" name="submit" onclick="myfunction()">
jQuery:
<script type="text/javascript">
function myfunction()
{
var url = $(location).attr('href');
$('#spn_url').html('<strong>' + url + '</strong>');
}
</script>
git branch --contains <ref>
is the most obvious "porcelain" command to do this. If you want to do something similar with only "plumbing" commands:
COMMIT=$(git rev-parse <ref>) # expands hash if needed
for BRANCH in $(git for-each-ref --format "%(refname)" refs/heads); do
if $(git rev-list $BRANCH | fgrep -q $COMMIT); then
echo $BRANCH
fi
done
(crosspost from this SO answer)
In SQL Server , cast text as datetime
select cast('5/21/2013 9:45:48' as datetime)
It is possible to make noncase sensitive URLs
RewriteEngine on
rewritemap lowercase int:tolower
RewriteCond $1 [A-Z]
RewriteRule ^/(.*)$ /${lowercase:$1} [R=301,L]
Making Google.com..GOOGLE.com etc direct to google.com
you have to use rewrite to pass params using proxy_pass here is example I did for angularjs app deployment to s3
S3 Static Website Hosting Route All Paths to Index.html
adopted to your needs would be something like
location /service/ {
rewrite ^\/service\/(.*) /$1 break;
proxy_pass http://apache;
}
if you want to end up in http://127.0.0.1:8080/query/params/
if you want to end up in http://127.0.0.1:8080/service/query/params/ you'll need something like
location /service/ {
rewrite ^\/(.*) /$1 break;
proxy_pass http://apache;
}
You cannot change the DataType after the Datatable is filled with data. However, you can clone the Data table, change the column type and load data from previous data table to the cloned table as shown below.
DataTable dtCloned = dt.Clone();
dtCloned.Columns[0].DataType = typeof(Int32);
foreach (DataRow row in dt.Rows)
{
dtCloned.ImportRow(row);
}
In React Router version 5.0.1 and above, you can use:
<Link to="route" target="_blank" onClick={(event) => {event.preventDefault(); window.open(this.makeHref("route"));}} />
You need to set the path to the headers in the project properties so the compiler looks there when trying to find the header file(s). I can't remember the exact location, but look though the Project properties and you should see it.
The first thing is to make a comparison of functions of SHA and opt for the safest algorithm that supports your programming language (PHP).
Then you can chew the official documentation to implement the hash()
function that receives as argument the hashing algorithm you have chosen and the raw password.
sha256 => 64 bits
sha384 => 96 bits
sha512 => 128 bits
The more secure the hashing algorithm is, the higher the cost in terms of hashing and time to recover the original value from the server side.
$hashedPassword = hash('sha256', $password);
That won't work in IE<9 though, however, you can make IEs support that using:
PIE makes Internet Explorer 6-8 capable of rendering several of the most useful CSS3 decoration features.
You can optionally actually use the get
method of a dict
:
x = {i<100: -1, -10<=i<=10: 0, i>100: 1}.get(True, 2)
You don't need the get
method if one of the keys is guaranteed to evaluate to True
:
x = {i<0: -1, i==0: 0, i>0: 1}[True]
At most one of the keys should ideally evaluate to True
. If more than one key evaluates to True
, the results could seem unpredictable.
Use the backslash before db on the header and you can use it then typically as you wrote it before.
Here is the example:
Use \DB;
Then inside your controller class you can use as you did before, like that ie :
$item = DB::table('items')->get();
Use the onchange event in HTML/standard JavaScript.
In jQuery that is the change() event. For example:
$('element').change(function() { // do something } );
EDIT
After reading some comments, what about:
$(function() {
var content = $('#myContent').val();
$('#myContent').keyup(function() {
if ($('#myContent').val() != content) {
content = $('#myContent').val();
alert('Content has been changed');
}
});
});
It's better to move all logic of working with database to repositores.
So in controller you write
/* you can also inject "FooRepository $repository" using autowire */
$repository = $this->getDoctrine()->getRepository(Foo::class);
$count = $repository->count();
And in Repository/FooRepository.php
public function count()
{
$qb = $repository->createQueryBuilder('t');
return $qb
->select('count(t.id)')
->getQuery()
->getSingleScalarResult();
}
It's better to move $qb = ...
to separate row in case you want to make complex expressions like
public function count()
{
$qb = $repository->createQueryBuilder('t');
return $qb
->select('count(t.id)')
->where($qb->expr()->isNotNull('t.fieldName'))
->andWhere($qb->expr()->orX(
$qb->expr()->in('t.fieldName2', 0),
$qb->expr()->isNull('t.fieldName2')
))
->getQuery()
->getSingleScalarResult();
}
Also think about caching your query result - http://symfony.com/doc/current/reference/configuration/doctrine.html#caching-drivers
public function count()
{
$qb = $repository->createQueryBuilder('t');
return $qb
->select('count(t.id)')
->getQuery()
->useQueryCache(true)
->useResultCache(true, 3600)
->getSingleScalarResult();
}
In some simple cases using EXTRA_LAZY
entity relations is good
http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/tutorials/extra-lazy-associations.html
Sharing another option found here with credentials
JENKINS_HOST=username:[email protected]:port
curl -sSL "http://$JENKINS_HOST/pluginManager/api/xml?depth=1&xpath=/*/*/shortName|/*/*/version&wrapper=plugins" | perl -pe 's/.*?<shortName>([\w-]+).*?<version>([^<]+)()(<\/\w+>)+/\1 \2\n/g'|sed 's/ /:/'
You can use PowerShell too (same as me).
For example:
rm $env:LOCALAPPDATA\NuGet\Cache\*.nupkg
Or 'quiet' mode (without error messages):
rm $env:LOCALAPPDATA\NuGet\Cache\*.nupkg 2> $null
Try adding -Xmx for more memory ( java -Xmx1024M YourClass
), and don't forget to stop referencing variables you don't need any more (memory leaks).
One another point to note down is in MaxLength attribute you can only provide max required range not a min required range. While in StringLength you can provide both.
I found using okHttp a lot easier as I could not get any of these solutions to work: https://stackoverflow.com/a/37942387/447549
See Request.setRetryPolicy()
and the constructor for DefaultRetryPolicy
, e.g.
JsonObjectRequest myRequest = new JsonObjectRequest(Method.GET,
url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error: " + error.getMessage());
}
});
myRequest.setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
I faced same issue. After downloading everything, still 'punkt' error was there. I searched package on my windows machine at C:\Users\vaibhav\AppData\Roaming\nltk_data\tokenizers and I can see 'punkt.zip' present there. I realized that somehow the zip has not been extracted into C:\Users\vaibhav\AppData\Roaming\nltk_data\tokenizers\punk. Once I extracted the zip, it worked like music.
Edit: Another (slightly better) way of doing what I'm suggesting is answered here: Django form input field styling
All the above options are awesome, just thought I'd throw in this one because it's different.
If you want custom styling, classes, etc. on your forms, you can make an html input in your template that matches your form field. For a CharField, for example, (default widget is TextInput
), let's say you want a bootstrap-looking text input. You would do something like this:
<input type="text" class="form-control" name="form_field_name_here">
And as long as you put the form field name matches the html name
attribue, (and the widget probably needs to match the input type as well) Django will run all the same validators on that field when you run validate
or form.is_valid()
and
Styling other things like labels, error messages, and help text don't require much workaround because you can do something like form.field.error.as_text
and style them however you want. The actual fields are the ones that require some fiddling.
I don't know if this is the best way, or the way I would recommend, but it is a way, and it might be right for someone.
Here's a useful walkthrough of styling forms and it includes most of the answers listed on SO (like using the attr on the widgets and widget tweaks). https://simpleisbetterthancomplex.com/article/2017/08/19/how-to-render-django-form-manually.html
I know this one is already too late. But we can fetch root URL by two methods
1st method
var path = require('path');
path.dirname(require.main.filename);
2nd method
var path = require('path');
path.dirname(process.mainModule.filename);
Reference Link:- https://gist.github.com/geekiam/e2e3e0325abd9023d3a3
In C++11, you can use std::any_of
instead.
An example to find if there is any zero in the array:
std::array<int,3> foo = {0,1,-1};
if ( std::any_of(foo.begin(), foo.end(), [](int i){return i==0;}) )
std::cout << "zero found...";
Just pass in the current Context to the Adapter constructor and store it as a field. Then inside the onClick you can use that context to call startActivity().
pseudo-code
public class MyAdapter extends Adapter {
private Context context;
public MyAdapter(Context context) {
this.context = context;
}
public View getView(...){
View v;
v.setOnClickListener(new OnClickListener() {
void onClick() {
context.startActivity(...);
}
});
}
}
you can use ssl for your host there is free project for ssl like letsencrypt https://letsencrypt.org/
Since Beautiful Soup 4.4.0.
a parameter called string
does the work that text
used to do in the previous versions.
string
is for finding strings, you can combine it with arguments that find tags: Beautiful Soup will find all tags whose .string matches your value for the string. This code finds the tags whose .string is “Elsie”:
soup.find_all("td", string="Elsie")
For more information about string have a look this section https://www.crummy.com/software/BeautifulSoup/bs4/doc/#the-string-argument
I also faced similar problem while working on Affable Bean e-commerce site development. I received an error:
Module has not been deployed.
I checked the sun-resources.xml
file and found the following statements which resulted in the error.
<resources>
<jdbc-resource enabled="true"
jndi-name="jdbc/affablebean"
object-type="user"
pool-name="AffableBeanPool">
</jdbc-resource>
<jdbc-connection-pool allow-non-component-callers="false"
associate-with-thread="false"
connection-creation-retry-attempts="0"
connection-creation-retry-interval-in-seconds="10"
connection-leak-reclaim="false"
connection-leak-timeout-in-seconds="0"
connection-validation-method="auto-commit"
datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource"
fail-all-connections="false"
idle-timeout-in-seconds="300"
is-connection-validation-required="false"
is-isolation-level-guaranteed="true"
lazy-connection-association="false"
lazy-connection-enlistment="false"
match-connections="false"
max-connection-usage-count="0"
max-pool-size="32"
max-wait-time-in-millis="60000"
name="AffableBeanPool"
non-transactional-connections="false"
pool-resize-quantity="2"
res-type="javax.sql.ConnectionPoolDataSource"
statement-timeout-in-seconds="-1"
steady-pool-size="8"
validate-atmost-once-period-in-seconds="0"
wrap-jdbc-objects="false">
<description>Connects to the affablebean database</description>
<property name="URL" value="jdbc:mysql://localhost:3306/affablebean"/>
<property name="User" value="root"/>
<property name="Password" value="nbuser"/>
</jdbc-connection-pool>
</resources>
Then I changed the statements to the following which is simple and works. I was able to run the file successfully.
<resources>
<jdbc-resource enabled="true" jndi-name="jdbc/affablebean" object-type="user" pool-name="AffablebeanPool">
<description/>
</jdbc-resource>
<jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit" datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false" max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="AffablebeanPool" non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.ConnectionPoolDataSource" statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
<property name="URL" value="jdbc:mysql://localhost:3306/AffableBean"/>
<property name="User" value="root"/>
<property name="Password" value="nbuser"/>
</jdbc-connection-pool>
</resources>
On your own system, try
install.packages("foo", dependencies=...)
with the dependencies=
argument is documented as
dependencies: logical indicating to also install uninstalled packages
which these packages depend on/link to/import/suggest (and so
on recursively). Not used if ‘repos = NULL’. Can also be a
character vector, a subset of ‘c("Depends", "Imports",
"LinkingTo", "Suggests", "Enhances")’.
Only supported if ‘lib’ is of length one (or missing), so it
is unambiguous where to install the dependent packages. If
this is not the case it is ignored, with a warning.
The default, ‘NA’, means ‘c("Depends", "Imports",
"LinkingTo")’.
‘TRUE’ means (as from R 2.15.0) to use ‘c("Depends",
"Imports", "LinkingTo", "Suggests")’ for ‘pkgs’ and
‘c("Depends", "Imports", "LinkingTo")’ for added
dependencies: this installs all the packages needed to run
‘pkgs’, their examples, tests and vignettes (if the package
author specified them correctly).
so you probably want a value TRUE
.
In your package, list what is needed in Depends:
, see the
Writing R Extensions manual which is pretty clear on this.
Use std::make_pair
:
revenue.push_back(std::make_pair("string",map[i].second));
One idea would be to winsorize the data in a two-pass procedure:
run a first pass, learn what the bounds are, e.g. cut of at given percentile, or N standard deviation above the mean, or ...
in a second pass, set the values beyond the given bound to the value of that bound
I should stress that this is an old-fashioned method which ought to be dominated by more modern robust techniques but you still come across it a lot.
you can use System.Diagnostics.Process.Start as well as WIN32 ShellExecute function by means of interop, for opening PDF files using the default viewer:
System.Diagnostics.Process.Start("SOMEAPP.EXE","Path/SomeFile.Ext");
[System.Runtime.InteropServices.DllImport("shell32. dll")]
private static extern long ShellExecute(Int32 hWnd, string lpOperation,
string lpFile, string lpParameters,
string lpDirectory, long nShowCmd);
Another approach is to place a WebBrowser Control into your Form and then use the Navigate method for opening the PDF file:
ThewebBrowserControl.Navigate(@"c:\the_file.pdf");
The skipping elements bug in this (code from above)
var len = cells.length;
for(var i = 0; i < len; i++) {
if(cells[i].className.toLowerCase() == "column") {
cells[i].parentNode.removeChild(cells[i]);
}
}
can be fixed by just running the loop backwards as follows (so that the temporary array is not needed)
var len = cells.length;
for(var i = len-1; i >-1; i--) {
if(cells[i].className.toLowerCase() == "column") {
cells[i].parentNode.removeChild(cells[i]);
}
}
HTML Markup
<select id="select">
<option value="1" data-foo="dogs">this</option>
<option value="2" data-foo="cats">that</option>
<option value="3" data-foo="gerbils">other</option>
</select>
Code
// JavaScript using jQuery
$(function(){
$('select').change(function(){
var selected = $(this).find('option:selected');
var extra = selected.data('foo');
...
});
});
// Plain old JavaScript
var sel = document.getElementById('select');
var selected = sel.options[sel.selectedIndex];
var extra = selected.getAttribute('data-foo');
See this as a working sample using jQuery here: http://jsfiddle.net/GsdCj/1/
See this as a working sample using plain JavaScript here: http://jsfiddle.net/GsdCj/2/
By using data attributes from HTML5 you can add extra data to elements in a syntactically-valid manner that is also easily accessible from jQuery.
You're receiving this error because you did not pass a data
variable to the DHT constructor.
aIKid and Alexander's answers are nice but it wont work because you still have to initialize self.data
in the class constructor like this:
class DHT:
def __init__(self, data=None):
if data is None:
data = {}
else:
self.data = data
self.data['one'] = '1'
self.data['two'] = '2'
self.data['three'] = '3'
def showData(self):
print(self.data)
And then calling the method showData like this:
DHT().showData()
Or like this:
DHT({'six':6,'seven':'7'}).showData()
or like this:
# Build the class first
dht = DHT({'six':6,'seven':'7'})
# The call whatever method you want (In our case only 1 method available)
dht.showData()
You can simply use String.Join function, and as separator use string.Empty
because it uses StringBuilder
internally.
string result = string.Join(string.Empty, new []{0,1,2,3,0,1});
E.g.: If you use semicolon as separator, the result would be 0;1;2;3;0;1
.
It actually works with null separator, and second parameter can be enumerable of any objects, like:
string result = string.Join(null, new object[]{0,1,2,3,0,"A",DateTime.Now});
I want to let everyone know that sometimes this error just is a result of some weird memory error. Restart your pc and go back into visual studio and it will be gone!! Bizarre! Try that before you start playing around with your web config file etc like I did!!!! ;-)
Simply use syntax below get and set
GET
//Script
var a = $("#selectIndex").val();
here a variable will hold the value of hiddenfield(selectindex)
Server side
<asp:HiddenField ID="selectIndex" runat="server" Value="0" />
SET
var a =10;
$("#selectIndex").val(a);
In my case the PHP-script itself returned 404 code. Had nothing to do with nginx.
In:
for i in range(c/10):
You're creating a float as a result - to fix this use the int division operator:
for i in range(c // 10):
For the final, compiled code of your application, the short answer is “no”. Different tools are able to extract different information from the code (e.g. the forms setups) and there are P code decompilers (see Edgar's excellent link for such tools). However, up to this day, there is no decompiler for native code. I'm not aware of anything similar for other high-level languages either.
Completely reset?
Delete the .git
directory locally.
Recreate the git repostory:
$ cd (project-directory)
$ git init
$ (add some files)
$ git add .
$ git commit -m 'Initial commit'
Push to remote server, overwriting. Remember you're going to mess everyone else up doing this … you better be the only client.
$ git remote add origin <url>
$ git push --force --set-upstream origin master
Try using ,
$('#points').val(request.responseText);
Here are the simple ways to every date format confusions:
for current date:
var current_date=new Date();
to get the Timestamp of current date:
var timestamp=new Date().getTime();
to convert a particular Date into Timestamp:
var timestamp_formation=new Date('mm/dd/yyyy').getTime();
to convert timestamp into Date:
var timestamp=new Date('02/10/2016').getTime();
var todate=new Date(timestamp).getDate();
var tomonth=new Date(timestamp).getMonth()+1;
var toyear=new Date(timestamp).getFullYear();
var original_date=tomonth+'/'+todate+'/'+toyear;
OUTPUT:
02/10/2016
I'm assuming that you wish to write software to do this. To do it naively you would just find lines and set the vectors. To do it intelligently, you attempt to fit shapes onto the drawing (model fitting). Additionally, you should attempt to ascertain bitmaped regions (regions you can't model through shames or applying textures. I would not recommend going this route as that it will take quite a bit of time and require a bit of graphics and computer vision knowledge. However, the output will much and scale much better than your original output.
look at this url Android adb devices unauthorized else briefly do the following:
C:\Users\*username*\.android
) and delete adbkeyC:\Windows\System32\config\systemprofile\.android
and delete adbkeyYou may find it in one of the directories above. Or just search adbkey in the Parent folders above then locate and delete.
You can try also with userInput.bat which uses the html input element.
This will assign the input to the value jstackId:
call userInput.bat jstackId
echo %jstackId%
This will just print the input value which eventually you can capture with FOR /F
:
call userInput.bat
For measuring distances with a single camera, you need to know some numbers. To measure height of something, say a chair, the only thing you have is the the size of it in the camera (which is in pixels, and can be converted to inches using screen size), that is all. The chance of measuring the height and width is using a reference, say a 6 foot tall person standing next to the chair.
This way you can work out in reverse using say a 10 foot tall object, using its size as appearing in the camera, you can work out the size of things at the same distance, on a surface that is not flat, even ensuring that they are at the same distance is a challenge.
So using the camera and just the camera, it is not possible. You need to know distance somehow, or need a reference.
If you are using the application to measure height of items you know the location of, then using GPS, you can find distance, and rest is math.
I have found some links using Google, they may help.
They may help you to find out what other information is needed other than what the camera can provide, so that you can think about your application as well regarding what can be done and what are the limitations.
One way is using multiple cameras, and that can be compensated using multiple pictures taken a known distance away. So the application can ask the user to take multiple images, track the distance using GPS, and probably it can work.
See these links as well:
I figured it out. I had an error in my cloud formation template that was creating the EC2 instances. As a result, the EC2 instances that were trying to access the above code deploy buckets, were in different regions (not us-west-2). It seems like the access policies on the buckets (owned by Amazon) only allow access from the region they belong in. When I fixed the error in my template (it was wrong parameter map), the error disappeared
Just try socket.disconnect(true)
on the server side by emitting any event from the client side.
Just pressing F5 is not always working.
why?
Because your ISP is also caching web data for you.
Solution: Force Refresh.
Force refresh your browser by pressing CTRL + F5 in Firefox or Chrome to clear ISP cache too, instead of just pressing F5
You then can see 200 response instead of 304 in the browser F12 developer tools network tab.
Another trick is to add question mark ?
at the end of the URL string of the requested page:
http://localhost:52199/Customers/Create?
The question mark will ensure that the browser refresh the request without caching any previous requests.
Additionally in Visual Studio you can set the default browser to Chrome in Incognito mode to avoid cache issues while developing, by adding Chrome in Incognito mode as default browser, see the steps (self illustrated):
Give this a try...
server {
listen 80;
server_name dev.int.com;
access_log off;
location / {
proxy_pass http://IP:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-for $remote_addr;
port_in_redirect off;
proxy_redirect http://IP:8080/jira /;
proxy_connect_timeout 300;
}
location ~ ^/stash {
proxy_pass http://IP:7990;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-for $remote_addr;
port_in_redirect off;
proxy_redirect http://IP:7990/ /stash;
proxy_connect_timeout 300;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/local/nginx/html;
}
}
You can't effectively use Distinct
on a collection of objects (without additional work). I will explain why.
It uses the default equality comparer,
Default
, to compare values.
For objects that means it uses the default equation method to compare objects (source). That is on their hash code. And since your objects don't implement the GetHashCode()
and Equals
methods, it will check on the reference of the object, which are not distinct.
try
block should be around open. Not around prompt.
while True:
prompt = input("\n Hello to Sudoku valitator,"
"\n \n Please type in the path to your file and press 'Enter': ")
try:
sudoku = open(prompt, 'r').readlines()
except FileNotFoundError:
print("Wrong file or file path")
else:
break
Simple Image upload in codeigniter
Find below code for easy image upload
public function doupload()
{
$upload_path="https://localhost/project/profile"
$uid='10'; //creare seperate folder for each user
$upPath=upload_path."/".$uid;
if(!file_exists($upPath))
{
mkdir($upPath, 0777, true);
}
$config = array(
'upload_path' => $upPath,
'allowed_types' => "gif|jpg|png|jpeg",
'overwrite' => TRUE,
'max_size' => "2048000",
'max_height' => "768",
'max_width' => "1024"
);
$this->load->library('upload', $config);
if(!$this->upload->do_upload('userpic'))
{
$data['imageError'] = $this->upload->display_errors();
}
else
{
$imageDetailArray = $this->upload->data();
$image = $imageDetailArray['file_name'];
}
}
Hope this helps you to upload image
Use the Columns Property and set the Auto Size Mode to All Cells, Resizable to True, Frozen to False and visible to True.
The column will automatically resize based on the data inserted.
You can use the below code to generate a random number that will always be 6 digits:
Math.random().toString().substr(2, 6)
Hope this works for everyone :)
Briefly how this works is Math.random()
generates a random number between 0 and 1 which we convert to a string and using .toString()
and take a 6 digit sample from said string using .substr()
with the parameters 2, 6
to start the sample from the 2nd char and continue it for 6 characters.
This can be used for any length number.
If you want to do more reading on this here are some links to the docs to save you some googling:
Math.random()
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
.toString()
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString
.substr()
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr
(This answer was updated, as the previous method using vq
isn't recognized anymore.)
Specifying the height of the video will change the quality accordingly. example for html 5;
<iframe style='width:100%; height:800px;' src='https://www.youtube.com/embed/xxxxxxxx'></iframe>
If you don't want to hardcode the width and height you can add a class to the iframe for css media queries.
Tested on a working server + passes the w3.org nuhtml validator.
It's simply “No such directory entry”. Since directory entries can be directories or files (or symlinks, or sockets, or pipes, or devices), the name ENOFILE
would have been too narrow in its meaning.
$('#drop').change(
function() {
var val1 = $('#pick option:selected').val();
var val2 = $('#drop option:selected').val();
// Do something with val1 and val2 ...
}
);
Working off of Peter Johnson's answer, I created a nice little alias for myself:
alias gcolt="git checkout $(git tag | sort -V | tail -1)"
aka 'git checkout latest tag'.
This relies on the GNU version of sort, which appropriately handles situations like the one lOranger pointed out:
v1.0.1
...
v1.0.9
v1.0.10
If you're on a mac, brew install coreutils
and then call gsort instead.
<button class="myButton" data-id="345" ng-click="doStuff($element.target)">Button</button>
I added class to button to get by querySelector, then get data attribute
var myButton = angular.element( document.querySelector( '.myButton' ) );
console.log( myButton.data( 'id' ) );
As long as strings can be viewed directly as a char array it's going to be really hard to convince me that std::string
represents strings as first class citizens in C++.
Besides, combining allocation and boundedness seems to be a bad idea to me anyways.
Try this
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Disposition: attachment;filename=\"filename.xlsx\"");
header("Cache-Control: max-age=0");
I guess you mean this:
class Value:
def __init__(self, v=None):
self.v = v
v1 = Value(1)
v2 = Value(2)
d = {'a': v1, 'b': v1, 'c': v2, 'd': v2}
d['a'].v += 1
d['b'].v == 2 # True
d['a']
and d['b']
to point to the same value that "updates" as it changes, make the value refer to a mutable object (user-defined class like above, or a dict
, list
, set
).d['a']
, d['b']
changes at same time because they both point to same object.for AndroidX use like
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/ic_add" />
Try using RenderAction("myPartial","Account");
One more time, building off of @RalphyZ
This one doesn't break the exposed API.
from argparse import ArgumentParser, SUPPRESS
# Disable default help
parser = ArgumentParser(add_help=False)
required = parser.add_argument_group('required arguments')
optional = parser.add_argument_group('optional arguments')
# Add back help
optional.add_argument(
'-h',
'--help',
action='help',
default=SUPPRESS,
help='show this help message and exit'
)
required.add_argument('--required_arg', required=True)
optional.add_argument('--optional_arg')
Which will show the same as above and should survive future versions:
usage: main.py [-h] [--required_arg REQUIRED_ARG]
[--optional_arg OPTIONAL_ARG]
required arguments:
--required_arg REQUIRED_ARG
optional arguments:
-h, --help show this help message and exit
--optional_arg OPTIONAL_ARG
List<T>.Add
adds a single element. Instead, use List<T>.AddRange
to add multiple values.
Additionally, List<T>.AddRange
takes an IEnumerable<T>
, so you don't need to convert tripDetails
into a List<TripDetails>
, you can pass it directly, e.g.:
tripDetailsCollection.AddRange(tripDetails);
Very compact, kotlin version:
tvTitle.apply {
text = "foobar"
paint?.isUnderlineText = true
}
Just close the file in case it is opened in the background. The error disappears by itself
In python generally “with” statement is used to open a file, process the data present in the file, and also to close the file without calling a close() method. “with” statement makes the exception handling simpler by providing cleanup activities.
General form of with:
with open(“file name”, “mode”) as file-var:
processing statements
note: no need to close the file by calling close() upon file-var.close()
For anyone else looking for help on this matter, or experiencing a FileNotFoundException or a FirstChanceException, check out my answer here:
In general you must be absolutely certain that you are meeting all of the requirements for making the reference - I know it's the obvious answer, but you're probably overlooking a relatively simple requirement.
In your example you use the href
attribute to tell where the JavaScript file can be found. This should be the src
attribute:
?> <script type="text/javascript" src="file.js"></script> <?php
For more information see w3schools.
Another option without sed
, awk
, perl
, etc
strings $file > $output
strings - print the strings of printable characters in files.
You can use .replace
. For example:
>>> df = pd.DataFrame({'col2': {0: 'a', 1: 2, 2: np.nan}, 'col1': {0: 'w', 1: 1, 2: 2}})
>>> di = {1: "A", 2: "B"}
>>> df
col1 col2
0 w a
1 1 2
2 2 NaN
>>> df.replace({"col1": di})
col1 col2
0 w a
1 A 2
2 B NaN
or directly on the Series
, i.e. df["col1"].replace(di, inplace=True)
.
Either you can use the accessors provided by the Web Storage API or you could write a wrapper/adapter. From your stated issue with defineGetter/defineSetter is sounds like writing a wrapper/adapter is too much work for you.
I honestly don't know what to tell you. Maybe you could reevaluate your opinion of what is a "ridiculous limitation". The Web Storage API is just what it's supposed to be, a key/value store.
Just for the sake of completeness you can just take the wanted data type and add brackets with the number of elements like so:
x <- character(10)
static void Main(string[] args)
{
//---listen at the specified IP and port no.---
IPAddress localAdd = IPAddress.Parse(SERVER_IP);
TcpListener listener = new TcpListener(localAdd, PORT_NO);
Console.WriteLine("Listening...");
listener.Start();
while (true)
{
//---incoming client connected---
TcpClient client = listener.AcceptTcpClient();
//---get the incoming data through a network stream---
NetworkStream nwStream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
//---read incoming stream---
int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
//---convert the data received into a string---
string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received : " + dataReceived);
//---write back the text to the client---
Console.WriteLine("Sending back : " + dataReceived);
nwStream.Write(buffer, 0, bytesRead);
client.Close();
}
listener.Stop();
Console.ReadLine();
}
In addition to @Nudier Mena answer, keep a while loop to keep the server in listening mode. So that we can have multiple instance of client connected.
Imao put UIImageView on background is not the best idea . In my case i added on controller view other 2 views . First view has [UIColor clearColor]
on background, second - color which u want to be transparent (grey in my case).Note that order is important.Then for second view set alpha 0.5(alpha >=0 <=1).Added this to lines in prepareForSegue
infoVC.providesPresentationContextTransitionStyle = YES;
infoVC.definesPresentationContext = YES;
And thats all.
On macOS High Sierra, this solved my issue:
sudo gem update --system -n /usr/local/bin/gem
The getDrawable (int id)
method is deprecated as of API 22.
Instead you should use the getDrawable (int id, Resources.Theme theme)
for API 21+
Code would look something like this.
Drawable myDrawable;
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){
myDrawable = context.getResources().getDrawable(id, context.getTheme());
} else {
myDrawable = context.getResources().getDrawable(id);
}
Thomas Pornin's answer as macros:
#define TICK(X) clock_t X = clock()
#define TOCK(X) printf("time %s: %g sec.\n", (#X), (double)(clock() - (X)) / CLOCKS_PER_SEC)
Use it like this:
TICK(TIME_A);
functionA();
TOCK(TIME_A);
TICK(TIME_B);
functionB();
TOCK(TIME_B);
Output:
time TIME_A: 0.001652 sec.
time TIME_B: 0.004028 sec.
if you need to access your variables for an echo statement within your quotes put your variable inside curly brackets
echo "i need to open my lock with its: {$array['key']}";
Use the DateFormat
API to convert the String into a Date object, then use the Calendar
API to add one day. Let me know if you want specific code examples, and I can update my answer.