I have written one easy step, but because of this performance will be degraded
Here is my code snippet:-
for (int tempReg = 0; tempReg < reg.Matches(lines).Count; tempReg++)
{
foreach (Match match in reg.Matches(lines))
{
var aStringBuilder = new StringBuilder(lines);
aStringBuilder.Insert(startIndex, match.ToString().Replace(",", " ");
lines[k] = aStringBuilder.ToString();
tempReg = 0;
break;
}
}
From the document.getElementsByTagName
I guess you are running the javascript in a browser.
The traditional way to expose functionality to javascript running in the browser is calling a remote URL using AJAX. The X in AJAX is for XML, but nowadays everybody uses JSON instead of XML.
For example, using jQuery you can do something like:
$.getJSON('http://example.com/your/webservice?param1=x¶m2=y',
function(data, textStatus, jqXHR) {
alert(data);
}
)
You will need to implement a python webservice on the server side. For simple webservices I like to use Flask.
A typical implementation looks like:
@app.route("/your/webservice")
def my_webservice():
return jsonify(result=some_function(**request.args))
You can run IronPython (kind of Python.Net) in the browser with silverlight, but I don't know if NLTK is available for IronPython.
Summary: Instead of a.f();
it should be a->f();
In main you have defined a as a pointer to object of A, so you can access functions using the ->
operator.
An alternate, but less readable way is (*a).f()
a.f()
could have been used to access f(), if a was declared as:
A a;
You can use animated background-position property and sprite image.
All the test cases in this post are flawed as they access the same file for each method tested. So disk caching kicks in which tests 2 and 3 benefit from. To prove my point I took test case provided by GHAD and changed the order of enumeration and below are the results.
Looking at result I think File.length() is the winner really.
Order of test is the order of output. You can even see the time taken on my machine varied between executions but File.Length() when not first, and incurring first disk access won.
---
LENGTH sum: 1163351, per Iteration: 4653.404
CHANNEL sum: 1094598, per Iteration: 4378.392
URL sum: 739691, per Iteration: 2958.764
---
CHANNEL sum: 845804, per Iteration: 3383.216
URL sum: 531334, per Iteration: 2125.336
LENGTH sum: 318413, per Iteration: 1273.652
---
URL sum: 137368, per Iteration: 549.472
LENGTH sum: 18677, per Iteration: 74.708
CHANNEL sum: 142125, per Iteration: 568.5
If you want to move the position of the legend please use the following code:
library(reshape2) # for melt
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend()) +
theme(legend.position="bottom")
This should give you the desired result.
Update for mid 2016:
The things are changing so fast that if it's late 2017 this answer might not be up to date anymore!
Beginners can quickly get lost in choice of build tools and workflows, but what's most up to date in 2016 is not using Bower, Grunt or Gulp at all! With help of Webpack you can do everything directly in NPM!
Google "npm as build tool" result: https://medium.com/@dabit3/introduction-to-using-npm-as-a-build-tool-b41076f488b0#.c33e74tsa
Don't get me wrong people use other workflows and I still use GULP in my legacy project(but slowly moving out of it), but this is how it's done in the best companies and developers working in this workflow make a LOT of money!
Look at this template it's a very up-to-date setup consisting of a mixture of the best and the latest technologies: https://github.com/coryhouse/react-slingshot
Your questions:
When I want to add a package (and check in the dependency into git), where does it belong - into package.json or into bower.json
Everything belongs in package.json now
Dependencies required for build are in "devDependencies" i.e. npm install require-dir --save-dev
(--save-dev updates your package.json by adding an entry to devDependencies)
npm install lodash --save
(--save updates your package.json by adding an entry to dependencies)If that is the case, when should I ever install packages explicitly like that without adding them to the file that manages dependencies (apart from installing command line tools globally)?
Always. Just because of comfort. When you add a flag (--save-dev
or --save
) the file that manages deps (package.json) gets updated automatically. Don't waste time by editing dependencies in it manually. Shortcut for npm install --save-dev package-name
is npm i -D package-name
and shortcut for npm install --save package-name
is npm i -S package-name
One of the most (probably the most) easiest way to install site-packages like PyQt5 is installing one of the versions of Anaconda. You can just install many of site-packages by installing it. List of avaliable site-packages with Anaconda versions can be checked here.
For example:
PATH: ....; C:\Anaconda3\Lib\site-packages\PyQt5; ...
I had the same task recently and I used the following for sql server 2012 db. Use management studio and connect to the database you want to search. Then execute the following script.
Select
[tgr].[name] as [trigger name],
[tbl].[name] as [table name]
from sysobjects tgr
join sysobjects tbl
on tgr.parent_obj = tbl.id
WHERE tgr.xtype = 'TR'
I simply added %%time
at the beginning of the cell and got the time. You may use the same on Jupyter Spark cluster/ Virtual environment using the same. Just add %%time
at the top of the cell and you will get the output. On spark cluster using Jupyter, I added to the top of the cell and I got output like below:-
[1] %%time
import pandas as pd
from pyspark.ml import Pipeline
from pyspark.ml.classification import LogisticRegression
import numpy as np
.... code ....
Output :-
CPU times: user 59.8 s, sys: 4.97 s, total: 1min 4s
Wall time: 1min 18s
C isn't as high-level as the scripting language you mention. But if you want to stay away from socket-based programming, try Curl. Curl is a great C library and has many features. I have used it for years and always recommend it. It also includes some stand alone programs for testing or shell use.
Explanation:
This problem occurs because Chrome allows up to 6 open connections by default. So if you're streaming multiple media files simultaneously from 6 <video>
or <audio>
tags, the 7th connection (for example, an image) will just hang, until one of the sockets opens up. Usually, an open connection will close after 5 minutes of inactivity, and that's why you're seeing your .pngs finally loading at that point.
Solution 1:
You can avoid this by minimizing the number of media tags that keep an open connection. And if you need to have more than 6, make sure that you load them last, or that they don't have attributes like preload="auto"
.
Solution 2:
If you're trying to use multiple sound effects for a web game, you could use the Web Audio API. Or to simplify things, just use a library like SoundJS, which is a great tool for playing a large amount of sound effects / music tracks simultaneously.
Solution 3: Force-open Sockets (Not recommended)
If you must, you can force-open the sockets in your browser (In Chrome only):
chrome://net-internals
.Sockets
from the menu.Flush socket pools
button.This solution is not recommended because you shouldn't expect your visitors to follow these instructions to be able to view your site.
You can also define an environment variable that is visible only within Eclipse.
Go to Run -> Run Configurations... and Select tab "Environment".
There you can add several environment variables that will be specific to your application.
I think it should be
$('#fileinput').val();
string result = Regex.Replace(anytext, @"<(.|\n)*?>", string.Empty);
public char lastChar(String s) {
if (s == "" || s == null)
return ' ';
char lc = s.charAt(s.length() - 1);
return lc;
}
When doing pan_list.append(p.last)
you're doing an inplace operation, that is an operation that modifies the object and returns nothing (i.e. None
).
You should do something like this :
last_list=[]
if p.last_name==None or p.last_name=="":
pass
last_list.append(p.last) # Here I modify the last_list, no affectation
print last_list
myFile.renameTo(new File("/the/new/place/newName.file"));
File#renameTo does that (it can not only rename, but also move between directories, at least on the same file system).
Renames the file denoted by this abstract pathname.
Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.
If you need a more comprehensive solution (such as wanting to move the file between disks), look at Apache Commons FileUtils#moveFile
public ActionResult Paging(int? pageno,bool? fwd,bool? bwd)
{
if(pageno!=null)
{
Session["currentpage"] = pageno;
}
using (HatronEntities DB = new HatronEntities())
{
if(fwd!=null && (bool)fwd)
{
pageno = Convert.ToInt32(Session["currentpage"]) + 1;
Session["currentpage"] = pageno;
}
if (bwd != null && (bool)bwd)
{
pageno = Convert.ToInt32(Session["currentpage"]) - 1;
Session["currentpage"] = pageno;
}
if (pageno==null)
{
pageno = 1;
}
if(pageno<0)
{
pageno = 1;
}
int total = DB.EmployeePromotion(0, 0, 0).Count();
int totalPage = (int)Math.Ceiling((double)total / 20);
ViewBag.pages = totalPage;
if (pageno > totalPage)
{
pageno = totalPage;
}
return View (DB.EmployeePromotion(0,0,0).Skip(GetSkip((int)pageno,20)).Take(20).ToList());
}
}
private static int GetSkip(int pageIndex, int take)
{
return (pageIndex - 1) * take;
}
@model IEnumerable<EmployeePromotion_Result>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Paging</title>
</head>
<body>
<div>
<table border="1">
@foreach (var itm in Model)
{
<tr>
<td>@itm.District</td>
<td>@itm.employee</td>
<td>@itm.PromotionTo</td>
</tr>
}
</table>
<a href="@Url.Action("Paging", "Home",new { pageno=1 })">First page</a>
<a href="@Url.Action("Paging", "Home", new { bwd =true })"><<</a>
@for(int itmp =1; itmp< Convert.ToInt32(ViewBag.pages)+1;itmp++)
{
<a href="@Url.Action("Paging", "Home",new { pageno=itmp })">@itmp.ToString()</a>
}
<a href="@Url.Action("Paging", "Home", new { fwd = true })">>></a>
<a href="@Url.Action("Paging", "Home", new { pageno = Convert.ToInt32(ViewBag.pages) })">Last page</a>
</div>
</body>
</html>
nelek's answer is the best one posted so far, but it relies on setting the css value: white-space: pre, which might be undesirable.
I'd like to offer a different solution, which tries to tackle the real question that should've been asked here:
"How to insert untrusted text into a DOM element?"
If you trust the text, why not just use innerHTML?
domElement.innerHTML = trustedText.replace(/\r/g, '').replace(/\n/g, '<br>');
should be sufficient for all the reasonable cases.
If you decided you should use .textContent instead of .innerHTML, it means you don't trust the text that you're about to insert, right? This is a reasonable concern.
For example, you have a form where the user can create a post, and after posting it, the post text is stored in your database, and later on appended to pages whenever other users visit the relevant page.
If you use innerHTML here, you get a security breach. i.e., a user can post something like
[script]alert(1);[/script]
(try to imagine that [] are <>, apparently stack overflow is appending text in unsafe ways!)
which won't trigger an alert if you use innerHTML, but it should give you an idea why using innerHTML can have issues. a smarter user would post
[img src="invalid_src" onerror="alert(1)"]
which would trigger an alert for every other user that visits the page. Now we have a problem. An even smarter user would put display: none on that img style, and make it post the current user's cookies to a cross domain site. Congratulations, all your user login details are now exposed on the internet.
So, the important thing to understand is, using innerHTML isn't wrong, it's perfect if you're just using it to build templates using only your own trusted developer code. The real question should've been "how do I append untrusted user text that has newlines to my HTML document".
This raises a question: which strategy do we use for newlines? do we use [br] elements? [p]s or [div]s?
Here is a short function that solves the problem:
function insertUntrustedText(domElement, untrustedText, newlineStrategy) {
domElement.innerHTML = '';
var lines = untrustedText.replace(/\r/g, '').split('\n');
var linesLength = lines.length;
if(newlineStrategy === 'br') {
for(var i = 0; i < linesLength; i++) {
domElement.appendChild(document.createTextNode(lines[i]));
domElement.appendChild(document.createElement('br'));
}
}
else {
for(var i = 0; i < linesLength; i++) {
var lineElement = document.createElement(newlineStrategy);
lineElement.textContent = lines[i];
domElement.appendChild(lineElement);
}
}
}
You can basically throw this somewhere in your common_functions.js file and then just fire and forget whenever you need to append any user/api/etc -> untrusted text (i.e. not-written-by-your-own-developer-team) to your html pages.
usage example:
insertUntrustedText(document.querySelector('.myTextParent'), 'line1\nline2\r\nline3', 'br');
the parameter newlineStrategy accepts only valid dom element tags, so if you want [br] newlines, pass 'br', if you want each line in a [p] element, pass 'p', etc.
<a href="javascript:alert('Hello!');">Clicky</a>
EDIT, years later: NO! Don't ever do this! I was young and stupid!
Edit, again: A couple people have asked why you shouldn't do this. There's a couple reasons:
Presentation: HTML should focus on presentation. Putting JS in an HREF means that your HTML is now, kinda, dealing with business logic.
Security: Javascript in your HTML like that violates Content Security Policy (CSP). Content Security Policy (CSP) is an added layer of security that helps to detect and mitigate certain types of attacks, including Cross-Site Scripting (XSS) and data injection attacks. These attacks are used for everything from data theft to site defacement or distribution of malware. Read more here.
Accessibility: Anchor tags are for linking to other documents/pages/resources. If your link doesn't go anywhere, it should be a button. This makes it a lot easier for screen readers, braille terminals, etc, to determine what's going on, and give visually impaired users useful information.
In Windows 7+ the first quotations will be the title to the cmd
window to open the program:
start "title" "C:\path\program.exe"
Formatting your command like the above will temporarily open a cmd
window that goes away as fast as it comes up so you really never see it. It also allows you to open more than one program without waiting for the first one to close first.
Using the each syntax will prevent the entire set of keys from being generated at once. This can be important if you're using a tie-ed hash to a database with millions of rows. You don't want to generate the entire list of keys all at once and exhaust your physical memory. In this case each serves as an iterator whereas keys actually generates the entire array before the loop starts.
So, the only place "each" is of real use is when the hash is very large (compared to the memory available). That is only likely to happen when the hash itself doesn't live in memory itself unless you're programming a handheld data collection device or something with small memory.
If memory is not an issue, usually the map or keys paradigm is the more prevelant and easier to read paradigm.
If you really don't want to use any server controls, you should put the Response.Write
in the place you want the string to be written:
<body>
<% Response.Write(stringVariable); %>
</body>
A shorthand for this syntax is:
<body>
<%= stringVariable %>
</body>
def f(x) -> 123:
return x
My summary:
Simply ->
is introduced to get developers to optionally specify the return type of the function. See Python Enhancement Proposal 3107
This is an indication of how things may develop in future as Python is adopted extensively - an indication towards strong typing - this is my personal observation.
You can specify types for arguments as well. Specifying return type of the functions and arguments will help in reducing logical errors and improving code enhancements.
You can have expressions as return type (for both at function and parameter level) and the result of the expressions can be accessed via annotations object's 'return' attribute. annotations will be empty for the expression/return value for lambda inline functions.
I am using large data sets exported to a python file in the form
XVals1 = [.........]
XVals2 = [.........]
Each list is of identical length. I use
>>> a1 = np.array(SV.XVals1)
>>> a2 = np.array(SV.XVals2)
Then
>>> A = np.matrix([a1,a2])
Another simple way that's supported by all browsers would be:
HTML:
<form class="disabled">
<input type="text" name="name" />
<input type="radio" name="gender" value="male">
<input type="radio" name="gender" value="female">
<input type="checkbox" name="vegetarian">
</form>
CSS:
.disabled {
pointer-events: none;
opacity: .4;
}
But be aware, that the tabbing still works with this approach and the elements with focus can still be manipulated by the user.
If you want to use timeit
in an interactive Python session, there are two convenient options:
Use the IPython shell. It features the convenient %timeit
special function:
In [1]: def f(x):
...: return x*x
...:
In [2]: %timeit for x in range(100): f(x)
100000 loops, best of 3: 20.3 us per loop
In a standard Python interpreter, you can access functions and other names you defined earlier during the interactive session by importing them from __main__
in the setup statement:
>>> def f(x):
... return x * x
...
>>> import timeit
>>> timeit.repeat("for x in range(100): f(x)", "from __main__ import f",
number=100000)
[2.0640320777893066, 2.0876040458679199, 2.0520210266113281]
Or you could use the known solution to this problem and use SSL. Self-signed certs are free and its a personal project right?
Very simple, you close it :)
var myWebSocket = new WebSocket("ws://example.org");
myWebSocket.send("Hello Web Sockets!");
myWebSocket.close();
Did you check also the following site And check the introduction article of Opera
You should also check out the "clear" property in css in case removing a float isn't an option
It sounds like you may be wanting to access the viewport of the device. You can do this by inserting this meta tag in your header.
<meta name="viewport" content="width=device-width, initial-scale=1.0">
Regular expression for matching everything after "net" and before ".php":
$pattern = "net([a-zA-Z0-9_]*)\.php";
In the above regular expression, you can find the matching group of characters enclosed by "()" to be what you are looking for.
Hope it's useful.
In case you're using apache's http-client 4:
SSLConnectionSocketFactory sslConnectionSocketFactory =
new SSLConnectionSocketFactory(sslContext,
new String[] { "TLSv1.2" }, null, new HostnameVerifier() {
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});
To scrolldown from any position in the recyclerview to bottom
edittext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
rv.postDelayed(new Runnable() {
@Override
public void run() {
rv.scrollToPosition(rv.getAdapter().getItemCount() - 1);
}
}, 1000);
}
});
Since none of the solutions seem to be working for you so far, try this one:
ini_set('display_errors', 1);
http://www.php.net/manual/en/errorfunc.configuration.php#ini.display-errors
This explicitly tells PHP to display the errors. Some environments can have this disabled by default.
This is what my environment settings look like in index.php
:
/*
*---------------------------------------------------------------
* APPLICATION ENVIRONMENT
*---------------------------------------------------------------
*/
define('ENVIRONMENT', 'development');
/*
*---------------------------------------------------------------
* ERROR REPORTING
*---------------------------------------------------------------
*/
if (defined('ENVIRONMENT'))
{
switch (ENVIRONMENT)
{
case 'development':
// Report all errors
error_reporting(E_ALL);
// Display errors in output
ini_set('display_errors', 1);
break;
case 'testing':
case 'production':
// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL ^ E_NOTICE);
// Don't display errors (they can still be logged)
ini_set('display_errors', 0);
break;
default:
exit('The application environment is not set correctly.');
}
}
According to the HTML specification you can't access the elements of the Canvas. You can get its context, and draw in it manipulate it, but that is all.
BUT, you can put both the Canvas and the html element in the same div with a aposition: relative
and then set the canvas and the other element to position: absolute
.
This ways they will be on the top of each other. Then you can use the left
and right
CSS properties to position the html element.
If the element doesn't shows up, maybe the canvas is before it, so use the z-index
CSS property to bring it before the canvas.
The important point is that the list comprehension creates a new list. The generator creates a an iterable object that will "filter" the source material on-the-fly as you consume the bits.
Imagine you have a 2TB log file called "hugefile.txt", and you want the content and length for all the lines that start with the word "ENTRY".
So you try starting out by writing a list comprehension:
logfile = open("hugefile.txt","r")
entry_lines = [(line,len(line)) for line in logfile if line.startswith("ENTRY")]
This slurps up the whole file, processes each line, and stores the matching lines in your array. This array could therefore contain up to 2TB of content. That's a lot of RAM, and probably not practical for your purposes.
So instead we can use a generator to apply a "filter" to our content. No data is actually read until we start iterating over the result.
logfile = open("hugefile.txt","r")
entry_lines = ((line,len(line)) for line in logfile if line.startswith("ENTRY"))
Not even a single line has been read from our file yet. In fact, say we want to filter our result even further:
long_entries = ((line,length) for (line,length) in entry_lines if length > 80)
Still nothing has been read, but we've specified now two generators that will act on our data as we wish.
Lets write out our filtered lines to another file:
outfile = open("filtered.txt","a")
for entry,length in long_entries:
outfile.write(entry)
Now we read the input file. As our for
loop continues to request additional lines, the long_entries
generator demands lines from the entry_lines
generator, returning only those whose length is greater than 80 characters. And in turn, the entry_lines
generator requests lines (filtered as indicated) from the logfile
iterator, which in turn reads the file.
So instead of "pushing" data to your output function in the form of a fully-populated list, you're giving the output function a way to "pull" data only when its needed. This is in our case much more efficient, but not quite as flexible. Generators are one way, one pass; the data from the log file we've read gets immediately discarded, so we can't go back to a previous line. On the other hand, we don't have to worry about keeping data around once we're done with it.
This button will appear yellow initially. On hover it will turn orange. When you click it, it will turn red. I used :hover and :focus to adapt the style.
(The :active selector is usually used of links (i.e. <a>
tags))
button{_x000D_
background-color:yellow;_x000D_
}_x000D_
_x000D_
button:hover{background-color:orange;}_x000D_
_x000D_
button:focus{background-color:red;}_x000D_
_x000D_
a {_x000D_
color: orange;_x000D_
}_x000D_
_x000D_
a.button{_x000D_
color:green;_x000D_
text-decoration: none;_x000D_
}_x000D_
_x000D_
a:visited {_x000D_
color: purple;_x000D_
}_x000D_
_x000D_
a:active {_x000D_
color: blue;_x000D_
}
_x000D_
<button>_x000D_
Hover and Click!_x000D_
</button>_x000D_
<br><br>_x000D_
_x000D_
<a href="#">Hello</a><br><br>_x000D_
<a class="button" href="#">Bye</a>
_x000D_
Starting in version 0.7.9 you can use the filter operator .isnot
instead of comparing constraints, like this:
query.filter(User.name.isnot(None))
This method is only necessary if pep8 is a concern.
source: sqlalchemy documentation
For today's Date
$(document).ready(function() {
$('#textboxname').datepicker();
$('#textboxname').datepicker('setDate', 'today');});
I think the upgrade of Java will not help. You need to uninstall the old version and then install the latest java version to help you. Make sure that you restart the computer once you are done with the installation.
Hope it helps!
This is an old post, but has a high page rank so I'll chime in with my solution.
I had a similar issue and ended up creating a subclass of UIToolbar
to manage the next/previous/done functionality in a dynamic tableView with sections: https://github.com/jday001/DataEntryToolbar
You set the toolbar as inputAccessoryView of your text fields and add them to its dictionary. This allows you to cycle through them forwards and backwards, even with dynamic content. There are delegate methods if you want to trigger your own functionality when textField navigation happens, but you don't have to deal with managing any tags or first responder status.
There are code snippets & an example app at the GitHub link to help with the implementation details. You will need your own data model to keep track of the values inside the fields.
Frisby is a REST API testing framework built on node.js and Jasmine that makes testing API endpoints easy, fast, and fun. http://frisbyjs.com
Example:
var frisby = require('../lib/frisby');
var URL = 'http://localhost:3000/';
var URL_AUTH = 'http://username:password@localhost:3000/';
frisby.globalSetup({ // globalSetup is for ALL requests
request: {
headers: { 'X-Auth-Token': 'fa8426a0-8eaf-4d22-8e13-7c1b16a9370c' }
}
});
frisby.create('GET user johndoe')
.get(URL + '/users/3.json')
.expectStatus(200)
.expectJSONTypes({
id: Number,
username: String,
is_admin: Boolean
})
.expectJSON({
id: 3,
username: 'johndoe',
is_admin: false
})
// 'afterJSON' automatically parses response body as JSON and passes it as an argument
.afterJSON(function(user) {
// You can use any normal jasmine-style assertions here
expect(1+1).toEqual(2);
// Use data from previous result in next test
frisby.create('Update user')
.put(URL_AUTH + '/users/' + user.id + '.json', {tags: ['jasmine', 'bdd']})
.expectStatus(200)
.toss();
})
.toss();
public void match2()
{
string input = "%download%#893434";
Regex word = new Regex(@"\d+");
Match m = word.Match(input);
Console.WriteLine(m.Value);
}
You cannot select on specific values (or types of values). You'd either make a reverse index (map numbers back to (lists of) keys) or you have to loop through all values every time.
If you are processing numbers in arbitrary order anyway, you may as well loop through all items:
for key, value in inputdict.items():
# do something with value
inputdict[key] = newvalue
otherwise I'd go with the reverse index:
from collections import defaultdict
reverse = defaultdict(list)
for key, value in inputdict.items():
reverse[value].append(key)
Now you can look up keys by value:
for key in reverse[value]:
inputdict[key] = newvalue
I found this page very useful
public abstract class GenericDAOWithJPA<T, ID extends Serializable> {
private Class<T> persistentClass;
//This you might want to get injected by the container
protected EntityManager entityManager;
@SuppressWarnings("unchecked")
public GenericDAOWithJPA() {
this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
@SuppressWarnings("unchecked")
public List<T> findAll() {
return entityManager.createQuery("Select t from " + persistentClass.getSimpleName() + " t").getResultList();
}
}
As most people have said, both ways work indeed, but I think only the first one should. Being semantically strict, the label does not "contain" the input. In my opinion, containment (parent/child) relationship in the markup structure should reflect containment in the visual output. i.e., an element surrounding another one in the markup should be drawn around that one in the browser. According to this, the label should be the input's sibling, not it's parent. So option number two is arbitrary and confusing. Everyone that has read the Zen of Python will probably agree (Flat is better than nested, Sparse is better than dense, There should be one-- and preferably only one --obvious way to do it...).
Because of decisions like that from W3C and major browser vendors (allowing "whichever way you prefer to do it", instead of "do it the right way") is that the web is so messed up today and we developers have to deal with tangled and so diverse legacy code.
Well to just to have some saying about semicolon. In lot of country, comma is what use for decimal not period. Mostly EU colonies, which consist of half of the world, another half follow UK standard (how the hell UK so big O_O) so in turn make using comma for database that include number create much of the headache because Excel refuse to recognize it as delimiter.
Like wise in my country, Viet Nam, follow France's standard, our partner HongKong use UK standard so comma make CSV unusable, and we use \t or ; instead for international use, but it still not "standard" per the document of CSV.
Already this has a lot of useful answers but here is something which might work, it did in my case:
Remove unnecessary imports from your class then Clean project or restart Studio.
As of ES 7, mapping types have been removed. You can read more details here
If you are using Ruby On Rails this means that you may need to remove document_type
from your model or concern.
As an alternative to mapping types one solution is to use an index per document type.
Before:
module Searchable
extend ActiveSupport::Concern
included do
include Elasticsearch::Model
include Elasticsearch::Model::Callbacks
index_name [Rails.env, Rails.application.class.module_parent_name.underscore].join('_')
document_type self.name.downcase
end
end
After:
module Searchable
extend ActiveSupport::Concern
included do
include Elasticsearch::Model
include Elasticsearch::Model::Callbacks
index_name [Rails.env, Rails.application.class.module_parent_name.underscore, self.name.downcase].join('_')
end
end
This C# function uses a regular expression to evaluate whether the passed email address is syntactically valid or not.
public static bool isValidEmail(string inputEmail)
{
string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
@"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
@".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
Regex re = new Regex(strRegex);
if (re.IsMatch(inputEmail))
return (true);
else
return (false);
}
Change this:
if(isset($_POST['submit'])){
if(!(isset($_POST['userName']))){
$username = 'Anonymous';
}
else $username = $_POST['userName'];
}
To this:
if(!empty($_POST['userName'])){
$username = $_POST['userName'];
}
if(empty($_POST['userName'])){
$username = 'Anonymous';
}
Just wanted to add a bit to Raphael's great answer. Here's how to get PHP to produce the same $_FILES
, regardless of whether you use JavaScript to submit.
HTML form:
<form enctype="multipart/form-data" action="/test.php"
method="post" class="putImages">
<input name="media[]" type="file" multiple/>
<input class="button" type="submit" alt="Upload" value="Upload" />
</form>
PHP produces this $_FILES
, when submitted without JavaScript:
Array
(
[media] => Array
(
[name] => Array
(
[0] => Galata_Tower.jpg
[1] => 518f.jpg
)
[type] => Array
(
[0] => image/jpeg
[1] => image/jpeg
)
[tmp_name] => Array
(
[0] => /tmp/phpIQaOYo
[1] => /tmp/phpJQaOYo
)
[error] => Array
(
[0] => 0
[1] => 0
)
[size] => Array
(
[0] => 258004
[1] => 127884
)
)
)
If you do progressive enhancement, using Raphael's JS to submit the files...
var data = new FormData($('input[name^="media"]'));
jQuery.each($('input[name^="media"]')[0].files, function(i, file) {
data.append(i, file);
});
$.ajax({
type: ppiFormMethod,
data: data,
url: ppiFormActionURL,
cache: false,
contentType: false,
processData: false,
success: function(data){
alert(data);
}
});
... this is what PHP's $_FILES
array looks like, after using that JavaScript to submit:
Array
(
[0] => Array
(
[name] => Galata_Tower.jpg
[type] => image/jpeg
[tmp_name] => /tmp/phpAQaOYo
[error] => 0
[size] => 258004
)
[1] => Array
(
[name] => 518f.jpg
[type] => image/jpeg
[tmp_name] => /tmp/phpBQaOYo
[error] => 0
[size] => 127884
)
)
That's a nice array, and actually what some people transform $_FILES
into, but I find it's useful to work with the same $_FILES
, regardless if JavaScript was used to submit. So, here are some minor changes to the JS:
// match anything not a [ or ]
regexp = /^[^[\]]+/;
var fileInput = $('.putImages input[type="file"]');
var fileInputName = regexp.exec( fileInput.attr('name') );
// make files available
var data = new FormData();
jQuery.each($(fileInput)[0].files, function(i, file) {
data.append(fileInputName+'['+i+']', file);
});
(14 April 2017 edit: I removed the form element from the constructor of FormData() -- that fixed this code in Safari.)
That code does two things.
input
name attribute automatically, making the HTML more maintainable. Now, as long as form
has the class putImages, everything else is taken care of automatically. That is, the input
need not have any special name.With these changes, submitting with JavaScript now produces precisely the same $_FILES
array as submitting with simple HTML.
SHA isn't encryption, it's a one-way hash function. AES (Advanced_Encryption_Standard) is a symmetric encryption standard.
If you are doing this in more than one place in your application it would make sense to use a client-side JSON database because creating custom search functions is messy and less maintainable than the alternative.
Check out ForerunnerDB which provides you with a very powerful client-side JSON database system and includes a very simple query language to help you do exactly what you are looking for:
// Create a new instance of ForerunnerDB and then ask for a database
var fdb = new ForerunnerDB(),
db = fdb.db('myTestDatabase'),
coll;
// Create our new collection (like a MySQL table) and change the default
// primary key from "_id" to "id"
coll = db.collection('myCollection', {primaryKey: 'id'});
// Insert our records into the collection
coll.insert([
{"name":"my Name","id":12,"type":"car owner"},
{"name":"my Name2","id":13,"type":"car owner2"},
{"name":"my Name4","id":14,"type":"car owner3"},
{"name":"my Name4","id":15,"type":"car owner5"}
]);
// Search the collection for the string "my nam" as a case insensitive
// regular expression - this search will match all records because every
// name field has the text "my Nam" in it
var searchResultArray = coll.find({
name: /my nam/i
});
console.log(searchResultArray);
/* Outputs
[
{"name":"my Name","id":12,"type":"car owner"},
{"name":"my Name2","id":13,"type":"car owner2"},
{"name":"my Name4","id":14,"type":"car owner3"},
{"name":"my Name4","id":15,"type":"car owner5"}
]
*/
Disclaimer: I am the developer of ForerunnerDB.
In Bootstrap the active
class needs to be applied to the <li>
element and not the <a>
. See the first example here: http://getbootstrap.com/components/#navbar
The way you handle your UI style based on what is active or not has nothing to do with ASP.NET MVC's ActionLink
helper. This is the proper solution to follow how the Bootstrap framework was built.
<ul class="nav navbar-nav">
<li class="active">@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
Edit:
Since you will most likely be reusing your menu on multiple pages, it would be smart to have a way to apply that selected class automatically based on the current page rather than copy the menu multiple times and do it manually.
The easiest way is to simply use the values contained in ViewContext.RouteData
, namely the Action
and Controller
values. We could build on what you currently have with something like this:
<ul class="nav navbar-nav">
<li class="@(ViewContext.RouteData.Values["Action"].ToString() == "Index" ? "active" : "")">@Html.ActionLink("Home", "Index", "Home")</li>
<li class="@(ViewContext.RouteData.Values["Action"].ToString() == "About" ? "active" : "")">@Html.ActionLink("About", "About", "Home")</li>
<li class="@(ViewContext.RouteData.Values["Action"].ToString() == "Contact" ? "active" : "")">@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
It's not pretty in code, but it'll get the job done and allow you to extract your menu into a partial view if you like. There are ways to do this in a much cleaner way, but since you're just getting started I'll leave it at that. Best of luck learning ASP.NET MVC!
Late edit:
This question seems to be getting a bit of traffic so I figured I'd throw in a more elegant solution using an HtmlHelper
extension.
Edit 03-24-2015: Had to rewrite this method to allow for multiple actions and controllers triggering the selected behavior, as well as handling for when the method is called from a child action partial view, thought I'd share the update!
public static string IsSelected(this HtmlHelper html, string controllers = "", string actions = "", string cssClass = "selected")
{
ViewContext viewContext = html.ViewContext;
bool isChildAction = viewContext.Controller.ControllerContext.IsChildAction;
if (isChildAction)
viewContext = html.ViewContext.ParentActionViewContext;
RouteValueDictionary routeValues = viewContext.RouteData.Values;
string currentAction = routeValues["action"].ToString();
string currentController = routeValues["controller"].ToString();
if (String.IsNullOrEmpty(actions))
actions = currentAction;
if (String.IsNullOrEmpty(controllers))
controllers = currentController;
string[] acceptedActions = actions.Trim().Split(',').Distinct().ToArray();
string[] acceptedControllers = controllers.Trim().Split(',').Distinct().ToArray();
return acceptedActions.Contains(currentAction) && acceptedControllers.Contains(currentController) ?
cssClass : String.Empty;
}
Works with .NET Core:
public static string IsSelected(this IHtmlHelper htmlHelper, string controllers, string actions, string cssClass = "selected")
{
string currentAction = htmlHelper.ViewContext.RouteData.Values["action"] as string;
string currentController = htmlHelper.ViewContext.RouteData.Values["controller"] as string;
IEnumerable<string> acceptedActions = (actions ?? currentAction).Split(',');
IEnumerable<string> acceptedControllers = (controllers ?? currentController).Split(',');
return acceptedActions.Contains(currentAction) && acceptedControllers.Contains(currentController) ?
cssClass : String.Empty;
}
Sample usage:
<ul>
<li class="@Html.IsSelected(actions: "Home", controllers: "Default")">
<a href="@Url.Action("Home", "Default")">Home</a>
</li>
<li class="@Html.IsSelected(actions: "List,Detail", controllers: "Default")">
<a href="@Url.Action("List", "Default")">List</a>
</li>
</ul>
<script type="text/javascript">
function iframeDidLoad() {
alert('Done');
}
function newSite() {
var sites = ['http://getprismatic.com',
'http://gizmodo.com/',
'http://lifehacker.com/']
document.getElementById('myIframe').src = sites[Math.floor(Math.random() * sites.length)];
}
</script>
<input type="button" value="Change site" onClick="newSite()" />
<iframe id="myIframe" src="http://getprismatic.com/" onLoad="iframeDidLoad();"></iframe>
Example at http://jsfiddle.net/MALuP/
You need to either have the message be a fixed size, or you need to send the size or you need to use some separator characters.
This is the easiest case for a known size (100 bytes):
in = new DataInputStream(server.getInputStream());
byte[] message = new byte[100]; // the well known size
in.readFully(message);
In this case DataInputStream
makes sense as it offers readFully()
. If you don't use it, you need to loop yourself until the expected number of bytes is read.
try this
var json = [{
"id" : "1",
"msg" : "hi",
"tid" : "2013-05-05 23:35",
"fromWho": "[email protected]"
},
{
"id" : "2",
"msg" : "there",
"tid" : "2013-05-05 23:45",
"fromWho": "[email protected]"
}];
json.forEach((item) => {
console.log('ID: ' + item.id);
console.log('MSG: ' + item.msg);
console.log('TID: ' + item.tid);
console.log('FROMWHO: ' + item.fromWho);
});
Why Server.Transfer
? Response.Redirect(Request.RawUrl)
would get you what you need.
You might have old invalid username/password cached in your browser. Try clearing them and check again.
If you are using IE and somesite.com is in your Intranet security zone, IE may be sending your windows credentials automatically.
just give and text style whatever you want like :D HTML:
<a href="javascript:;" class="fa fa-trash" style="color:#d9534f;">
<span style="color:black;">Text Name</span>
</a>
That was a stroll down memory lane...
I replaced awk by perl a long time ago.
Apparently the AWK regular expression engine does not capture its groups.
you might consider using something like :
perl -n -e'/test(\d+)/ && print $1'
the -n flag causes perl to loop over every line like awk does.
It is probably better to make the addHours method immutable by returning a copy of the Date object rather than mutating its parameter.
Date.prototype.addHours= function(h){
var copiedDate = new Date(this.getTime());
copiedDate.setHours(copiedDate.getHours()+h);
return copiedDate;
}
This way you can chain a bunch of method calls without worrying about state.
If you have been committing your code to source control regularly, this may save you the hassle of creating a new Storyboard and possibly introducing more problems...
I was able to solve this by comparing the Git source code of the version that worked against the broken one. The diff showed that the first line should contain the Id of the initial view controller, in my case, initialViewController="Q7U-eo-vxw". I searched through the source code to be sure that the id existed. All I had to do was put it back and everything worked again!
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="5056" systemVersion="13E28" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" initialViewController="Q7U-eo-vxw">
<dependencies>
<deployment defaultVersion="1296" identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="3733"/>
</dependencies>
<scenes>
Here are some steps that can help you troubleshoot:
We can use [(ngModel)] in following way and have a value selection variable radioSelected
app.component.html
<div class="text-center mt-5">
<h4>Selected value is {{radioSel.name}}</h4>
<div>
<ul class="list-group">
<li class="list-group-item" *ngFor="let item of itemsList">
<input type="radio" [(ngModel)]="radioSelected" name="list_name" value="{{item.value}}" (change)="onItemChange(item)"/>
{{item.name}}
</li>
</ul>
</div>
<h5>{{radioSelectedString}}</h5>
</div>
app.component.ts
import {Item} from '../app/item';
import {ITEMS} from '../app/mock-data';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
radioSel:any;
radioSelected:string;
radioSelectedString:string;
itemsList: Item[] = ITEMS;
constructor() {
this.itemsList = ITEMS;
//Selecting Default Radio item here
this.radioSelected = "item_3";
this.getSelecteditem();
}
// Get row item from array
getSelecteditem(){
this.radioSel = ITEMS.find(Item => Item.value === this.radioSelected);
this.radioSelectedString = JSON.stringify(this.radioSel);
}
// Radio Change Event
onItemChange(item){
this.getSelecteditem();
}
}
Sample Data for Listing
export const ITEMS: Item[] = [
{
name:'Item 1',
value:'item_1'
},
{
name:'Item 2',
value:'item_2'
},
{
name:'Item 3',
value:'item_3'
},
{
name:'Item 4',
value:'item_4'
},
{
name:'Item 5',
value:'item_5'
}
];
I'm not really sure, but you can try some like this:
var pack = function( arr ) {
var length = arr.length,
result = {},
i;
for ( i = 0; i < length; i++ ) {
result[ ( i < 10 ? '0' : '' ) + ( i + 1 ) ] = arr[ i ];
}
return result;
};
pack( [ 'one', 'two', 'three' ] ); //{01: "one", 02: "two", 03: "three"}
tried all proposed solutions, all seem to have issues of their own.
If you actually look into the Orchestrator source, particularly the .start()
implementation you will see that if the last parameter is a function it will treat it as a callback.
I wrote this snippet for my own tasks:
gulp.task( 'task1', () => console.log(a) )
gulp.task( 'task2', () => console.log(a) )
gulp.task( 'task3', () => console.log(a) )
gulp.task( 'task4', () => console.log(a) )
gulp.task( 'task5', () => console.log(a) )
function runSequential( tasks ) {
if( !tasks || tasks.length <= 0 ) return;
const task = tasks[0];
gulp.start( task, () => {
console.log( `${task} finished` );
runSequential( tasks.slice(1) );
} );
}
gulp.task( "run-all", () => runSequential([ "task1", "task2", "task3", "task4", "task5" ));
This is a standard problem.
Note that MySQL allows you to omit columns from the GROUP BY clause, which Standard SQL does not, but you do not get deterministic results in general when you use the MySQL facility.
SELECT *
FROM Messages AS M
JOIN (SELECT To_ID, From_ID, MAX(TimeStamp) AS Most_Recent
FROM Messages
WHERE To_ID = 12345678
GROUP BY From_ID
) AS R
ON R.To_ID = M.To_ID AND R.From_ID = M.From_ID AND R.Most_Recent = M.TimeStamp
WHERE M.To_ID = 12345678
I've added a filter on the To_ID
to match what you're likely to have. The query will work without it, but will return a lot more data in general. The condition should not need to be stated in both the nested query and the outer query (the optimizer should push the condition down automatically), but it can do no harm to repeat the condition as shown.
You can run find . -name "*.pyc" -type f -delete
.
But use it with precaution. Run first find . -name "*.pyc" -type f
to see exactly which files you will remove.
In addition, make sure that -delete is the last argument in your command. If you put it before the -name *.pyc argument, it will delete everything.
Trigger
and Sequence
can be used when you want serialized number that anyone can easily read/remember/understand. But if you don't want to manage ID Column (like emp_id) by this way, and value of this column is not much considerable, you can use SYS_GUID()
at Table Creation to get Auto Increment like this.
CREATE TABLE <table_name>
(emp_id RAW(16) DEFAULT SYS_GUID() PRIMARY KEY,
name VARCHAR2(30));
Now your emp_id
column will accept "globally unique identifier value".
you can insert value in table by ignoring emp_id column like this.
INSERT INTO <table_name> (name) VALUES ('name value');
So, it will insert unique value to your emp_id
Column.
Sublime Text 2 is my favorite. Intuitively understandable and quite powerful.
On top of dhobbs answer above (https://stackoverflow.com/a/9728478/624597), here is an extra functionality of storing results to a file (I personally use it to copy and paste to FreeMind to have a nice overview of the structure, therefore I used tabs instead of spaces for indentation):
import os
def list_files(startpath):
with open("folder_structure.txt", "w") as f_output:
for root, dirs, files in os.walk(startpath):
level = root.replace(startpath, '').count(os.sep)
indent = '\t' * 1 * (level)
output_string = '{}{}/'.format(indent, os.path.basename(root))
print(output_string)
f_output.write(output_string + '\n')
subindent = '\t' * 1 * (level + 1)
for f in files:
output_string = '{}{}'.format(subindent, f)
print(output_string)
f_output.write(output_string + '\n')
list_files(".")
Solved this by adding following
RewriteCond %{ENV:REDIRECT_STATUS} 200 [OR]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
I had the same issue too, the problem is exacerbated with the download link now only working for Visual Studio 2017, and installing the package from the download link did nothing for VS2015, although it took up 5gB of space.
I looked everywhere on how to do it with the Nu Get package manager and I couldn't find the solution.
It turns out it's even simpler than that, all you have to do is right-click the project or solution in the Solution Explorer from within Visual Studio, and click "Install Missing Components"
use ${fn:length(companies) > 0}
to check the size. This returns a boolean
In terms of performance my favorite answer would be:
b.extend(a)
Check how the related alternatives compare with each other in terms of performance:
In [1]: import timeit
In [2]: timeit.timeit('b.extend(a)', setup='b=[];a=range(0,10)', number=100000000)
Out[2]: 9.623248100280762
In [3]: timeit.timeit('b = a[:]', setup='b=[];a=range(0,10)', number=100000000)
Out[3]: 10.84756088256836
In [4]: timeit.timeit('b = list(a)', setup='b=[];a=range(0,10)', number=100000000)
Out[4]: 21.46313500404358
In [5]: timeit.timeit('b = [elem for elem in a]', setup='b=[];a=range(0,10)', number=100000000)
Out[5]: 66.99795293807983
In [6]: timeit.timeit('for elem in a: b.append(elem)', setup='b=[];a=range(0,10)', number=100000000)
Out[6]: 67.9775960445404
In [7]: timeit.timeit('b = deepcopy(a)', setup='from copy import deepcopy; b=[];a=range(0,10)', number=100000000)
Out[7]: 1216.1108016967773
You can use OpenXml SDK for *.xlsx files. It works very quickly. I made simple C# IDataReader implementation for this sdk. See here. Now you can easy import excel file to sql server database using SqlBulkCopy. It uses small memory because it reads by SAX(Simple API for XML) method (OpenXmlReader)
Example:
private static void DataReaderBulkCopySample()
{
using (var reader = new ExcelDataReader(@"test.xlsx"))
{
var cols = Enumerable.Range(0, reader.FieldCount).Select(i => reader.GetName(i)).ToArray();
DataHelper.CreateTableIfNotExists(ConnectionString, TableName, cols);
using (var bulkCopy = new SqlBulkCopy(ConnectionString))
{
// MSDN: When EnableStreaming is true, SqlBulkCopy reads from an IDataReader object using SequentialAccess,
// optimizing memory usage by using the IDataReader streaming capabilities
bulkCopy.EnableStreaming = true;
bulkCopy.DestinationTableName = TableName;
foreach (var col in cols)
bulkCopy.ColumnMappings.Add(col, col);
bulkCopy.WriteToServer(reader);
}
}
}
Use setTimeout()
:
var delayInMilliseconds = 1000; //1 second
setTimeout(function() {
//your code to be executed after 1 second
}, delayInMilliseconds);
If you want to do it without setTimeout
: Refer to this question.
You can make use of java.net.URL
and/or java.net.URLConnection
.
URL url = new URL("https://stackoverflow.com");
try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"))) {
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
}
}
Also see the Oracle's simple tutorial on the subject. It's however a bit verbose. To end up with less verbose code, you may want to consider Apache HttpClient instead.
By the way: if your next question is "How to process HTML result?", then the answer is "Use a HTML parser. No, don't use regex for this.".
You don't need to make a custom encoder class to supply the default
method - it can be passed in as a keyword argument:
import json
def serialize_sets(obj):
if isinstance(obj, set):
return list(obj)
return obj
json_str = json.dumps(set([1,2,3]), default=serialize_sets)
print(json_str)
results in [1, 2, 3]
in all supported Python versions.
Well, it's fairly self-explanatory: you've run out of memory.
You may want to try starting it with more memory, using the -Xmx flag, e.g.
java -Xmx2048m [whatever you'd have written before]
This will use up to 2 gigs of memory.
See the non-standard options list for more details.
NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(3), target: self, selector: "functionHere", userInfo: nil, repeats: false)
This would call the function functionHere() with a 3 seconds delay
String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL, Keys.RETURN);
WebElement e = driver.findElement(By
.xpath("html/body/header/div/div[1]/nav/a"));
e.sendKeys(selectLinkOpeninNewTab);//to open the link in a current page in to the browsers new tab
e.sendKeys(Keys.CONTROL + "\t");//to move focus to next tab in same browser
try {
Thread.sleep(8000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//to wait some time in that tab
e.sendKeys(Keys.CONTROL + "\t");//to switch the focus to old tab again
Hope it helps to you..
If you have readonly
attribute, blur by itself would not work. Contraption below should do the job.
$('#myInputID').removeAttr('readonly').trigger('blur').attr('readonly','readonly');
Expected situation
# Wrong output from cell_values()
42884.0
# Expected output
2017-5-29
Example: Let cell_values(2,2) from sheet number 0 will be the date targeted
Get the required variables as the following
workbook = xlrd.open_workbook("target.xlsx")
sheet = workbook.sheet_by_index(0)
wrongValue = sheet.cell_value(2,2)
And make use of xldate_as_tuple
y, m, d, h, i, s = xlrd.xldate_as_tuple(wrongValue, workbook.datemode)
print("{0} - {1} - {2}".format(y, m, d))
That's my solution
You don't need to write js to do that, simply use:
<a href="path_to/image.jpg" alt="something">Download image</a>
And the browser itself will automatically download the image.
If for some reason it doesn't work add the download attribute. With this attribute you can set a name for the downloadable file:
<a href="path_to/image.jpg" download="myImage">Download image</a>
You could count with sql and retrieve the answer from the resultset like so:
Statment stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet ct = stmt.executeQuery("SELECT COUNT(*) FROM [table_name]");
if(ct.next()){
td.setTotalNumRows(ct.getInt(1));
}
Here I'm counting everything but you can easily modify the SQL to count based on a criteria.
If your git version does not have the --orphan option, this method should be used:
git symbolic-ref HEAD refs/heads/<newbranch>
rm .git/index
git clean -fdx
After doing some work:
git add -A
git commit -m <message>
git push origin <newbranch>
If you don't want to use jQuery you can try this approach:
public setCaretPosition() {
const editableDiv = document.getElementById('contenteditablediv');
const lastLine = this.input.nativeElement.innerHTML.replace(/.*?(<br>)/g, '');
const selection = window.getSelection();
selection.collapse(editableDiv.childNodes[editableDiv.childNodes.length - 1], lastLine.length);
}
editableDiv
you editable element, don't forget to set an id
for it. Then you need to get your innerHTML
from the element and cut all brake lines. And just set collapse with next arguments.
Moreover, you can use (x = Eval("item") ?? 0) in this case.
I think your EmpID
column is string and you forget to use ' '
in your value.
Because when you write EmpID=" + id.Text
, your command looks like EmpID = 12345
instead of EmpID = '12345'
Change your SqlCommand
to
SqlCommand cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID='" + id.Text +"'", con);
Or as a better way you can (and should) always use parameterized queries
. This kind of string concatenations are open for SQL Injection
attacks.
SqlCommand cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = @id", con);
cmd.Parameters.AddWithValue("@id", id.Text);
I think your EmpID
column keeps your employee id's, so it's type should some numerical type instead of character.
I think the issue is that you need to wrap your div
in a container and/or row.
This should achieve a similar look as what you are looking for:
<div class="container">
<div class="row" id="error-container">
<div class="span12">
<div class="alert alert-error">
<button type="button" class="close" data-dismiss="alert">×</button>
test error message
</div>
</div>
</div>
</div>
CSS:
#error-container {
margin-top:10px;
position: fixed;
}
Here's my research results:
Apple has hidden the UDID from all public APIs, starting with iOS 7. Any UDID that begins with FFFF is a fake ID. The "Send UDID" apps that previously worked can no longer be used to gather UDID for test devices. (sigh!)
The UDID is shown when a device is connected to XCode (in the organizer), and when the device is connected to iTunes (although you have to click on 'Serial Number' to get the Identifier to display.
If you need to get the UDID for a device to add to a provisioning profile, and can't do it yourself in XCode, you will have to walk them through the steps to copy/paste it from iTunes.
UPDATE -- see okiharaherbst's answer below for a script based approach to allow test users to provide you with their device UDIDs by hosting a mobileconfig file on a server
There are two approaches which are not mentioned above, but both of which solve the problem in a way which complies with PEP 8 and allow you to make better use of your space. They are:
msg = (
'This message is so long, that it requires '
'more than {x} lines.{sep}'
'and you may want to add more.').format(
x=x, sep=2*'\n')
print(msg)
Notice how the parentheses are used to allow us not to add plus signs between pure strings, and spread the result over multiple lines without the need for explicit line continuation '\' (ugly and cluttered).
The advantages are same with what is described below, the difference is that you can do it anywhere.
Compared to the previous alternative, it is visually better when inspecting code, because it outlines the start and end of msg
clearly (compare with msg +=
one every line, which needs one additional thinking step to deduce that those lines add to the same string - and what if you make a typo, forgetting a +
on one random line ?).
Regarding this approach, many times we have to build a string using iterations and checks within the iteration body, so adding its pieces within the function call, as shown later, is not an option.
A close alternative is:
msg = 'This message is so long, that it requires '
msg += 'many lines to write, one reason for that\n'
msg += 'is that it contains numbers, like this '
msg += 'one: ' + str(x) +', which take up more space\n'
msg += 'to insert. Note how newlines are also included '
msg += 'and can be better presented in the code itself.'
print(msg)
Though the first is preferable.
The other approach is like the previous ones, though it starts the message on the line below the print
.
The reason for this is to gain space on the left, otherwise the print(
itself "pushes" you to the right. This consumption of indentation is the inherited by the rest of the lines comprising the message, because according to PEP 8 they must align with the opening parenthesis of print
above them. So if your message was already long, this way it's forced to be spread over even more lines.
Contrast:
raise TypeError('aaaaaaaaaaaaaaaa' +
'aaaaaaaaaaaaaaaa' +
'aaaaaaaaaaaaaaaa')
with this (suggested here):
raise TypeError(
'aaaaaaaaaaaaaaaaaaaaaaaa' +
'aaaaaaaaaaaaaaaaaaaaaaaa')
The line spread was reduced. Of course this last approach does no apply so much to print
, because it is a short call. But it does apply to exceptions.
A variation you can have is:
raise TypeError((
'aaaaaaaaaaaaaaaaaaaaaaaa'
'aaaaaaaaaaaaaaaaaaaaaaaa'
'aaaaa {x} aaaaa').format(x=x))
Notice how you don't need to have plus signs between pure strings. Also, the indentation guides the reader's eyes, no stray parentheses hanging below to the left. The replacements are very readable. In particular, such an approach makes writing code that generates code or mathematical formulas a very pleasant task.
you can also use VSCommands 2010 to run as different user:
A quick search on the VSCode marketplace: https://marketplace.visualstudio.com/items/bradgashler.htmltagwrap.
Launch VS Code Quick Open (Ctrl+P)
paste ext install htmltagwrap
and enter
select HTML
press Alt + W (Option + W for Mac).
You should not use your domain models
in your views. ViewModels
are the correct way to do it.
You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.
If you never heard of viewmodels, take a look at this.
The easiest way that I found for adding a column to a DataFrame was to use the "add" function. Here's a snippet of code, also with the output to a CSV file. Note that including the "columns" argument allows you to set the name of the column (which happens to be the same as the name of the np.array that I used as the source of the data).
# now to create a PANDAS data frame
df = pd.DataFrame(data = FF_maxRSSBasal, columns=['FF_maxRSSBasal'])
# from here on, we use the trick of creating a new dataframe and then "add"ing it
df2 = pd.DataFrame(data = FF_maxRSSPrism, columns=['FF_maxRSSPrism'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = FF_maxRSSPyramidal, columns=['FF_maxRSSPyramidal'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = deltaFF_strainE22, columns=['deltaFF_strainE22'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = scaled, columns=['scaled'])
df = df.add( df2, fill_value=0 )
df2 = pd.DataFrame(data = deltaFF_orientation, columns=['deltaFF_orientation'])
df = df.add( df2, fill_value=0 )
#print(df)
df.to_csv('FF_data_frame.csv')
For the record, this is documented in How do I add resources to my JAR? (illustrated for unit tests but the same applies for a "regular" resource):
To add resources to the classpath for your unit tests, you follow the same pattern as you do for adding resources to the JAR except the directory you place resources in is
${basedir}/src/test/resources
. At this point you would have a project directory structure that would look like the following:my-app |-- pom.xml `-- src |-- main | |-- java | | `-- com | | `-- mycompany | | `-- app | | `-- App.java | `-- resources | `-- META-INF | |-- application.properties `-- test |-- java | `-- com | `-- mycompany | `-- app | `-- AppTest.java `-- resources `-- test.properties
In a unit test you could use a simple snippet of code like the following to access the resource required for testing:
... // Retrieve resource InputStream is = getClass().getResourceAsStream("/test.properties" ); // Do something with the resource ...
render() {
var myloop = [];
for (let i = 0; i < 10; i++) {
myloop.push(
<View key={i}>
<Text style={{ textAlign: 'center', marginTop: 5 }} >{i}</Text>
</View>
);
}
return (
<View >
<Text >Welcome to React Native!</Text>
{myloop}
</View>
);
}
Output 1 2 3 4 5 6 7 8 9
jQuery's delay
function is meant to be used with effects and effect queues, see the delay
docs and the example therein:
$('#foo').slideUp(300).delay(800).fadeIn(400);
If you want to observe a variable for changes, you could do something like
(function() {
var observerInterval = setInterval(function() {
if (/* check for changes here */) {
clearInterval(observerInterval);
// do something here
}
}, 1000);
})();
Well, what I do on every project is a mix of the options above.
First, add the jsr310 dependency:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
Important detail: put this dependency on the top of your depedencies list. I already see a project where the Localdate error persists even with this dependency on the pom.xml. But changing the order of the depedency the error was gone.
On your /src/main/resources/application.yml
file, setup the write-dates-as-timestamps
property:
spring:
jackson:
serialization:
write-dates-as-timestamps: false
And create a ObjectMapper
bean as this:
@Configuration
public class WebConfigurer {
@Bean
@Primary
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.build();
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
return objectMapper;
}
}
Following this configuration, the conversion always work on Spring Boot 1.5.x without any error.
Working with Spring AMQP, pay attention if you have a new instance of Jackson2JsonMessageConverter
(common thing when creating a SimpleRabbitListenerContainerFactory
). You need to pass the ObjectMapper
bean to it, like:
Jackson2JsonMessageConverter converter = new Jackson2JsonMessageConverter(objectMapper);
Otherwise, you will receive the same error.
It's possible to change default fonts, both for the axes and for other text, by adding the following lines to the startup.m
file.
% Change default axes fonts.
set(0,'DefaultAxesFontName', 'Times New Roman')
set(0,'DefaultAxesFontSize', 14)
% Change default text fonts.
set(0,'DefaultTextFontname', 'Times New Roman')
set(0,'DefaultTextFontSize', 14)
If you don't know if you have a startup.m
file, run
which startup
to find its location. If Matlab says there isn't one, run
userpath
to know where it should be placed.
First convert you datagridview's data to List, then convert List to DataTable
public static DataTable ToDataTable<T>( this List<T> list) where T : class {
Type type = typeof(T);
var ps = type.GetProperties ( );
var cols = from p in ps
select new DataColumn ( p.Name , p.PropertyType );
DataTable dt = new DataTable();
dt.Columns.AddRange(cols.ToArray());
list.ForEach ( (l) => {
List<object> objs = new List<object>();
objs.AddRange ( ps.Select ( p => p.GetValue ( l , null ) ) );
dt.Rows.Add ( objs.ToArray ( ) );
} );
return dt;
}
I think something is being missed by the other answers.
Yes, p[i]
is by definition equivalent to *(p+i)
, which (because addition is commutative) is equivalent to *(i+p)
, which (again, by the definition of the []
operator) is equivalent to i[p]
.
(And in array[i]
, the array name is implicitly converted to a pointer to the array's first element.)
But the commutativity of addition is not all that obvious in this case.
When both operands are of the same type, or even of different numeric types that are promoted to a common type, commutativity makes perfect sense: x + y == y + x
.
But in this case we're talking specifically about pointer arithmetic, where one operand is a pointer and the other is an integer. (Integer + integer is a different operation, and pointer + pointer is nonsense.)
The C standard's description of the +
operator (N1570 6.5.6) says:
For addition, either both operands shall have arithmetic type, or one operand shall be a pointer to a complete object type and the other shall have integer type.
It could just as easily have said:
For addition, either both operands shall have arithmetic type, or the left operand shall be a pointer to a complete object type and the right operand shall have integer type.
in which case both i + p
and i[p]
would be illegal.
In C++ terms, we really have two sets of overloaded +
operators, which can be loosely described as:
pointer operator+(pointer p, integer i);
and
pointer operator+(integer i, pointer p);
of which only the first is really necessary.
So why is it this way?
C++ inherited this definition from C, which got it from B (the commutativity of array indexing is explicitly mentioned in the 1972 Users' Reference to B), which got it from BCPL (manual dated 1967), which may well have gotten it from even earlier languages (CPL? Algol?).
So the idea that array indexing is defined in terms of addition, and that addition, even of a pointer and an integer, is commutative, goes back many decades, to C's ancestor languages.
Those languages were much less strongly typed than modern C is. In particular, the distinction between pointers and integers was often ignored. (Early C programmers sometimes used pointers as unsigned integers, before the unsigned
keyword was added to the language.) So the idea of making addition non-commutative because the operands are of different types probably wouldn't have occurred to the designers of those languages. If a user wanted to add two "things", whether those "things" are integers, pointers, or something else, it wasn't up to the language to prevent it.
And over the years, any change to that rule would have broken existing code (though the 1989 ANSI C standard might have been a good opportunity).
Changing C and/or C++ to require putting the pointer on the left and the integer on the right might break some existing code, but there would be no loss of real expressive power.
So now we have arr[3]
and 3[arr]
meaning exactly the same thing, though the latter form should never appear outside the IOCCC.
Workaround:
tableView.getColumns().get(0).setVisible(false);
tableView.getColumns().get(0).setVisible(true);
System.getProperties()
can be overridden by calls to System.setProperty(String key, String value)
or with command line parameters -Dfile.separator=/
File.separator
gets the separator for the default filesystem.
FileSystems.getDefault()
gets you the default filesystem.
FileSystem.getSeparator()
gets you the separator character for the filesystem. Note that as an instance method you can use this to pass different filesystems to your code other than the default, in cases where you need your code to operate on multiple filesystems in the one JVM.
This answer assumes that you have python3.6
installed. For python3.7
, replace 3.6
with 3.7
. For python3.8
, replace 3.6
with 3.8
, but it may also first require the python3.8-distutils
package.
With regard to installing pip
, using curl
(instead of wget
) avoids writing the file to disk.
curl https://bootstrap.pypa.io/get-pip.py | sudo -H python3.6
The -H
flag is evidently necessary with sudo
in order to prevent errors such as the following when installing pip for an updated python interpreter:
The directory '/home/someuser/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/someuser/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
curl https://bootstrap.pypa.io/get-pip.py | python3.6 - --user
This may sometimes give a warning such as:
WARNING: The script wheel is installed in '/home/ubuntu/.local/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
After this, pip
, pip3
, and pip3.6
can all be expected to point to the same target:
$ (pip -V && pip3 -V && pip3.6 -V) | uniq
pip 18.0 from /usr/local/lib/python3.6/dist-packages (python 3.6)
Of course you can alternatively use python3.6 -m pip
as well.
$ python3.6 -m pip -V
pip 18.0 from /usr/local/lib/python3.6/dist-packages (python 3.6)
I am surprised that nobody has mentioned CSS pseudo-classes, which are also a sort-of conditionals in CSS. You can do some pretty advanced things with this, without a single line of JavaScript.
Some pseudo-classes:
Example:
div { color: white; background: red }_x000D_
input:checked + div { background: green }
_x000D_
<input type=checkbox>Click me!_x000D_
<div>Red or green?</div>
_x000D_
Sadly there are no operation-assignment
operators in VBA.
(Addition-assignment +=
are available in VB.Net)
Pointless workaround;
Sub Inc(ByRef i As Integer)
i = i + 1
End Sub
...
Static value As Integer
inc value
inc value
No. You'll need cancel it (clearTimeout
), measure the time since you started it and restart it with the new time.
I think you means the difference between DELETE TABLE and TRUNCATE TABLE.
DROP TABLE
remove the table from the database.
DELETE TABLE
without a condition delete all rows. If there are trigger and references then this will process for every row. Also a index will be modify if there one.
TRUNCATE TABLE
set the row count zero and without logging each row. That it is many faster as the other both.
I used this code:
ws.Range("A:A").FormulaR1C1 = "=DATEVALUE(RC[1])"
column A will be mm/dd/yyyy
RC[1] is column B, the TEXT string, eg, 01/30/12, THIS IS NOT DATE TYPE
Of course slideDown
and slideUp
don't do what you want, you said you want it to be left/right, not top/down.
If your edit to your question adding the jquery-ui
tag means you're using jQuery UI, I'd go with nnnnnn's solution, using jQuery UI's slide
effect.
If not:
Assuming the menu starts out visible (edit: oops, I see that isn't a valid assumption; see note below), if you want it to slide out to the left and then later slide back in from the left, you could do this: Live Example | Live Source
$(document).ready(function() {
// Hide menu once we know its width
$('#showmenu').click(function() {
var $menu = $('.menu');
if ($menu.is(':visible')) {
// Slide away
$menu.animate({left: -($menu.outerWidth() + 10)}, function() {
$menu.hide();
});
}
else {
// Slide in
$menu.show().animate({left: 0});
}
});
});
You'll need to put position: relative
on the menu element.
Note that I replaced your toggle
with click
, because that form of toggle
was removed from jQuery.
If you want the menu to start out hidden, you can adjust the above. You want to know the element's width, basically, when putting it off-page.
This version doesn't care whether the menu is initially-visible or not: Live Copy | Live Source
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<div id="showmenu">Click Here</div>
<div class="menu" style="display: none; position: relative;"><ul><li>Button1</li><li>Button2</li><li>Button3</li></ul></div>
<script>
$(document).ready(function() {
var first = true;
// Hide menu once we know its width
$('#showmenu').click(function() {
var $menu = $('.menu');
if ($menu.is(':visible')) {
// Slide away
$menu.animate({left: -($menu.outerWidth() + 10)}, function() {
$menu.hide();
});
}
else {
// Slide in
$menu.show().css("left", -($menu.outerWidth() + 10)).animate({left: 0});
}
});
});
</script>
</body>
</html>
you don't need to use *ngIf if you use ng-container
<ng-container [ngTemplateOutlet]="myTemplate === 'first' ? first : myTemplate ===
'second' ? second : third"></ng-container>
<ng-template #first>first</ng-template>
<ng-template #second>second</ng-template>
<ng-template #third>third</ng-template>
This structure works for me - I used it in a small tasks management application.
The controller:
public JsonResult taskCount(string fDate)
{
// do some stuff based on the date
// totalTasks is a count of the things I need to do today
// tasksDone is a count of the tasks I actually did
// pcDone is the percentage of tasks done
return Json(new {
totalTasks = totalTasks,
tasksDone = tasksDone,
percentDone = pcDone
});
}
In the AJAX call I access the data like this:
.done(function (data) {
// data.totalTasks
// data.tasksDone
// data.percentDone
});
This is also an alternate use of case-when...
UPDATE [dbo].[JobTemplates]
SET [CycleId] =
CASE [Id]
WHEN 1376 THEN 44 --ACE1 FX1
WHEN 1385 THEN 44 --ACE1 FX2
WHEN 1574 THEN 43 --ACE1 ELEM1
WHEN 1576 THEN 43 --ACE1 ELEM2
WHEN 1581 THEN 41 --ACE1 FS1
WHEN 1585 THEN 42 --ACE1 HS1
WHEN 1588 THEN 43 --ACE1 RS1
WHEN 1589 THEN 44 --ACE1 RM1
WHEN 1590 THEN 43 --ACE1 ELEM3
WHEN 1591 THEN 43 --ACE1 ELEM4
WHEN 1595 THEN 44 --ACE1 SSTn
ELSE 0
END
WHERE
[Id] IN (1376,1385,1574,1576,1581,1585,1588,1589,1590,1591,1595)
I like the use of the temporary tables in cases where duplicate values are not permitted and your update may create them. For example:
SELECT
[Id]
,[QueueId]
,[BaseDimensionId]
,[ElastomerTypeId]
,CASE [CycleId]
WHEN 29 THEN 44
WHEN 30 THEN 43
WHEN 31 THEN 43
WHEN 101 THEN 41
WHEN 102 THEN 43
WHEN 116 THEN 42
WHEN 120 THEN 44
WHEN 127 THEN 44
WHEN 129 THEN 44
ELSE 0
END AS [CycleId]
INTO
##ACE1_PQPANominals_1
FROM
[dbo].[ProductionQueueProcessAutoclaveNominals]
WHERE
[QueueId] = 3
ORDER BY
[BaseDimensionId], [ElastomerTypeId], [Id];
---- (403 row(s) affected)
UPDATE [dbo].[ProductionQueueProcessAutoclaveNominals]
SET
[CycleId] = X.[CycleId]
FROM
[dbo].[ProductionQueueProcessAutoclaveNominals]
INNER JOIN
(
SELECT
MIN([Id]) AS [Id],[QueueId],[BaseDimensionId],[ElastomerTypeId],[CycleId]
FROM
##ACE1_PQPANominals_1
GROUP BY
[QueueId],[BaseDimensionId],[ElastomerTypeId],[CycleId]
) AS X
ON
[dbo].[ProductionQueueProcessAutoclaveNominals].[Id] = X.[Id];
----(375 row(s) affected)
I've been working in C#/Razor and since I don't have IIS setup on my home laptop I looked for a javascript solution to load in views while creating static markup for our project.
I stumbled upon a website explaining methods of "ditching jquery," it demonstrates a method on the site does exactly what you're after in plain Jane javascript (reference link at the bottom of post). Be sure to investigate any security vulnerabilities and compatibility issues if you intend to use this in production. I am not, so I never looked into it myself.
JS Function
var getURL = function (url, success, error) {
if (!window.XMLHttpRequest) return;
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === 4) {
if (request.status !== 200) {
if (error && typeof error === 'function') {
error(request.responseText, request);
}
return;
}
if (success && typeof success === 'function') {
success(request.responseText, request);
}
}
};
request.open('GET', url);
request.send();
};
Get the content
getURL(
'/views/header.html',
function (data) {
var el = document.createElement(el);
el.innerHTML = data;
var fetch = el.querySelector('#new-header');
var embed = document.querySelector('#header');
if (!fetch || !embed) return;
embed.innerHTML = fetch.innerHTML;
}
);
index.html
<!-- This element will be replaced with #new-header -->
<div id="header"></div>
views/header.html
<!-- This element will replace #header -->
<header id="new-header"></header>
The source is not my own, I'm merely referencing it as it's a good vanilla javascript solution to the OP. Original code lives here: http://gomakethings.com/ditching-jquery#get-html-from-another-page
perl -lne 'print if((/abc/../mno/) && !(/abc/||/mno/))' your_file
xmlstr = etree.tostring(listings, encoding='utf8', method='xml')
conn = boto.connect_s3(
aws_access_key_id = access_key,
aws_secret_access_key = secret_key,
# host = '<bucketName>.s3.amazonaws.com',
host = 'bycket.s3.amazonaws.com',
#is_secure=False, # uncomment if you are not using ssl
calling_format = boto.s3.connection.OrdinaryCallingFormat(),
)
conn.auth_region_name = 'us-west-1'
bucket = conn.get_bucket('resources', validate=False)
key= bucket.get_key('filename.txt')
key.set_contents_from_string("SAMPLE TEXT")
key.set_canned_acl('public-read')
Given the code you provided in comments, I assume you want to do this:
>>> dateList = "Thu Sep 16 13:14:15 CDT 2010".split()
>>> sdateList = "Thu Sep 16 14:14:15 CDT 2010".split()
>>> dateList == sdataList
false
The split
-method of the string returns a list. A list in Python is very different from an array. ==
in this case does an element-wise comparison of the two lists and returns if all their elements are equal and the number and order of the elements is the same. Read the documentation.
Please see http://msdn.microsoft.com/en-us/library/aa260631(v=SQL.80).aspx In SQL server a timestamp is not the same as a DateTime column. This is used to uniquely identify a row in a database, not just a table but the entire database. This can be used for optimistic concurrency. for example UPDATE [Job] SET [Name]=@Name, [XCustomData]=@XCustomData WHERE ([ModifiedTimeStamp]=@Original_ModifiedTimeStamp AND [GUID]=@Original_GUID
the ModifiedTimeStamp ensures that you are updating the original data and will fail if another update has occurred to the row.
Double click Shift
to open the quick actions. Then search for "Decrease Font Size" or "Increase Font Size" and hit Enter
. To repeat the action you can doubleclick Shift
and Enter
I prefer that way because it works even when you're using not your own Computer without opening settings. Also works without leaving fullscreen, which is useful if you are live coding.
best way is
button.setBackgroundResource(android.R.drawable.ic_delete);
OR this for Drawable left and something like that for right etc.
int imgResource = R.drawable.left_img;
button.setCompoundDrawablesWithIntrinsicBounds(imgResource, 0, 0, 0);
and
getResources().getDrawable()
is now deprecated
To use unsafe code blocks, the project has to be compiled with the /unsafe switch on.
Open the properties for the project, go to the Build
tab and check the Allow unsafe code
checkbox.
If you want to use parameters for a,b,c,d in Laravel 4
Model::where(function ($query) use ($a,$b) {
$query->where('a', '=', $a)
->orWhere('b', '=', $b);
})
->where(function ($query) use ($c,$d) {
$query->where('c', '=', $c)
->orWhere('d', '=', $d);
});
You map your dispatcher on *.do:
<servlet-mapping>
<servlet-name>Dispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
but your controller is mapped on an url without .do:
@RequestMapping("/editPresPage")
Try changing this to:
@RequestMapping("/editPresPage.do")
I don't know if I'm the one that doesn't get the question right, but this just worked for me: Using an onchange() event in your html, eg.
<select id="numberToSelect" onchange="selectNum">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
//javascript
function sele(){
var strUser = numberToSelect.value;
}
This will give you whatever value is on the select dropdown per click
Whenever you wanted to make a layout scrollable, you can use <ScrollView>
With a layout or component in it.
With PowerShell 2.0 (Windows 7 preinstalled) you can use:
(New-Object Net.WebClient).DownloadFile('http://www.example.com/package.zip', 'package.zip')
Starting with PowerShell 3.0 (Windows 8 preinstalled) you can use Invoke-WebRequest
:
Invoke-WebRequest http://www.example.com/package.zip -OutFile package.zip
From a batch file they are called:
powershell -Command "(New-Object Net.WebClient).DownloadFile('http://www.example.com/package.zip', 'package.zip')"
powershell -Command "Invoke-WebRequest http://www.example.com/package.zip -OutFile package.zip"
(PowerShell 2.0 is available for installation on XP, 3.0 for Windows 7)
$users = $dbh->query($sql);
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
Here $users
is a PDOStatement
object over which you can iterate. The first iteration outputs all results, the second does nothing since you can only iterate over the result once. That's because the data is being streamed from the database and iterating over the result with foreach
is essentially shorthand for:
while ($row = $users->fetch()) ...
Once you've completed that loop, you need to reset the cursor on the database side before you can loop over it again.
$users = $dbh->query($sql);
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
echo "<br/>";
$result = $users->fetch(PDO::FETCH_ASSOC);
foreach($result as $key => $value) {
echo $key . "-" . $value . "<br/>";
}
Here all results are being output by the first loop. The call to fetch
will return false
, since you have already exhausted the result set (see above), so you get an error trying to loop over false
.
In the last example you are simply fetching the first result row and are looping over it.
Your friend is correct. Both gzip and ZIP are based on DEFLATE. This is a general purpose algorithm, and is not intended for encoding small strings.
If you need this, a possible solution is a custom encoding and decoding HashMap<String, String>
. This can allow you to do a simple one-to-one mapping:
HashMap<String, String> toCompressed, toUncompressed;
String compressed = toCompressed.get(uncompressed);
// ...
String uncompressed = toUncompressed.get(compressed);
Clearly, this requires setup, and is only practical for a small number of strings.
str_pad
from the stringr
package is an alternative.
anim = 25499:25504
str_pad(anim, width=6, pad="0")
I fixed it by ticking the "Enable annotation processing" checkbox in Settings->Compiler->Annotation Processors.
Along with this you might also need to install lombok
plugin as mentioned in @X.Chen's answer for new versions of IntelliJ Idea.
PATH mode is used in generating XML from a SELECT query
1. SELECT
ID,
Name
FROM temp1
FOR XML PATH;
Ouput:
<row>
<ID>1</ID>
<Name>aaa</Name>
</row>
<row>
<ID>1</ID>
<Name>bbb</Name>
</row>
<row>
<ID>1</ID>
<Name>ccc</Name>
</row>
<row>
<ID>1</ID>
<Name>ddd</Name>
</row>
<row>
<ID>1</ID>
<Name>eee</Name>
</row>
The Output is element-centric XML where each column value in the resulting rowset is wrapped in an row element. Because the SELECT clause does not specify any aliases for the column names, the child element names generated are the same as the corresponding column names in the SELECT clause.
For each row in the rowset a tag is added.
2.
SELECT
ID,
Name
FROM temp1
FOR XML PATH('');
Ouput:
<ID>1</ID>
<Name>aaa</Name>
<ID>1</ID>
<Name>bbb</Name>
<ID>1</ID>
<Name>ccc</Name>
<ID>1</ID>
<Name>ddd</Name>
<ID>1</ID>
<Name>eee</Name>
For Step 2: If you specify a zero-length string, the wrapping element is not produced.
3.
SELECT
Name
FROM temp1
FOR XML PATH('');
Ouput:
<Name>aaa</Name>
<Name>bbb</Name>
<Name>ccc</Name>
<Name>ddd</Name>
<Name>eee</Name>
4. SELECT
',' +Name
FROM temp1
FOR XML PATH('')
Ouput:
,aaa,bbb,ccc,ddd,eee
In Step 4 we are concatenating the values.
5. SELECT ID,
abc = (SELECT
',' +Name
FROM temp1
FOR XML PATH('') )
FROM temp1
Ouput:
1 ,aaa,bbb,ccc,ddd,eee
1 ,aaa,bbb,ccc,ddd,eee
1 ,aaa,bbb,ccc,ddd,eee
1 ,aaa,bbb,ccc,ddd,eee
1 ,aaa,bbb,ccc,ddd,eee
6. SELECT ID,
abc = (SELECT
',' +Name
FROM temp1
FOR XML PATH('') )
FROM temp1 GROUP by iD
Ouput:
ID abc
1 ,aaa,bbb,ccc,ddd,eee
In Step 6 we are grouping the date by ID.
STUFF( source_string, start, length, add_string ) Parameters or Arguments source_string The source string to modify. start The position in the source_string to delete length characters and then insert add_string. length The number of characters to delete from source_string. add_string The sequence of characters to insert into the source_string at the start position.
SELECT ID,
abc =
STUFF (
(SELECT
',' +Name
FROM temp1
FOR XML PATH('')), 1, 1, ''
)
FROM temp1 GROUP by iD
Output:
-----------------------------------
| Id | Name |
|---------------------------------|
| 1 | aaa,bbb,ccc,ddd,eee |
-----------------------------------
If you only have as "click event handler", use a <button>
instead. A link has a specific semantic meaning.
E.g.:
<button onclick="ShowOld(2367,146986,2)">
<img title="next page" alt="next page" src="/themes/me/img/arrn.png">
</button>
I got the same error too .. my error is unmet dependencies /var/cache/apt/archives/mongodb-org-server_4.4.2_amd64.deb
and I ran this:
sudo dpkg -i --force-all /var/cache/apt/archives/mongodb-org-server_4.4.2_amd64.deb
and it worked
My OneLiner:
var MyList = new List<MyType>(MyDico.Values);
For a period I had to extract the Media ID myself quite frequently, so I wrote my own script (very likely it's based on some of the examples here). Together with other small scripts I used frequently, I started to upload them on www.findinstaid.com for my own quick access.
I added the option to enter a username to get the media ID of the 12 most recent posts, or to enter a URL to get the media ID of a specific post.
If it's convenient, everyone can use the link (I don't have any adds or any other monetary interests in the website - I only have a referral link on the 'Audit' tab to www.auditninja.io which I do also own, but also on this site, there are no adds or monetary interests - just hobby projects).
If you give the element a tabindex
then you can use the :focus
pseudo class to simulate a click.
HTML
<img id="btnLeft" tabindex="0" src="http://placehold.it/250x100" />
CSS
#btnLeft:focus{
width:70px;
height:74px;
}
I too wanted to do something similar, this is what I found: (SDK 3.1.3)
I have a view controller A (itself owned by a Nav controller) which loads VC B on a button press:
In AViewController.m
BViewController *bController = [[BViewController alloc] initWithNibName:@"Bnib" bundle:nil];
[self.navigationController pushViewController:bController animated:YES];
[bController release];
Now VC B has its interface from Bnib, but when a button is pressed, I want to go to an 'edit mode' which has a separate UI from a different nib, but I don't want a new VC for the edit mode, I want the new nib to be associated with my existing B VC.
So, in BViewController.m (in button press method)
NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"EditMode" owner:self options:nil];
UIView *theEditView = [nibObjects objectAtIndex:0];
self.editView = theEditView;
[self.view addSubview:theEditView];
Then on another button press (to exit edit mode):
[editView removeFromSuperview];
and I'm back to my original Bnib.
This works fine, but note my EditMode.nib has only 1 top level obj in it, a UIView obj. It doesn't matter whether the File's Owner in this nib is set as BViewController or the default NSObject, BUT make sure the View Outlet in the File's Owner is NOT set to anything. If it is, then I get a exc_bad_access crash and xcode proceeds to load 6677 stack frames showing an internal UIView method repeatedly called... so looks like an infinite loop. (The View Outlet IS set in my original Bnib however)
Hope this helps.
Swift:
func updateCell(path:Int){
let indexPath = NSIndexPath(forRow: path, inSection: 1)
tableView.beginUpdates()
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) //try other animations
tableView.endUpdates()
}
Best way to solve this until a fix is available (if a fix comes) is to force IE compatibility mode on the user.
Use <META http-equiv="X-UA-Compatible" content="IE=9">
ideally in the masterpage so all pages in your site get the workaround.
ViewGroup
is itself a View
that works as a container for other views. It extends the functionality of View
class in order to provide efficient ways to layout the child views.
For example, LinearLayout
is a ViewGroup
that lets you define the orientation in which you want child views to be laid, that's all you need to do and LinearLayout
will take care of the rest.
I had been experiencing this problem and nothing seemed to work until I moved the log call into a handler. Now it works every time, no matter where you are at.
This:
ORDER BY 1
...is known as an "Ordinal" - the number stands for the column based on the number of columns defined in the SELECT clause. In the query you provided, it means:
ORDER BY A.PAYMENT_DATE
It's not a recommended practice, because:
Actually, it is as simple as setting major
and minor
separately:
In [9]: plot([23, 456, 676, 89, 906, 34, 2345])
Out[9]: [<matplotlib.lines.Line2D at 0x6112f90>]
In [10]: yscale('log')
In [11]: grid(b=True, which='major', color='b', linestyle='-')
In [12]: grid(b=True, which='minor', color='r', linestyle='--')
The gotcha with minor grids is that you have to have minor tick marks turned on too. In the above code this is done by yscale('log')
, but it can also be done with plt.minorticks_on()
.
In C++11 you can clear the queue by doing this:
std::queue<int> queue;
// ...
queue = {};
Out of curiosity, I found a box with a GNU version of sed
(v4.1.5) and tested the (uncached) performance of two approaches suggested so far, using an 11M line text file:
$ wc -l input
11771722 input
$ time head -1000 input > output; time tail -n +1000 input > input.tmp; time cp input.tmp input; time rm input.tmp
real 0m1.165s
user 0m0.030s
sys 0m1.130s
real 0m1.256s
user 0m0.062s
sys 0m1.162s
real 0m4.433s
user 0m0.033s
sys 0m1.282s
real 0m6.897s
user 0m0.000s
sys 0m0.159s
$ time head -1000 input > output && time sed -i '1,+999d' input
real 0m0.121s
user 0m0.000s
sys 0m0.121s
real 0m26.944s
user 0m0.227s
sys 0m26.624s
This is the Linux I was working with:
$ uname -a
Linux hostname 2.6.18-128.1.1.el5 #1 SMP Mon Jan 26 13:58:24 EST 2009 x86_64 x86_64 x86_64 GNU/Linux
For this test, at least, it looks like sed
is slower than the tail
approach (27 sec vs ~14 sec).
This program is the bug free and enhanced version of the above MD5 cracker that reads the file containing list of hashed passwords and checks it against hashed word from the English dictionary word list. Hope it is helpful.
I downloaded the English dictionary from the following link https://github.com/dwyl/english-words
# md5cracker.py
# English Dictionary https://github.com/dwyl/english-words
import hashlib, sys
hash_file = 'exercise\hashed.txt'
wordlist = 'data_sets\english_dictionary\words.txt'
try:
hashdocument = open(hash_file,'r')
except IOError:
print('Invalid file.')
sys.exit()
else:
count = 0
for hash in hashdocument:
hash = hash.rstrip('\n')
print(hash)
i = 0
with open(wordlist,'r') as wordlistfile:
for word in wordlistfile:
m = hashlib.md5()
word = word.rstrip('\n')
m.update(word.encode('utf-8'))
word_hash = m.hexdigest()
if word_hash==hash:
print('The word, hash combination is ' + word + ',' + hash)
count += 1
break
i += 1
print('Itiration is ' + str(i))
if count == 0:
print('The hash given does not correspond to any supplied word in the wordlist.')
else:
print('Total passwords identified is: ' + str(count))
sys.exit()
Stuff them into a map
(pseudocode)
map[string -> int] $m
foreach($word in $array)
{
if(!$m.contains($word))
$m[$word] = 0;
$m[$word] += 1;
}
Using boolean algebra, it is easy to show that:
A xor B = (not A and B) or (A and not B)
A B | f = notA and B | g = A and notB | f or g | A xor B
----+----------------+----------------+--------+--------
0 0 | 0 | 0 | 0 | 0
0 1 | 1 | 0 | 1 | 1
1 0 | 0 | 1 | 1 | 1
1 1 | 0 | 0 | 0 | 0
You can use a prototype assignment within the constructor definition.
The variable will be visible to the prototype added method but all the instances of the functions will access the same SHARED variable.
function A()
{
var sharedVar = 0;
this.local = "";
A.prototype.increment = function(lval)
{
if (lval) this.local = lval;
alert((++sharedVar) + " while this.p is still " + this.local);
}
}
var a = new A();
var b = new A();
a.increment("I belong to a");
b.increment("I belong to b");
a.increment();
b.increment();
I hope this can be usefull.
Another Solution to isolate a character in a string
package main
import "fmt"
func main() {
var word string = "ZbjTS"
// P R I N T
fmt.Println(word)
yo := string([]rune(word)[0])
fmt.Println(yo)
//I N D E X
x :=0
for x < len(word){
yo := string([]rune(word)[x])
fmt.Println(yo)
x+=1
}
}
for string arrays also:
fmt.Println(string([]rune(sArray[0])[0]))
// = commented line
lintOptions {
checkReleaseBuilds false
abortOnError false
}
The above code can fix the problem by ignoring it, but it may result in crashing the app as well.
The good answer is in the following link:
Because in IE7 elem.attributes lists all possible attributes, not only the present ones, we have to test the attribute value. This plugin works in all major browsers:
(function($) {
$.fn.getAttributes = function () {
var elem = this,
attr = {};
if(elem && elem.length) $.each(elem.get(0).attributes, function(v,n) {
n = n.nodeName||n.name;
v = elem.attr(n); // relay on $.fn.attr, it makes some filtering and checks
if(v != undefined && v !== false) attr[n] = v
})
return attr
}
})(jQuery);
Usage:
var attribs = $('#some_id').getAttributes();
Just To mention, in CSS 3
:after
should be used like this
::after
From https://developer.mozilla.org/de/docs/Web/CSS/::after :
The ::after notation was introduced in CSS 3 in order to establish a discrimination between pseudo-classes and pseudo-elements. Browsers also accept the notation :after introduced in CSS 2.
So it should be:
li { display: inline; list-style-type: none; }
li::after { content: ", "; }
li:last-child::before { content: "and "; }
li:last-child::after { content: "."; }
You can use this also,
<CheckBox
android:layout_width="match_parent"
android:layout_height="@dimen/button_height_35"
android:text="@string/english"
android:checked="true"
android:paddingEnd="@dimen/padding_5"
android:paddingStart="@dimen/padding_5"
android:layoutDirection="rtl"
android:drawablePadding="@dimen/padding_5"
android:drawableEnd="@drawable/ic_english"
style="@style/TextStyleSemiBold"
android:textSize="@dimen/text_15"
android:button="@drawable/language_selector"/>
A simple example without classes:
from tkinter import *
master = Tk()
# Create this method before you create the entry
def return_entry(en):
"""Gets and prints the content of the entry"""
content = entry.get()
print(content)
Label(master, text="Input: ").grid(row=0, sticky=W)
entry = Entry(master)
entry.grid(row=0, column=1)
# Connect the entry with the return button
entry.bind('<Return>', return_entry)
mainloop()
The easier way is to just use pprint
, which is in base Python
import pprint
item = MyDjangoModel.objects.get(name = 'foo')
pprint.pprint(item.__dict__, indent = 4)
This gives output that looks similar to json.dumps(..., indent = 4)
but it correctly handles the weird data types that might be embedded in your model instance, such as ModelState
and UUID
, etc.
Tested on Python 3.7
input = InputBox("Text:")
If input <> "" Then
' Normal
Else
' Cancelled, or empty
End If
From MSDN:
If the user clicks Cancel, the function returns a zero-length string ("").
Above Answers are correct. I faced an different issue where in HTC M8 my application crashes when selecting an image from gallery. I'm getting null value for image path. I fixed and optimized with the following solution. in onActivityResult method
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ((requestCode == RESULT_LOAD_IMAGE) && (resultCode == RESULT_OK)) {
if (data != null) {
Uri selectedImageUri = null;
selectedImageUri = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor imageCursor = mainActivity.getContentResolver().query(
selectedImageUri, filePathColumn, null, null, null);
if (imageCursor == null) {
return;
}
imageCursor.moveToFirst();
int columnIndex = imageCursor.getColumnIndex(filePathColumn[0]);
picturePath = imageCursor.getString(columnIndex);
if (picturePath == null) {
picturePath = selectedImageUri.getPath();
String wholeID = DocumentsContract
.getDocumentId(selectedImage);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = { MediaStore.Images.Media.DATA };
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = mainActivity.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[] { id }, null);
columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
picturePath = cursor.getString(columnIndex);
}
cursor.close();
}
picturePathAbs = new File(picturePath).getAbsolutePath();
imageCursor.close();
}
}
If you have Ruby on your system you can do this:
http://unixgods.org/~tilo/Ruby/Using_Variables_in_CSS_Files_with_Ruby_on_Rails.html
This was made for Rails, but see below for how to modify it to run it stand alone.
You could use this method independently from Rails, by writing a small Ruby wrapper script which works in conjunction with site_settings.rb and takes your CSS-paths into account, and which you can call every time you want to re-generate your CSS (e.g. during site startup)
You can run Ruby on pretty much any operating system, so this should be fairly platform independent.
e.g. wrapper: generate_CSS.rb (run this script whenever you need to generate your CSS)
#/usr/bin/ruby # preferably Ruby 1.9.2 or higher
require './site_settings.rb' # assuming your site_settings file is on the same level
CSS_IN_PATH = File.join( PATH-TO-YOUR-PROJECT, 'css-input-files')
CSS_OUT_PATH = File.join( PATH-TO-YOUR-PROJECT, 'static' , 'stylesheets' )
Site.generate_CSS_files( CSS_IN_PATH , CSS_OUT_PATH )
the generate_CSS_files method in site_settings.rb then needs to be modified like this:
module Site
# ... see above link for complete contents
# Module Method which generates an OUTPUT CSS file *.css for each INPUT CSS file *.css.in we find in our CSS directory
# replacing any mention of Color Constants , e.g. #SomeColor# , with the corresponding color code defined in Site::Color
#
# We will only generate CSS files if they are deleted or the input file is newer / modified
#
def self.generate_CSS_files(input_path = File.join( Rails.root.to_s , 'public' ,'stylesheets') ,
output_path = File.join( Rails.root.to_s , 'public' ,'stylesheets'))
# assuming all your CSS files live under "./public/stylesheets"
Dir.glob( File.join( input_path, '*.css.in') ).each do |filename_in|
filename_out = File.join( output_path , File.basename( filename_in.sub(/.in$/, '') ))
# if the output CSS file doesn't exist, or the the input CSS file is newer than the output CSS file:
if (! File.exists?(filename_out)) || (File.stat( filename_in ).mtime > File.stat( filename_out ).mtime)
# in this case, we'll need to create the output CSS file fresh:
puts " processing #{filename_in}\n --> generating #{filename_out}"
out_file = File.open( filename_out, 'w' )
File.open( filename_in , 'r' ).each do |line|
if line =~ /^\s*\/\*/ || line =~ /^\s+$/ # ignore empty lines, and lines starting with a comment
out_file.print(line)
next
end
while line =~ /#(\w+)#/ do # substitute all the constants in each line
line.sub!( /#\w+#/ , Site::Color.const_get( $1 ) ) # with the color the constant defines
end
out_file.print(line)
end
out_file.close
end # if ..
end
end # def self.generate_CSS_files
end # module Site
This works:
Suppose
dbo.AsDesignedBites.XN1E1 = 4016519.564`
For the following string:
'POLYGON(('+STR(dbo.AsDesignedBites.XN1E1, 11, 3)+'...
If you always add to the end, then each element will be added to the end and stay that way until you change it.
If you always insert at the start, then each element will appear in the reverse order you added them.
If you insert them in the middle, the order will be something else.
I know this has several answers, but none of these really helped me. I found [this article][1] which explains why my sticky
wasn't operating as expected.
Basically, you cannot use position: sticky;
on <thead>
or <tr>
elements. However, they can be used on <th>
.
The minimum code I needed to make it work is as follows:
table {
text-align: left;
position: relative;
}
th {
background: white;
position: sticky;
top: 0;
}
With the table set to relative the <th>
can be set to sticky, with the top at 0
[1]: https://css-tricks.com/position-sticky-and-table-headers/
NOTE: It's necessary to wrap the table with a div with max-height:
<div id="managerTable" >
...
</div>
where:
#managerTable {
max-height: 500px;
overflow: auto;
}
If you enable Query Store on SQL Server 2016 or newer you can use the following query to get last SP execution. The history depends on the Query Store Configuration.
SELECT
ObjectName = '[' + s.name + '].[' + o.Name + ']'
, LastModificationDate = MAX(o.modify_date)
, LastExecutionTime = MAX(q.last_execution_time)
FROM sys.query_store_query q
INNER JOIN sys.objects o
ON q.object_id = o.object_id
INNER JOIN sys.schemas s
ON o.schema_id = s.schema_id
WHERE o.type IN ('P')
GROUP BY o.name , + s.name
In PyCharm, I'd leave it out. It turns off the UTF-8 indicator at the bottom with a warning that the encoding is hard-coded. Don't think you need the PyCharm comment mentioned above.
I tried to require a development branch from a different repository and not the latest version and I had the same issue and non of the above worked for me :(
after a while I saw in the documentation that in cases of dev branch you need to require with a 'dev-' prefix to the version and the following worked perfectly.
composer require [vendorName]/[packageName]:dev-[gitBranchName]
You can use regular expressions, and it works:
boolean found = s1.matches("(?i).*" + s2+ ".*");
I am using algorithm which continues dividing the number by it's current Prime Factor.
My Solution in python 3 :
def PrimeFactor(n):
m = n
while n%2==0:
n = n//2
if n == 1: # check if only 2 is largest Prime Factor
return 2
i = 3
sqrt = int(m**(0.5)) # loop till square root of number
last = 0 # to store last prime Factor i.e. Largest Prime Factor
while i <= sqrt :
while n%i == 0:
n = n//i # reduce the number by dividing it by it's Prime Factor
last = i
i+=2
if n> last: # the remaining number(n) is also Factor of number
return n
else:
return last
print(PrimeFactor(int(input())))
Input : 10
Output : 5
Input : 600851475143
Output : 6857
You can use Javascript to parse your DOM, and highlight the link with the same label than the first h1 tags. But I think it is overkill =)
It would be better to set a var wich contain the title of your page, and use it to add a class at the corresponding link.
If you just want to check string equality, use the == operator. Determining whether two strings are equal is simpler than finding an ordering (which is what compare() gives,) so it might be better performance-wise in your case to use the equality operator.
Longer answer: The API provides a method to check for string equality and a method to check string ordering. You want string equality, so use the equality operator (so that your expectations and those of the library implementors align.) If performance is important then you might like to test both methods and find the fastest.
Using Visual Studio
This gives details about each assembly, app domain and has a few options to load symbols (i.e. pdb files that contain debug information).
Using Process Explorer
If you want an external tool you can use the Process Explorer (freeware, published by Microsoft)
Click on a process and it will show a list with all the assemblies used. The tool is pretty good as it shows other information such as file handles etc.
Programmatically
Check this SO question that explains how to do it.
Below code will hide your text with fixed width you decide. but not quite right for responsive designs.
.CropLongTexts {
width: 170px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
Update
I have noticed in (mobile) device(s) that the text (mixed) with each other due to (fixed width)... so i have edited the code above to become hidden responsively as follow:
.CropLongTexts {
max-width: 170px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
The (max-width) ensure the text will be hidden responsively whatever the (screen size) and will not mixed with each other.
Yes, you can.
From cplusplus.com:
Because these functions are operator overloading functions, the usual way in which they are called is:
strm >> variable;
Where
strm
is the identifier of a istream object andvariable
is an object of any type supported as right parameter. It is also possible to call a succession of extraction operations as:strm >> variable1 >> variable2 >> variable3; //...
which is the same as performing successive extractions from the same object
strm
.
Just replace strm
with cin
.
if (!String.prototype.hasOwnProperty('addSlashes')) {
String.prototype.addSlashes = function() {
return this.replace(/&/g, '&') /* This MUST be the 1st replacement. */
.replace(/'/g, ''') /* The 4 other predefined entities, required. */
.replace(/"/g, '"')
.replace(/\\/g, '\\\\')
.replace(/</g, '<')
.replace(/>/g, '>').replace(/\u0000/g, '\\0');
}
}
Usage: alert(str.addSlashes());
Easy
import pymongo
conn = pymongo.MongoClient()
db = conn.test #test is my database
col = db.spam #Here spam is my collection
array = list(col.find())
print array
There you go
Basically, no difference. The only consistent trend is that Python seems to be getting slower with every version... :(
%%timeit
x = []
for i in range(100000000): # xrange on Python 2.7
x.append('a')
x = ''.join(x)
Python 2.7
1 loop, best of 3: 7.34 s per loop
Python 3.4
1 loop, best of 3: 7.99 s per loop
Python 3.5
1 loop, best of 3: 8.48 s per loop
Python 3.6
1 loop, best of 3: 9.93 s per loop
%%timeit
x = ''
for i in range(100000000): # xrange on Python 2.7
x += 'a'
Python 2.7:
1 loop, best of 3: 7.41 s per loop
Python 3.4
1 loop, best of 3: 9.08 s per loop
Python 3.5
1 loop, best of 3: 8.82 s per loop
Python 3.6
1 loop, best of 3: 9.24 s per loop
Is there a way to remove all previous click events that have been assigned to a button?
$('#saveBtn').unbind('click').click(function(){saveQuestion(id)});
PowerShell comes with a built in command for it. So running directly from a .bat
file:
powershell -ExecutionPolicy ByPass -Command Send-MailMessage ^
-SmtpServer server.address.name ^
-To [email protected] ^
-From [email protected] ^
-Subject Testing ^
-Body 123
NB -ExecutionPolicy ByPass
is only needed if you haven't set up permissions for running PS from CMD
Also for those looking to call it from within powershell, drop everything before -Command
[inclusive], and `
will be your escape character (not ^
)
If you use a CompletableFuture (introduced in Java 8) or a SettableFuture (from Google Guava), you can make your test finish as soon as it's done, rather than waiting a pre-set amount of time. Your test would look something like this:
CompletableFuture<String> future = new CompletableFuture<>();
executorService.submit(new Runnable() {
@Override
public void run() {
future.complete("Hello World!");
}
});
assertEquals("Hello World!", future.get());
You can do it programmatically:
ddlColor.DataSource = from p in db.ProductTypes
where p.ProductID == pID
orderby p.Color
select new { p.Color };
ddlColor.DataTextField = "Color";
ddlColor.DataBind();
ddlColor.Items.Insert(0, new ListItem("Select", "NA"));
Or add it in markup as:
<asp:DropDownList .. AppendDataBoundItems="true">
<Items>
<asp:ListItem Text="Select" Value="" />
</Items>
</asp:DropDownList>
An optimized Imran Tariq's version
Pattern.compile(strptrn, Pattern.CASE_INSENSITIVE + Pattern.LITERAL).matcher(str1).find();
Pattern.quote(strptrn) always returns "\Q" + s + "\E" even if there is nothing to quote, concatination spoils performance.
#include<stdio.h>
using namespace std;
int main()
{
printf("%s",__DATE__);
printf("%s",__TIME__);
return 0;
}
I'm surprised that no-one's mentioned this but you could just create an interface called ObjectLiteral
, that accepts key: value
pairs of type string: any
:
interface ObjectLiteral {
[key: string]: any;
}
Then you'd use it, like this:
let data: ObjectLiteral = {
hello: "world",
goodbye: 1,
// ...
};
An added bonus is that you can re-use this interface many times as you need, on as many objects you'd like.
Good luck.
Problem is that while runtime generic type is erased so new E[10]
would be equivalent to new Object[10]
.
This would be dangerous because it would be possible to put in array other data than of E
type. That is why you need to explicitly say that type you want by either
E[]
array, or componentType
argiment.You can simply use the method text() of jQuery to get all the content of the text contained in the element. The text() method also returns the textual content of the child elements.
HTML Code:
<div id="box">
<p>Lorem ipsum elit sit ut, consectetur adipiscing dolor.</p>
</div>
JQuery Code:
$(document).ready(function(){
$("button").click(function(){
var divContent = $('#box').text();
alert(divContent);
});
});
You can see an example here: How to get the text content of an element with jQuery
It's possible to build PyCrypto using the Windows 7 SDK toolkits. There are two versions of the Windows 7 SDK. The original version (for .Net 3.5) includes the VS 2008 command-line compilers. Both 32- and 64-bit compilers can be installed.
The first step is to compile mpir to provide fast arithmetic. I've documented the process I use in the gmpy library. Detailed instructions for building mpir using the SDK compiler can be found at sdk_build
The key steps to use the SDK compilers from a DOS prompt are:
1) Run either vcvars32.bat or vcvars64.bat as appropriate.
2) At the prompt, execute "set MSSdk=1"
3) At the prompt, execute "set DISTUTILS_USE_SDK=1"
This should allow "python setup.py install" to succeed assuming there are no other issues with the C code. But I vaaguely remember that I had to edit a couple of PyCrypto files to enable mpir and to find the mpir libraries but I don't have my Windows system up at the moment. It will be a couple of days before I'll have time to recreate the steps. If you haven't reported success by then, I'll post the PyCrypto steps. The steps will assume you were able to compile mpir.
I hope this helps.
No. If such a feature existed it would be listed in this syntax illustration. (Although it's possible there is an undocumented SQL feature, or maybe there is some package that I'm not aware of.)
you don't need to pass any regular expression there. this works just fine..
(function($) {
$(document).ready(function() {
$('#data').click(function(e) {
e.preventDefault();
$.each($("#keywords").val().split("\n"), function(e, element) {
alert(element);
});
});
});
})(jQuery);
try this one http://code.google.com/p/geckofx/ hope it ain't dupe or this one i think is better http://webkitdotnet.sourceforge.net/
Thankyou Frank.i got the idea. Here is the working code.
Option Explicit
Private Sub CommandButton1_Click()
Dim directory As String, fileName As String, sheet As Worksheet, total As Integer
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
.Title = "Please select the file."
.Filters.Clear
.Filters.Add "Excel 2003", "*.xls?"
If .Show = True Then
fileName = Dir(.SelectedItems(1))
End If
End With
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Workbooks.Open (fileName)
For Each sheet In Workbooks(fileName).Worksheets
total = Workbooks("import-sheets.xlsm").Worksheets.Count
Workbooks(fileName).Worksheets(sheet.Name).Copy _
after:=Workbooks("import-sheets.xlsm").Worksheets(total)
Next sheet
Workbooks(fileName).Close
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
The main difference is that a 8-bit PNG comprises a max. of 256 colours, like GIFs. PNG-24 is a lossless format and can contain up to 16 million colours.
As Vicky already pointed out, %DATE%
and %TIME%
return the current date and time using the short date and time formats that are fully (endlessly) customizable.
One user may configure its system to return Fri040811 08.03PM while another user may choose 08/04/2011 20:30.
It's a complete nightmare for a BAT programmer.
Changing the format to a firm format may fix the problem, provided you restore back the previous format before leaving the BAT file. But it may be subject to nasty race conditions and complicate recovery in cancelled BAT files.
Fortunately, there is an alternative.
You may use WMIC, instead. WMIC Path Win32_LocalTime Get Day,Hour,Minute,Month,Second,Year /Format:table
returns the date and time in a invariable way. Very convenient to directly parse it with a FOR /F
command.
So, putting the pieces together, try this as a starting point...
SETLOCAL enabledelayedexpansion
FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
SET /A FD=%%F*1000000+%%D*100+%%A
SET /A FT=10000+%%B*100+%%C
SET FT=!FT:~-4!
ECHO Archive_!FD!_!FT!.zip
)
If you don't wish to mess with IFS (perhaps for the code within the loop) this might help.
If know that your string will not have whitespace, you can substitute the ';' with a space and use the for/in construct:
#local str
for str in ${STR//;/ } ; do
echo "+ \"$str\""
done
But if you might have whitespace, then for this approach you will need to use a temp variable to hold the "rest" like this:
#local str rest
rest=$STR
while [ -n "$rest" ] ; do
str=${rest%%;*} # Everything up to the first ';'
# Trim up to the first ';' -- and handle final case, too.
[ "$rest" = "${rest/;/}" ] && rest= || rest=${rest#*;}
echo "+ \"$str\""
done
a = [0,1,2,3,127,200,255]
print str.join("", ("%02x" % i for i in a))
prints
000102037fc8ff
(Also note that your code will fail for integers in the range from 10 to 15.)
LinkedHashMap
is precisely what you're looking for.
It is exactly like HashMap
, except that when you iterate over it, it presents the items in the insertion order.
This solution worked well for me: http://www.apachefriends.org/f/viewtopic.php?f=17&t=50902&p=196185#p196185
Edit /opt/lampp/etc/extra/httpd-xampp.conf and adding Require all granted line at bottom of block <Directory "/opt/lampp/phpmyadmin">
to have the following code:
<Directory "/opt/lampp/phpmyadmin">
AllowOverride AuthConfig Limit
Order allow,deny
Allow from all
Require all granted
</Directory>