A good alternative is SqlCmd, since it does include headers, but it has the downside of adding space padding around the data for human readability. You can combine SqlCmd with the GnuWin32 sed (stream editing) utility to cleanup the results. Here's an example that worked for me, though I can't guarantee that it's bulletproof.
First, export the data:
sqlcmd -S Server -i C:\Temp\Query.sql -o C:\Temp\Results.txt -s" "
The -s" "
is a tab character in double quotes. I found that you have to run this command via a batch file, otherwise the Windows command prompt will treat the tab as an automatic completion command and will substitute a filename in place of the tab.
If Query.sql contains:
SELECT name, object_id, type_desc, create_date
FROM MSDB.sys.views
WHERE name LIKE 'sysmail%'
then you'll see something like this in Results.txt
name object_id type_desc create_date ------------------------------------------- ----------- ------------------- ----------------------- sysmail_allitems 2001442204 VIEW 2012-07-20 17:38:27.820 sysmail_sentitems 2017442261 VIEW 2012-07-20 17:38:27.837 sysmail_unsentitems 2033442318 VIEW 2012-07-20 17:38:27.850 sysmail_faileditems 2049442375 VIEW 2012-07-20 17:38:27.860 sysmail_mailattachments 2097442546 VIEW 2012-07-20 17:38:27.933 sysmail_event_log 2129442660 VIEW 2012-07-20 17:38:28.040 (6 rows affected)
Next, parse the text using sed:
sed -r "s/ +\t/\t/g" C:\Temp\Results.txt | sed -r "s/\t +/\t/g" | sed -r "s/(^ +| +$)//g" | sed 2d | sed $d | sed "/^$/d" > C:\Temp\Results_New.txt
Note that the 2d
command means to delete the second line, the $d
command means to delete the last line, and "/^$/d"
deletes any blank lines.
The cleaned up file looks like this (though I replaced the tabs with |
so they could be visualized here):
name|object_id|type_desc|create_date sysmail_allitems|2001442204|VIEW|2012-07-20 17:38:27.820 sysmail_sentitems|2017442261|VIEW|2012-07-20 17:38:27.837 sysmail_unsentitems|2033442318|VIEW|2012-07-20 17:38:27.850 sysmail_faileditems|2049442375|VIEW|2012-07-20 17:38:27.860 sysmail_mailattachments|2097442546|VIEW|2012-07-20 17:38:27.933 sysmail_event_log|2129442660|VIEW|2012-07-20 17:38:28.040
I think the simplest way to do this is from Excel.
If you have a newer version of Excel you could bring the data in from PowerPivot and then insert this data into a table.
In my case, there is a single table which happens to be a device list from a router. If you wish to read the table using TR/TH/TD (row, header, data) instead of a matrix as mentioned above, you can do something like the following:
List<TableRow> deviceTable = (from table in document.DocumentNode.SelectNodes(XPathQueries.SELECT_TABLE)
from row in table?.SelectNodes(HtmlBody.TR)
let rows = row.SelectSingleNode(HtmlBody.TR)
where row.FirstChild.OriginalName != null && row.FirstChild.OriginalName.Equals(HtmlBody.T_HEADER)
select new TableRow
{
Header = row.SelectSingleNode(HtmlBody.T_HEADER)?.InnerText,
Data = row.SelectSingleNode(HtmlBody.T_DATA)?.InnerText}).ToList();
}
TableRow is just a simple object with Header and Data as properties. The approach takes care of null-ness and this case:
<tr>_x000D_
<td width="28%"> </td>_x000D_
</tr>
_x000D_
which is row without a header. The HtmlBody object with the constants hanging off of it are probably readily deduced but I apologize for it even still. I came from the world where if you have " in your code, it should either be constant or localizable.
var pinIcon = new google.maps.MarkerImage(
"http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|00D900",
null, /* size is determined at runtime */
null, /* origin is 0,0 */
null, /* anchor is bottom center of the scaled image */
new google.maps.Size(12, 18)
);
Are you committing the cell before pressing the button (pressing Enter)? The contents of the cell must be stored before it can be used to name a sheet.
A better way to do this is to pop up a dialog box and get the name you wish to use.
I try to avoid floating elements unless the design really needs it. Because you have floated the <li>
they are out of normal flow.
If you add .navigation { text-align:center; }
and change .navigation li { float: left; }
to .navigation li { display: inline-block; }
then entire navigation will be centred.
One caveat to this approach is that display: inline-block;
is not supported in IE6 and needs a workaround to make it work in IE7.
For console projects in a step-by-step fashion, you'll have to first add the System.Windows.Forms
reference. The following steps work in Visual Studio Community 2013 with .NET 4.5:
System.Windows.Forms
.Then, add the following using
statement in with the others at the top of your code:
using System.Windows.Forms;
Then, add either of the following Clipboard
.SetText
statements to your code:
Clipboard.SetText("hello");
// OR
Clipboard.SetText(helloString);
And lastly, add STAThreadAttribute
to your Main
method as follows, to avoid a System.Threading.ThreadStateException
:
[STAThreadAttribute]
static void Main(string[] args)
{
// ...
}
https://www.ripe.net/internet-coordination/press-centre/understanding-ip-addressing
For IPv4, this pool is 32-bits (2³²) in size and contains 4,294,967,296 IPv4 addresses.
In case of IPv6
The IPv6 address space is 128-bits (2¹²8) in size, containing 340,282,366,920,938,463,463,374,607,431,768,211,456 IPv6 addresses.
inclusive of RESERVED IP
Reserved address blocks
Range Description Reference
0.0.0.0/8 Current network (only valid as source address) RFC 6890
10.0.0.0/8 Private network RFC 1918
100.64.0.0/10 Shared Address Space RFC 6598
127.0.0.0/8 Loopback RFC 6890
169.254.0.0/16 Link-local RFC 3927
172.16.0.0/12 Private network RFC 1918
192.0.0.0/24 IETF Protocol Assignments RFC 6890
192.0.2.0/24 TEST-NET-1, documentation and examples RFC 5737
192.88.99.0/24 IPv6 to IPv4 relay (includes 2002::/16) RFC 3068
192.168.0.0/16 Private network RFC 1918
198.18.0.0/15 Network benchmark tests RFC 2544
198.51.100.0/24 TEST-NET-2, documentation and examples RFC 5737
203.0.113.0/24 TEST-NET-3, documentation and examples RFC 5737
224.0.0.0/4 IP multicast (former Class D network) RFC 5771
240.0.0.0/4 Reserved (former Class E network) RFC 1700
255.255.255.255 Broadcast RFC 919
You can use pragma related commands in sqlite like below
pragma table_info("table_name")
--Alternatively
select * from pragma_table_info("table_name")
If you require column names like id|foo|bar|age|street|address
, basically your answer is in below query.
select group_concat(name,'|') from pragma_table_info("table_name")
If problem persists after trying any of the above solutions, Restart your server once. It worked for me :)
yu have to install the correct version for your computer 32 or 63 bits thats all
You can use py2exe as already answered and use Cython to convert your key .py
files in .pyc
, C compiled files, like .dll
in Windows and .so
on Linux.
It is much harder to revert than common .pyo
and .pyc
files (and also gain in performance!).
I suggest to use
for string only state values
export default class Home extends React.Component<{}, { [key: string]: string }> { }
for string key and any type of state values
export default class Home extends React.Component<{}, { [key: string]: any}> { }
for any key / any values
export default class Home extends React.Component<{}, { [key: any]: any}> {}
This answer applies to using gVim on Windows 10. I cannot guarantee the same results for other operating systems.
Add:
set nobackup
set noswapfile
set noundofile
To your _vimrc file.
Note: This is the direct answer to the question (for Windows 10) and probably not the safest thing to do (read the other answers), but this is the fastest solution in my case.
As other posters have mentioned - there's no clean way to left-align the last row with flexbox (at least as per the current spec)
However, for what it's worth: With the CSS Grid Layout Module this is surprisingly easy to produce:
Basically the relevant code boils down to this:
ul {
display: grid; /* 1 */
grid-template-columns: repeat(auto-fill, 100px); /* 2 */
grid-gap: 1rem; /* 3 */
justify-content: space-between; /* 4 */
}
1) Make the container element a grid container
2) Set the grid with auto columns of width 100px. (Note the use of auto-fill (as apposed to auto-fit
- which (for a 1-row layout) collapses empty tracks to 0 - causing the items to expand to take up the remaining space. This would result in a justified 'space-between' layout when grid has only one row which in our case is not what we want. (check out this demo to see the difference between them)).
3) Set gaps/gutters for the grid rows and columns - here, since want a 'space-between' layout - the gap will actually be a minimum gap because it will grow as necessary.
4) Similar to flexbox.
ul {_x000D_
display: grid;_x000D_
grid-template-columns: repeat(auto-fill, 100px);_x000D_
grid-gap: 1rem;_x000D_
justify-content: space-between;_x000D_
_x000D_
/* boring properties */_x000D_
list-style: none;_x000D_
background: wheat;_x000D_
padding: 2rem;_x000D_
width: 80vw;_x000D_
margin: 0 auto;_x000D_
}_x000D_
_x000D_
li {_x000D_
height: 50px;_x000D_
border: 1px solid green;_x000D_
}
_x000D_
<ul>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
</ul>
_x000D_
You should use System property instead of environment variable for this case. Edit your tomcat scripts for JAVA_OPTS and add property like:
-DAPP_MASTER_PASSWORD=foo
and in your code, write
System.getProperty("APP_MASTER_PASSWORD");
You can do this in Eclipse as well, instead of JAVA_OPTS, copy the line in VM parameters inside run configurations.
There are two types of measurements you can use for specifying widths, heights, margins etc: relative and fixed.
An example of a relative measurement is percentages, which you have used. Percentages are relevant to their containing element. If there is no containing element they are relative to the window.
<div style="width:100%">
<!-- This div will be the full width of the browser, whatever size it is -->
<div style="width:300px">
<!-- this div will be 300px, whatever size the browser is -->
<p style="width:50%">
This paragraph's width will be 50% of it's parent (150px).
</p>
</div>
</div>
Another relative measurement is ems which are relative to font size.
An example of a fixed measurement is pixels but a fixed measurement can also be pt (points), cm (centimetres) etc. Fixed (sometimes called absolute) measurements are always the same size. A pixel is always a pixel, a centimetre is always a centimetre.
If you were to use fixed measurements for your sizes the browser size wouldn't affect the layout.
For me, to develop for web, works fine the following:
Image(
image: AssetImage('lib/images/portadaSchamann5.png'),
alignment: Alignment.center,
height: double.infinity,
width: double.infinity,
fit: BoxFit.fill,
),
systemd
sudo systemctl stop mysqld.service && sudo yum remove -y mariadb mariadb-server && sudo rm -rf /var/lib/mysql /etc/my.cnf
sysvinit
sudo service mysql stop && sudo apt-get remove mariadb mariadb-server && sudo rm -rf /var/lib/mysql /etc/my.cnf
Atomic size is 4096 bytes, max size is 65536 bytes. Sendfile uses 16 pipes each of 4096 bytes size. cmd : ioctl(fd, FIONREAD, &buff_size).
you can convert to array so get object name
var objs = [
{name: "Joe", age: 22},
{name: "Kevin", age: 24},
{name: "Peter", age: 21}
];
document.body.innerHTML = Object.values(objs).map(function(obj){
return obj.name;
});
_x000D_
I would suggest you just evenly space them as shown in this answer here
.navbar ul {
list-style-type: none;
padding: 0;
display: flex;
flex-direction: row;
justify-content: space-around;
flex-wrap: nowrap; /* assumes you only want one row */
}
I followed @Viktor Kerkez's answer and have had mixed success. I found that sometimes this recipe of
conda skeleton pypi PACKAGE
conda build PACKAGE
would look like everything worked but I could not successfully import PACKAGE. Recently I asked about this on the Anaconda user group and heard from @Travis Oliphant himself on the best way to use conda to build and manage packages that do not ship with Anaconda. You can read this thread here, but I'll describe the approach below to hopefully make the answers to the OP's question more complete...
Example: I am going to install the excellent prettyplotlib package on Windows using conda 2.2.5.
1a) conda build --build-recipe prettyplotlib
You'll see the build messages all look good until the final TEST section of the build. I saw this error
File "C:\Anaconda\conda-bld\test-tmp_dir\run_test.py", line 23 import None SyntaxError: cannot assign to None TESTS FAILED: prettyplotlib-0.1.3-py27_0
1b) Go into /conda-recipes/prettyplotlib and edit the meta.yaml file. Presently, the packages being set up like in step 1a result in yaml files that have an error in the test
section. For example, here is how mine looked for prettyplotlib
test: # Python imports imports:
-
- prettyplotlib
- prettyplotlib
Edit this section to remove the blank line preceded by the - and also remove the redundant prettyplotlib line. At the time of this writing I have found that I need to edit most meta.yaml files like this for external packages I am installing with conda, meaning that there is a blank import line causing the error along with a redundant import of the given package.
1c) Rerun the command from 1a, which should complete with out error this time. At the end of the build you'll be asked if you want to upload the build to binstar. I entered No and then saw this message:
If you want to upload this package to binstar.org later, type:
$ binstar upload C:\Anaconda\conda-bld\win-64\prettyplotlib-0.1.3-py27_0.tar.bz2
That tar.bz2 file is the build that you now need to actually install.
2) conda install C:\Anaconda\conda-bld\win-64\prettyplotlib-0.1.3-py27_0.tar.bz2
Following these steps I have successfully used conda to install a number of packages that do not come with Anaconda. Previously, I had installed some of these using pip, so I did pip uninstall PACKAGE
prior to installing PACKAGE with conda. Using conda, I can now manage (almost) all of my packages with a single approach rather than having a mix of stuff installed with conda, pip, easy_install, and python setup.py install.
For context, I think this recent blog post by @Travis Oliphant will be helpful for people like me who do not appreciate everything that goes into robust Python packaging but certainly appreciate when stuff "just works". conda seems like a great way forward...
What I use is simple. For example I have a nav bar that is position : fixed
so I adjust it to leave a small space to the edges like this.
nav {
right: 1%;
width: 98%;
position: fixed;
margin: auto;
padding: 0;
}
The idea is to take the remainder percentage of the width "in this case 2%" and use the half of it.
Don't stop and also save exit status
Just in case if you want your script not to stop if a particular command fails and you also want to save error code of failed command:
set -e
EXIT_CODE=0
command || EXIT_CODE=$?
echo $EXIT_CODE
I restarted eclipse and did the Project -> Clean -> select your project One of them fixed my problem with adb
[2011-12-31 10:50:45 - HelloAndroid] Android Launch! good
[2011-12-31 10:50:45 - HelloAndroid] adb is running normally. good
[2011-12-31 10:50:45 - HelloAndroid] Could not find HelloAndroid.apk! bad
Thanks for the help. On to the next problem (sigh)
Or use sed & regex.
<some_command> | sed 's/^.* \(".*"$\)/\1/'
I made a collection layout.
To make the separator visible, Set the background color of the collection view to gray. One row per section.
Useage:
let layout = GridCollectionViewLayout()
layout.cellHeight = 50 // if not set, cellHeight = Collection.height/numberOfSections
layout.cellWidth = 50 // if not set, cellWidth = Collection.width/numberOfItems(inSection)
collectionView.collectionViewLayout = layout
Layout:
import UIKit
class GridCollectionViewLayout: UICollectionViewLayout {
var cellWidth : CGFloat = 0
var cellHeight : CGFloat = 0
var seperator: CGFloat = 1
private var cache = [UICollectionViewLayoutAttributes]()
override func prepare() {
guard let collectionView = self.collectionView else {
return
}
self.cache.removeAll()
let numberOfSections = collectionView.numberOfSections
if cellHeight <= 0
{
cellHeight = (collectionView.bounds.height - seperator*CGFloat(numberOfSections-1))/CGFloat(numberOfSections)
}
for section in 0..<collectionView.numberOfSections {
let numberOfItems = collectionView.numberOfItems(inSection: section)
let cellWidth2 : CGFloat
if cellWidth <= 0
{
cellWidth2 = (collectionView.bounds.width - seperator*CGFloat(numberOfItems-1))/CGFloat(numberOfItems)
}
else
{
cellWidth2 = cellWidth
}
for row in 0..<numberOfItems {
let indexPath = NSIndexPath(row: row, section: section)
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath as IndexPath)
attributes.frame = CGRect(x: (cellWidth2+seperator)*CGFloat(row),
y: (cellHeight+seperator)*CGFloat(section),
width: cellWidth2,
height: cellHeight)
//row_temp.append(attributes)
self.cache.append(attributes)
}
//self.itemAttributes.append(row_temp)
}
}
override var collectionViewContentSize: CGSize {
guard let collectionView = collectionView else
{
return CGSize.zero
}
if (collectionView.numberOfSections <= 0)
{
return collectionView.bounds.size
}
let width:CGFloat
if cellWidth <= 0
{
width = collectionView.bounds.width
}
else
{
width = cellWidth*CGFloat(collectionView.numberOfItems(inSection: 0))
}
let numberOfSections = CGFloat(collectionView.numberOfSections)
var height:CGFloat = 0
height += numberOfSections * cellHeight
height += (numberOfSections - 1) * seperator
return CGSize(width: width, height: height)
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var layoutAttributes = [UICollectionViewLayoutAttributes]()
for attributes in cache {
if attributes.frame.intersects(rect) {
layoutAttributes.append(attributes)
}
}
return layoutAttributes
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
return cache[indexPath.item]
}
}
Set the PATH variable, like you're doing. If you're running the program from the IDE, you can modify environment variables by adjusting the Debugging options in the project properties.
If the DLLs are named such that you don't need different paths for the different configuration types, you can add the path to the system PATH variable or to Visual Studio's global one in Tools | Options.
For PHP >= 5.4 you can use a simpler function like this : http_response_code(404);
PHP Documentation
The OP's questions about canonical form and how it can improve performance of the equals
method can both be answered by extending the example provided in Effective Java.
Consider the following class:
public final class CaseInsensitiveString {
private final String s;
public CaseInsensitiveString(String s) {
this.s = Objects.requireNonNull(s);
}
@Override
public boolean equals(Object o) {
return o instanceof CaseInsensitiveString && ((CaseInsensitiveString) o).s.equalsIgnoreCase(s);
}
}
The equals
method in this example has added cost by using String
's equalsIgnoreCase
method. As mentioned in the text
you may want to store a canonical form of the field so the equals method can do a cheap exact comparison on canonical forms rather than a more costly nonstandard comparison.
What does Joshua Bloch mean when he says canonical form? Well, I think Dónal's concise answer is very appropriate. We can store the underlying String
field in the CaseInsensitiveString
example in a standard way, perhaps the uppercase form of the String
. Now, you can reference this canonical form of the CaseInsensitiveString
, its uppercase variant, and perform cheap evaluations in your equals
and hashcode
methods.
Another more efficient way to do is just use @Value
@Value("classpath:sss.json")
private Resource resource;
and after that you can just get the file this way
File file = resource.getFile();
You need Set with objects:
Set rng = Sheet8.Range("A12")
Sheet8 is fine.
Sheet1.[a1]
I'm Daniel Stenberg.
I founded the curl project back in 1998, I wrote the initial curl version and I created libcurl. I've written more than half of all the 24,000 commits done in the source code repository up to this point in time. I'm still the lead developer of the project. To a large extent, curl is my baby.
I shipped the first version of curl as open source since I wanted to "give back" to the open source world that had given me so much code already. I had used so much open source and I wanted to be as cool as the other open source authors.
Thanks to it being open source, literally thousands of people have been able to help us out over the years and have improved the products, the documentation. the web site and just about every other detail around the project. curl and libcurl would never have become the products that they are today were they not open source. The list of contributors now surpass 1900 names and currently the list grows with a few hundred names per year.
Thanks to curl and libcurl being open source and liberally licensed, they were immediately adopted in numerous products and soon shipped by operating systems and Linux distributions everywhere thus getting a reach beyond imagination.
Thanks to them being "everywhere", available and liberally licensed they got adopted and used everywhere and by everyone. It created a defacto transfer library standard.
At an estimated six billion installations world wide, we can safely say that curl is the most widely used internet transfer library in the world. It simply would not have gone there had it not been open source. curl runs in billions of mobile phones, a billion Windows 10 installations, in a half a billion games and several hundred million TVs - and more.
Should I have released it with proprietary license instead and charged users for it? It never occured to me, and it wouldn't have worked because I would never had managed to create this kind of stellar project on my own. And projects and companies wouldn't have used it.
Now, why do I and my fellow curl developers still continue to develop curl and give it away for free to the world?
Yes. So insanely much.
But I'm not satisfied with this and I'm not just leaning back, happy with what we've done. I keep working on curl every single day, to improve, to fix bugs, to add features and to make sure curl keeps being the number one file transfer solution for the world even going forward.
We do mistakes along the way. We make the wrong decisions and sometimes we implement things in crazy ways. But to win in the end and to conquer the world is about patience and endurance and constantly going back and reconsidering previous decisions and correcting previous mistakes. To continuously iterate, polish off rough edges and gradually improve over time.
Never give in. Never stop. Fix bugs. Add features. Iterate. To the end of time.
Yeah. For real.
Sure I get tired at times. Working on something every day for over twenty years isn't a paved downhill road. Sometimes there are obstacles. During times things are rough. Occasionally people are just as ugly and annoying as people can be.
But curl is my life's project and I have patience. I have thick skin and I don't give up easily. The tough times pass and most days are awesome. I get to hang out with awesome people and the reward is knowing that my code helps driving the Internet revolution everywhere is an ego boost above normal.
curl will never be "done" and so far I think work on curl is pretty much the most fun I can imagine. Yes, I still think so even after twenty years in the driver's seat. And as long as I think it's fun I intend to keep at it.
I am using django with postgres in Docker containers. in the docker-compose file, add the following:
db:
image: postgres:10-alpine
environment:
- POSTGRES_DB=app
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=supersecretpassword
**ports:
- "6543:5432"**
which will add accessible port by your local machine. for myself, I connected DBeaver to it. this will prevent port clashes between your app request and local machine request. at first, I got a message saying that the port 5432 is in use (which is by django app) so I couldn't access by pgAdmin or DBeaver.
Yes, the Jackson manual parser design is quite different from other libraries. In particular, you will notice that JsonNode
has most of the functions that you would typically associate with array nodes from other API's. As such, you do not need to cast to an ArrayNode
to use. Here's an example:
JSON:
{
"objects" : ["One", "Two", "Three"]
}
Code:
final String json = "{\"objects\" : [\"One\", \"Two\", \"Three\"]}";
final JsonNode arrNode = new ObjectMapper().readTree(json).get("objects");
if (arrNode.isArray()) {
for (final JsonNode objNode : arrNode) {
System.out.println(objNode);
}
}
Output:
"One"
"Two"
"Three"
Note the use of isArray
to verify that the node is actually an array before iterating. The check is not necessary if you are absolutely confident in your datas structure, but its available should you need it (and this is no different from most other JSON libraries).
This happened to me because Xcode didn't appear to like me using the same variable name in two different classes (that conform to the same protocol, if that matters, although the variable name has nothing related in any protocol). I simply renamed my new variable.
I had to step into the setters where it was crashing in order to see it, while debugging. This answer applies to iOS
To convert a string with comma separated values to a string array use Split
:
string strOne = "One,Two,Three,Four";
string[] strArrayOne = new string[] {""};
//somewhere in your code
strArrayOne = strOne.Split(',');
Result will be a string array with four strings:
{"One","Two","Three","Four"}
You probably forgot to set the form's KeyPreview property to True. Overriding the ProcessCmdKey() method is the generic solution:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
if (keyData == (Keys.Control | Keys.F)) {
MessageBox.Show("What the Ctrl+F?");
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
According to Google Maps' own help:
Currently Bootstrap 4 uses a background-image with embbed SVG data info that include the color of the SVG shape. Something like:
.carousel-control-prev-icon { background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23fff' viewBox='0 0 8 8'%3E%3Cpath d='M5.25 0l-4 4 4 4 1.5-1.5-2.5-2.5 2.5-2.5-1.5-1.5z'/%3E%3C/svg%3E"); }
Note the part about fill='%23fff'
it fills the shape with a color, in this case #fff (white), for red simply replace with #f00
Finally, it is safe to include this (same change for next-icon):
.carousel-control-prev-icon {background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23f00' viewBox='0 0 8 8'%3E%3Cpath d='M5.25 0l-4 4 4 4 1.5-1.5-2.5-2.5 2.5-2.5-1.5-1.5z'/%3E%3C/svg%3E"); }
On OSX 10.11, you can sudo nano /etc/paths
and add the path(s) you want here, one per line. Way simpler than figuring which of ~/.bashrc
, /etc/profile
, '~/.bash_profile` etc... you should add to. Besides, why export and append $PATH to itself when you can just go and modify PATH directly...?
For anyone encountering a similar situation I was able to solve the issue above as follows:
Regenerate your pkcs12 file as follows:
openssl pkcs12 -in oldpkcs.p12 -out keys -passout pass:tmp
openssl pkcs12 -in keys -export -out new.p12 -passin pass:tmp -passout pass:newpasswd
Import the CA certificate from server into a TrustStore ( either your own, or the java keystore in $JAVA_HOME/jre/lib/security/cacerts
, password: changeit
).
Set the following system properties:
System.setProperty("javax.net.ssl.trustStore", "myTrustStore");
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
System.setProperty("javax.net.ssl.keyStoreType", "pkcs12");
System.setProperty("javax.net.ssl.keyStore", "new.p12");
System.setProperty("javax.net.ssl.keyStorePassword", "newpasswd");
Test ur url.
Courtesy@ http://forums.sun.com/thread.jspa?threadID=5296333
In case you are like me, and cannot work out how to use "regular expression with capturing groups" for extract
, the following code replicates the extract(...)
line in Hadleys' answer:
df %>%
gather(question_number, value, starts_with("Q3.")) %>%
mutate(loop_number = str_sub(question_number,-2,-2), question_number = str_sub(question_number,1,4)) %>%
select(id, time, loop_number, question_number, value) %>%
spread(key = question_number, value = value)
The problem here is that the initial gather forms a key column that is actually a combination of two keys. I chose to use mutate
in my original solution in the comments to split this column into two columns with equivalent info, a loop_number
column and a question_number
column. spread
can then be used to transform the long form data, which are key value pairs (question_number, value)
to wide form data.
If you're using Apache POI 4.x, you can do that with:
Cell c = row.getCell(3);
if (c == null || c.getCellType() == CellType.Blank) {
// This cell is empty
}
For older Apache POI 3.x versions, which predate the move to the CellType
enum, it's:
Cell c = row.getCell(3);
if (c == null || c.getCellType() == Cell.CELL_TYPE_BLANK) {
// This cell is empty
}
Don't forget to check if the Row
is null though - if the row has never been used with no cells ever used or styled, the row itself might be null!
If your method is void and you want to check for an exception, you could use expected
:
https://weblogs.java.net/blog/johnsmart/archive/2009/09/27/testing-exceptions-junit-47
First, let's see what each function does:
regexObject.test( String )
Executes the search for a match between a regular expression and a specified string. Returns true or false.
string.match( RegExp )
Used to retrieve the matches when matching a string against a regular expression. Returns an array with the matches or
null
if there are none.
Since null
evaluates to false
,
if ( string.match(regex) ) {
// There was a match.
} else {
// No match.
}
Is there any difference regarding performance?
Yes. I found this short note in the MDN site:
If you need to know if a string matches a regular expression regexp, use regexp.test(string).
Is the difference significant?
The answer once more is YES! This jsPerf I put together shows the difference is ~30% - ~60% depending on the browser:
Use .test
if you want a faster boolean check. Use .match
to retrieve all matches when using the g
global flag.
Which operating system?
For windows machines, if you're writing a server to scale well, and therefore using I/O Completion Ports and async I/O, then the main limitation is the amount of non-paged pool that you're using for each active connection. This translates directly into a limit based on the amount of memory that your machine has installed (non-paged pool is a finite, fixed size amount that is based on the total memory installed).
For connections that don't see much traffic you can reduce make them more efficient by posting 'zero byte reads' which don't use non-paged pool and don't affect the locked pages limit (another potentially limited resource that may prevent you having lots of socket connections open).
Apart from that, well, you will need to profile but I've managed to get more than 70,000 concurrent connections on a modestly specified (760MB memory) server; see here http://www.lenholgate.com/blog/2005/11/windows-tcpip-server-performance.html for more details.
Obviously if you're using a less efficient architecture such as 'thread per connection' or 'select' then you should expect to achieve less impressive figures; but, IMHO, there's simply no reason to select such architectures for windows socket servers.
Edit: see here http://blogs.technet.com/markrussinovich/archive/2009/03/26/3211216.aspx; the way that the amount of non-paged pool is calculated has changed in Vista and Server 2008 and there's now much more available.
I know this is an old question.
Here's another option - attending to different platform requirements - Source
<link rel='shortcut icon' type='image/vnd.microsoft.icon' href='/favicon.ico'> <!-- IE -->
<link rel='apple-touch-icon' type='image/png' href='/icon.57.png'> <!-- iPhone -->
<link rel='apple-touch-icon' type='image/png' sizes='72x72' href='/icon.72.png'> <!-- iPad -->
<link rel='apple-touch-icon' type='image/png' sizes='114x114' href='/icon.114.png'> <!-- iPhone4 -->
<link rel='icon' type='image/png' href='/icon.114.png'> <!-- Opera Speed Dial, at least 144×114 px -->
This is the broadest approach I have found so far.
Ultimately the decision depends on your own needs. Ask yourself, who is your target audience?
UPDATE May 27, 2018: As expected, time goes by and things change. But there's good news too. I found a tool called Real Favicon Generator that generates all the required lines for the icon to work on all modern browsers and platforms. It doesn't handle backwards compatibility though.
You can try this as well:
from time import perf_counter
t0 = perf_counter()
...
t1 = perf_counter()
time_taken = t1 - t0
In case anyone wishes to do this with bootstrap, version 4 offers the following:
The classes are named using the format {property}{sides}-{size} for xs and {property}{sides}-{breakpoint}-{size} for sm, md, lg, and xl.
Where property is one of:
m - for classes that set margin
p - for classes that set padding
Where sides is one of:
t - for classes that set margin-top or padding-top
b - for classes that set margin-bottom or padding-bottom
l - for classes that set margin-left or padding-left
r - for classes that set margin-right or padding-right
x - for classes that set both *-left and *-right
y - for classes that set both *-top and *-bottom
blank - for classes that set a margin or padding on all 4 sides of the element
Where size is one of:
0 - for classes that eliminate the margin or padding by setting it to 0
1 - (by default) for classes that set the margin or padding to $spacer * .25
2 - (by default) for classes that set the margin or padding to $spacer * .5
3 - (by default) for classes that set the margin or padding to $spacer
4 - (by default) for classes that set the margin or padding to $spacer * 1.5
5 - (by default) for classes that set the margin or padding to $spacer * 3
auto - for classes that set the margin to auto
For example:
.mt-0 {
margin-top: 0 !important;
}
.ml-1 {
margin-left: ($spacer * .25) !important;
}
.px-2 {
padding-left: ($spacer * .5) !important;
padding-right: ($spacer * .5) !important;
}
.p-3 {
padding: $spacer !important;
}
Reference: https://getbootstrap.com/docs/4.0/utilities/spacing/
It really does not make sense to shift both into the positive, if you want a growth value that is comparable with the normal growth as result of both positive numbers. If I want to see the growth of 2 positive numbers, I don't want the shifting.
It makes however sense to invert the growth for 2 negative numbers. -1 to -2 is mathematically a growth of 100%, but that feels as something positive, and in fact, the result is a decline.
So, I have following function, allowing to invert the growth for 2 negative numbers:
setGrowth(Quantity q1, Quantity q2, boolean fromPositiveBase) {
if (q1.getValue().equals(q2.getValue()))
setValue(0.0F);
else if (q1.getValue() <= 0 ^ q2.getValue() <= 0) // growth makes no sense
setNaN();
else if (q1.getValue() < 0 && q2.getValue() < 0) // both negative, option to invert
setValue((q2.getValue() - q1.getValue()) / ((fromPositiveBase? -1: 1) * q1.getValue()));
else // both positive
setValue((q2.getValue() - q1.getValue()) / q1.getValue());
}
In your controller, render the new
action from your create action if validation fails, with an instance variable, @car
populated from the user input (i.e., the params
hash). Then, in your view, add a logic check (either an if block around the form
or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params
values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car
is set.
swift 5 version:
By using default inbuilt color:
button.setTitleColor(UIColor.green, for: .normal)
OR
You can use your custom color by using RGB method:
button.setTitleColor(UIColor(displayP3Red: 0.0/255.0, green: 180.0/255.0, blue: 2.0/255.0, alpha: 1.0), for: .normal)
In order to set the color of highlighted item you need to set the color of cell.SelectionStyle
in iOS.
This example is to set the color of tapped item to transparent.
If you want you can change it with other colors from UITableViewCellSelectionStyle
. This is to be written in the platform project of iOS by creating a new Custom ListView renderer in your Forms project.
public class CustomListViewRenderer : ListViewRenderer
{
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (Control == null)
{
return;
}
if (e.PropertyName == "ItemsSource")
{
foreach (var cell in Control.VisibleCells)
{
cell.SelectionStyle = UITableViewCellSelectionStyle.None;
}
}
}
}
For android you can add this style in your values/styles.xml
<style name="ListViewStyle.Light" parent="android:style/Widget.ListView">
<item name="android:listSelector">@android:color/transparent</item>
<item name="android:cacheColorHint">@android:color/transparent</item>
</style>
All the answers so far don't address the trailing concern:
Is there an efficient method when there are hundreds of revisions after the one to be deleted?
The steps follow, but for reference, let's assume the following history:
[master] -> [hundreds-of-commits-including-merges] -> [C] -> [R] -> [B]
C: commit just following the commit to be removed (clean)
R: The commit to be removed
B: commit just preceding the commit to be removed (base)
Because of the "hundreds of revisions" constraint, I'm assuming the following pre-conditions:
This is a pretty restrictive set of constraints, but there is an interesting answer that actually works in this corner case.
Here are the steps:
git branch base B
git branch remove-me R
git branch save
git rebase --preserve-merges --onto base remove-me
If there are truly no conflicts, then this should proceed with no further interruptions. If there are conflicts, you can resolve them and rebase --continue
or decide to just live with the embarrassment and rebase --abort
.
Now you should be on master
that no longer has commit R in it. The save
branch points to where you were before, in case you want to reconcile.
How you want to arrange everyone else's transfer over to your new history is up to you. You will need to be acquainted with stash
, reset --hard
, and cherry-pick
. And you can delete the base
, remove-me
, and save
branches
Do NOT eval. use a real parser, i.e., from json.org
you should try with jquery validate plugin :
$('form').validate({
rules:{
email:{
required:true,
email:true
}
},
messages:{
email:{
required:"Email is required",
email:"Please type a valid email"
}
}
})
Martijen's answer makes sense, but it was missing something crucial that may seem obvious to others but was hard for me to figure out.
In the version where you use argparse, you need to have this line in the main body.
args = parser.parse_args(args)
Normally when you are using argparse just in a script you just write
args = parser.parse_args()
and parse_args find the arguments from the command line. But in this case the main function does not have access to the command line arguments, so you have to tell argparse what the arguments are.
Here is an example
import argparse
import sys
def x(x_center, y_center):
print "X center:", x_center
print "Y center:", y_center
def main(args):
parser = argparse.ArgumentParser(description="Do something.")
parser.add_argument("-x", "--xcenter", type=float, default= 2, required=False)
parser.add_argument("-y", "--ycenter", type=float, default= 4, required=False)
args = parser.parse_args(args)
x(args.xcenter, args.ycenter)
if __name__ == '__main__':
main(sys.argv[1:])
Assuming you named this mytest.py To run it you can either do any of these from the command line
python ./mytest.py -x 8
python ./mytest.py -x 8 -y 2
python ./mytest.py
which returns respectively
X center: 8.0
Y center: 4
or
X center: 8.0
Y center: 2.0
or
X center: 2
Y center: 4
Or if you want to run from another python script you can do
import mytest
mytest.main(["-x","7","-y","6"])
which returns
X center: 7.0
Y center: 6.0
Here is a good example on how to do a command if a file does or does not exist:
if exist C:\myprogram\sync\data.handler echo Now Exiting && Exit
if not exist C:\myprogram\html\data.sql Exit
We will take those three files and put it in a temporary place. After deleting the folder, it will restore those three files.
xcopy "test" "C:\temp"
xcopy "test2" "C:\temp"
del C:\myprogram\sync\
xcopy "C:\temp" "test"
xcopy "C:\temp" "test2"
del "c:\temp"
Use the XCOPY command:
xcopy "C:\myprogram\html\data.sql" /c /d /h /e /i /y "C:\myprogram\sync\"
I will explain what the /c /d /h /e /i /y
means:
/C Continues copying even if errors occur.
/D:m-d-y Copies files changed on or after the specified date.
If no date is given, copies only those files whose
source time is newer than the destination time.
/H Copies hidden and system files also.
/E Copies directories and subdirectories, including empty ones.
Same as /S /E. May be used to modify /T.
/T Creates directory structure, but does not copy files. Does not
include empty directories or subdirectories. /T /E includes
/I If destination does not exist and copying more than one file,
assumes that destination must be a directory.
/Y Suppresses prompting to confirm you want to overwrite an
existing destination file.
`To see all the commands type`xcopy /? in cmd
Call other batch file with option sync.bat myprogram.ini.
I am not sure what you mean by this, but if you just want to open both of these files you just put the path of the file like
Path/sync.bat
Path/myprogram.ini
If it was in the Bash environment it was easy for me, but I do not know how to test if a file or folder exists and if it is a file or folder.
You are using a batch file. You mentioned earlier you have to create a .bat file to use this:
I have to create a .BAT file that does this:
Below is the point to point difference about ViewData, ViewBag, TempData & Session. Credit/copied askforprogram.in , Follow the link for code example that i haven't mentioned here.
ViewData in MVC
ViewBag in MVC
TempData in MVC
Session in MVC
If you're displaying a user-readable file name, you do not want to use lastPathComponent
. Instead, pass the full path to NSFileManager's displayNameAtPath:
method. This basically does does the same thing, only it correctly localizes the file name and removes the extension based on the user's preferences.
Tuples are fixed size in nature whereas lists are dynamic.
In other words, a tuple
is immutable whereas a list
is mutable.
in
operator to check if an element exists in the tuple.Tuples are faster than lists. If you're defining a constant set of values and all you're ever going to do with it is iterate through it, use a tuple instead of a list.
It makes your code safer if you “write-protect” data that does not need to be changed. Using a tuple instead of a list is like having an implied assert statement that this data is constant, and that special thought (and a specific function) is required to override that.
Some tuples can be used as dictionary keys (specifically, tuples that contain immutable values like strings, numbers, and other tuples). Lists can never be used as dictionary keys, because lists are not immutable.
Source: Dive into Python 3
Actually, I do like mark instruction but little differently.
I've added C:\Program Files (x86)\GnuWin32\bin\
to the Path variable,
and try to run it with type awk using cmd.
Hope it works.
you can disable all selection
.disable-all{-webkit-touch-callout: none; -webkit-user-select: none;-khtml-user-select: none;-moz-user-select: none;-ms-user-select: none;user-select: none;}
now you can enable input and text-area enable
input, textarea{
-webkit-touch-callout:default;
-webkit-user-select:text;
-khtml-user-select: text;
-moz-user-select:text;
-ms-user-select:text;
user-select:text;}
You can use CSS to do the trick:
$("#yourElement").css({ top: '100px' });
While you haven't provided enough information to actually indicate WHERE you should be pulling data from, you do need to pull it from somewhere. You can specify the URL in load, as well as define data parameters or a callback function.
$("#getCameraSerialNumbers").click(function () {
$("#step1Content").load('YourUrl');
});
I would suggest using FileUtils from Apache Commons IO library.It will create the parent folders of the output file,if they don't exist.while Files.write(out,arrayList,Charset.defaultCharset());
will not do this,throwing exception if the parent directories don't exist.
FileUtils.writeLines(new File("output.txt"), encoding, list);
BLEUscore
BLEU, or the Bilingual Evaluation Understudy, is a score for comparing a candidate translation of text to one or more reference translations.
A perfect match results in a score of 1.0, whereas a perfect mismatch results in a score of 0.0.
Although developed for translation, it can be used to evaluate text generated for a suite of natural language processing tasks.
Code:
import nltk
from nltk.translate import bleu
from nltk.translate.bleu_score import SmoothingFunction
smoothie = SmoothingFunction().method4
C1='Text'
C2='Best'
print('BLEUscore:',bleu([C1], C2, smoothing_function=smoothie))
Examples: By updating C1 and C2.
C1='Test' C2='Test'
BLEUscore: 1.0
C1='Test' C2='Best'
BLEUscore: 0.2326589746035907
C1='Test' C2='Text'
BLEUscore: 0.2866227639866161
You can also compare sentence similarity:
C1='It is tough.' C2='It is rough.'
BLEUscore: 0.7348889200874658
C1='It is tough.' C2='It is tough.'
BLEUscore: 1.0
In 64 bit windows machines the COM components need to register itself in HKEY_CLASSES_ROOT\CLSID (64 bit component) OR HKEY_CLASSES_ROOT\Wow6432Node\CLSID (32 bit component) . If your application is a 32 bit application running on 64-bit machine the COM library would typically look for the GUID under Wow64 node and if your application is a 64 bit application, the COM library would try to load from HKEY_CLASSES_ROOT\CLSID. Make sure you are targeting the correct platform and ensure you have installed the correct version of library(32/64 bit).
No need for jQuery! This simple snippet works fine for me. It uses angular.element() to bind window resize event.
/**
* Window resize event handling
*/
angular.element($window).on('resize', function () {
console.log($window.innerWidth);
});
/**
* Window resize unbind event
*/
angular.element($window).off('resize');
Live @Sergey's solution but with integer division.
double value = 23.8764367843;
double rounded = (double) Math.round(value * 100) / 100;
System.out.println(value +" rounded is "+ rounded);
prints
23.8764367843 rounded is 23.88
EDIT: As Sergey points out, there should be no difference between multipling double*int and double*double and dividing double/int and double/double. I can't find an example where the result is different. However on x86/x64 and other systems there is a specific machine code instruction for mixed double,int values which I believe the JVM uses.
for (int j = 0; j < 11; j++) {
long start = System.nanoTime();
for (double i = 1; i < 1e6; i *= 1.0000001) {
double rounded = (double) Math.round(i * 100) / 100;
}
long time = System.nanoTime() - start;
System.out.printf("double,int operations %,d%n", time);
}
for (int j = 0; j < 11; j++) {
long start = System.nanoTime();
for (double i = 1; i < 1e6; i *= 1.0000001) {
double rounded = (double) Math.round(i * 100.0) / 100.0;
}
long time = System.nanoTime() - start;
System.out.printf("double,double operations %,d%n", time);
}
Prints
double,int operations 613,552,212
double,int operations 661,823,569
double,int operations 659,398,960
double,int operations 659,343,506
double,int operations 653,851,816
double,int operations 645,317,212
double,int operations 647,765,219
double,int operations 655,101,137
double,int operations 657,407,715
double,int operations 654,858,858
double,int operations 648,702,279
double,double operations 1,178,561,102
double,double operations 1,187,694,386
double,double operations 1,184,338,024
double,double operations 1,178,556,353
double,double operations 1,176,622,937
double,double operations 1,169,324,313
double,double operations 1,173,162,162
double,double operations 1,169,027,348
double,double operations 1,175,080,353
double,double operations 1,182,830,988
double,double operations 1,185,028,544
Use fmod()
from <cmath>
. If you do not want to include the C header file:
template<typename T, typename U>
constexpr double dmod (T x, U mod)
{
return !mod ? x : x - mod * static_cast<long long>(x / mod);
}
//Usage:
double z = dmod<double, unsigned int>(14.3, 4);
double z = dmod<long, float>(14, 4.6);
//This also works:
double z = dmod(14.7, 0.3);
double z = dmod(14.7, 0);
double z = dmod(0, 0.3f);
double z = dmod(myFirstVariable, someOtherVariable);
Mongo includes a mongoexport utility (see docs) which can dump a collection. This utility uses the native libmongoclient and is likely the fastest method.
mongoexport -d <database> -c <collection_name>
Also helpful:
-o
: write the output to file, otherwise standard output is used (docs)
--jsonArray
: generates a valid json document, instead of one json object per line (docs)
--pretty
: outputs formatted json (docs)
dblink executes a query (usually a SELECT, but it can be any SQL statement that returns rows) in a remote database.
When two text arguments are given, the first one is first looked up as a persistent connection's name; if found, the command is executed on that connection. If not found, the first argument is treated as a connection info string as for dblink_connect, and the indicated connection is made just for the duration of this command.
one of the good example:
SELECT *
FROM table1 tb1
LEFT JOIN (
SELECT *
FROM dblink('dbname=db2','SELECT id, code FROM table2')
AS tb2(id int, code text);
) AS tb2 ON tb2.column = tb1.column;
Note: I am giving this information for future reference. Refrence
If the function is a void, ending the function will return
. Otherwise, you need to do an explicit return someValue
. As Mark mentioned, you can also throw
an exception. What's the context of your question? Do you have a larger code sample with which to show you some ways to exit the function?
You can also use glob2 to recursively collect all paths (using ** subfolders wildcard) and then use shutil.copyfile, saving the paths
glob2 link: https://code.activestate.com/pypm/glob2/
override
is a C++11 keyword which means that a method is an "override" from a method from a base class. Consider this example:
class Foo
{
public:
virtual void func1();
}
class Bar : public Foo
{
public:
void func1() override;
}
If B::func1()
signature doesn't equal A::func1()
signature a compilation error will be generated because B::func1()
does not override A::func1()
, it will define a new method called func1()
instead.
There is a String.prototype.includes
in ES6:
"potato".includes("to");
> true
Note that this does not work in Internet Explorer or some other old browsers with no or incomplete ES6 support. To make it work in old browsers, you may wish to use a transpiler like Babel, a shim library like es6-shim, or this polyfill from MDN:
if (!String.prototype.includes) {
String.prototype.includes = function(search, start) {
'use strict';
if (typeof start !== 'number') {
start = 0;
}
if (start + search.length > this.length) {
return false;
} else {
return this.indexOf(search, start) !== -1;
}
};
}
There's no need to group in that subquery... a where clause would suffice:
SELECT * FROM tblpm n
WHERE date_updated=(SELECT MAX(date_updated)
FROM tblpm WHERE control_number=n.control_number)
Also, do you have an index on the 'date_updated' column? That would certainly help.
Within the dplyr world, try:
select(iris,contains("Sepal"))
See the Selection section in ?select
for numerous other helpers like starts_with
, ends_with
, etc.
Toggle the text Show
and Hide
and move your backgroundPosition
Y axis
$(function(){ // DOM READY shorthand
$(".slidingDiv").hide();
$('.show_hide').click(function( e ){
// e.preventDefault(); // If you use anchors
var SH = this.SH^=1; // "Simple toggler"
$(this).text(SH?'Hide':'Show')
.css({backgroundPosition:'0 '+ (SH?-18:0) +'px'})
.next(".slidingDiv").slideToggle();
});
});
CSS:
.show_hide{
background:url(plusminus.png) no-repeat;
padding-left:20px;
}
If you don't want to go with separate struct definition for nested struct and you don't like second method suggested by @OneOfOne you can use this third method:
package main
import "fmt"
type Configuration struct {
Val string
Proxy struct {
Address string
Port string
}
}
func main() {
c := &Configuration{
Val: "test",
}
c.Proxy.Address = `127.0.0.1`
c.Proxy.Port = `8080`
}
You can check it here: https://play.golang.org/p/WoSYCxzCF2
If you are using macOS sierra there is a update in PHP version. you need to have Entrust.net Certificate Authority (2048) file added to the PHP code. more info check accepted answer here Push Notification in PHP using PEM file
It seems to me you are using the wrong version...
TAP-Win32 should not be installed on the 64bit version. Download the right one and try again!
I also had the same issue, trying to run a unit test calling code that uses readEntity
. Can't use getEntity
in production code because that just returns a ByteInputStream
and not the content of the body and there is no way I am adding production code that is hit only in unit tests.
My solution was to create a response and then use a Mockito spy to mock out the readEntity
method:
Response error = Response.serverError().build();
Response mockResponse = spy(error);
doReturn("{jsonbody}").when(mockResponse).readEntity(String.class);
Note that you can't use the when(mockResponse.readEntity(String.class)
option because that throws the same IllegalStateException
.
Hope this helps!
Try this:
catch (Throwable t) {
logger.error("any message" + t);
StackTraceElement[] s = t.getStackTrace();
for(StackTraceElement e : s){
logger.error("\tat " + e);
}
}
This was the shortest way I could find to sort a DataTable without having to create any new variables.
DataTable.DefaultView.Sort = "ColumnName ASC"
DataTable = DataTable.DefaultView.ToTable
Where:
ASC - Ascending
DESC - Descending
ColumnName - The column you want to sort by
DataTable - The table you want to sort
Add the sheet name infront of the cell, e.g.:
=COUNTIFS(stock!A:A,"M",stock!C:C,"Yes")
Assumes the sheet name is "stock"
from datetime import datetime
from time import clock
t = datetime.utcnow()
print 't == %s %s\n\n' % (t,type(t))
n = 100000
te = clock()
for i in xrange(1):
t_stripped = t.strftime('%Y%m%d%H%M%S%f')
print clock()-te
print t_stripped," t.strftime('%Y%m%d%H%M%S%f')"
print
te = clock()
for i in xrange(1):
t_stripped = str(t).replace('-','').replace(':','').replace('.','').replace(' ','')
print clock()-te
print t_stripped," str(t).replace('-','').replace(':','').replace('.','').replace(' ','')"
print
te = clock()
for i in xrange(n):
t_stripped = str(t).translate(None,' -:.')
print clock()-te
print t_stripped," str(t).translate(None,' -:.')"
print
te = clock()
for i in xrange(n):
s = str(t)
t_stripped = s[:4] + s[5:7] + s[8:10] + s[11:13] + s[14:16] + s[17:19] + s[20:]
print clock()-te
print t_stripped," s[:4] + s[5:7] + s[8:10] + s[11:13] + s[14:16] + s[17:19] + s[20:] "
result
t == 2011-09-28 21:31:45.562000 <type 'datetime.datetime'>
3.33410112179
20110928212155046000 t.strftime('%Y%m%d%H%M%S%f')
1.17067364707
20110928212130453000 str(t).replace('-','').replace(':','').replace('.','').replace(' ','')
0.658806915404
20110928212130453000 str(t).translate(None,' -:.')
0.645189262881
20110928212130453000 s[:4] + s[5:7] + s[8:10] + s[11:13] + s[14:16] + s[17:19] + s[20:]
Use of translate() and slicing method run in same time
translate() presents the advantage to be usable in one line
Comparing the times on the basis of the first one:
1.000 * t.strftime('%Y%m%d%H%M%S%f')
0.351 * str(t).replace('-','').replace(':','').replace('.','').replace(' ','')
0.198 * str(t).translate(None,' -:.')
0.194 * s[:4] + s[5:7] + s[8:10] + s[11:13] + s[14:16] + s[17:19] + s[20:]
SELECT * FROM Table1
WHERE MAKE+MODEL+[Serial Number] not in
(select make+model+[serial number] from Table2
WHERE make+model+[serial number] IS NOT NULL)
That worked for me, where make+model+[serial number]
was one field name
$('#formID')[0].reset(); // Reset all form fields
Assuming you want to show an Image thumbnail which is 50x50 pixels and link to the the actual image you can do
<a href="path/to/image.jpg" alt="Image description" target="_blank" style="display: inline-block; width: 50px; height; 50px; background-image: url('path/to/image.jpg');"></a>
Of course it's best to give that link a class or id and put it in your css
For SVG RatingBar
I used RatingBar custom Vector Drawables superimposing and the answer of erdomester here. This solution traverses all drawables inside SvgRatingBar
view of your layout, so in RecyclerView
it has an overhead.
SvgRatingBar.java:
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ClipDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.VectorDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.graphics.drawable.shapes.Shape;
import android.os.Build;
import android.util.AttributeSet;
import android.view.Gravity;
import androidx.appcompat.graphics.drawable.DrawableWrapper;
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat;
import com.example.R; // Your R.java file for R.attr.ratingBarStyle.
public class SvgRatingBar extends androidx.appcompat.widget.AppCompatRatingBar {
private Bitmap sampleTile;
public SvgRatingBar(Context context) {
this(context, null);
}
public SvgRatingBar(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.ratingBarStyle);
}
public SvgRatingBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
LayerDrawable drawable = (LayerDrawable) createTile(getProgressDrawable(), false);
setProgressDrawable(drawable);
}
/**
* Converts a drawable to a tiled version of itself. It will recursively
* traverse layer and state list drawables.
*/
@SuppressLint("RestrictedApi")
private Drawable createTile(Drawable drawable, boolean clip) {
if (drawable instanceof DrawableWrapper) {
Drawable inner = ((DrawableWrapper) drawable).getWrappedDrawable();
if (inner != null) {
inner = createTile(inner, clip);
((DrawableWrapper) drawable).setWrappedDrawable(inner);
}
} else if (drawable instanceof LayerDrawable) {
LayerDrawable background = (LayerDrawable) drawable;
final int n = background.getNumberOfLayers();
Drawable[] outDrawables = new Drawable[n];
for (int i = 0; i < n; i++) {
int id = background.getId(i);
outDrawables[i] = createTile(background.getDrawable(i),
(id == android.R.id.progress || id == android.R.id.secondaryProgress));
}
LayerDrawable newBg = new LayerDrawable(outDrawables);
for (int i = 0; i < n; i++) {
newBg.setId(i, background.getId(i));
}
return newBg;
} else if (drawable instanceof BitmapDrawable) {
final BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
final Bitmap tileBitmap = bitmapDrawable.getBitmap();
if (sampleTile == null) {
sampleTile = tileBitmap;
}
final ShapeDrawable shapeDrawable = new ShapeDrawable(getDrawableShape());
final BitmapShader bitmapShader = new BitmapShader(tileBitmap,
Shader.TileMode.REPEAT, Shader.TileMode.CLAMP);
shapeDrawable.getPaint().setShader(bitmapShader);
shapeDrawable.getPaint().setColorFilter(bitmapDrawable.getPaint().getColorFilter());
return (clip) ? new ClipDrawable(shapeDrawable, Gravity.START,
ClipDrawable.HORIZONTAL) : shapeDrawable;
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && drawable instanceof VectorDrawable) {
return createTile(getBitmapDrawableFromVectorDrawable(drawable), clip);
} else if (drawable instanceof VectorDrawableCompat) {
// API 19 support.
return createTile(getBitmapDrawableFromVectorDrawable(drawable), clip);
}
return drawable;
}
private BitmapDrawable getBitmapDrawableFromVectorDrawable(Drawable drawable) {
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return new BitmapDrawable(getResources(), bitmap);
}
@Override
protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (sampleTile != null) {
final int width = sampleTile.getWidth() * getNumStars();
setMeasuredDimension(resolveSizeAndState(width, widthMeasureSpec, 0),
getMeasuredHeight());
}
}
private Shape getDrawableShape() {
final float[] roundedCorners = new float[]{5, 5, 5, 5, 5, 5, 5, 5};
return new RoundRectShape(roundedCorners, null, null);
}
}
In your layout:
<com.example.common.control.SvgRatingBar
android:id="@+id/rate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minHeight="13dp"
android:numStars="5"
android:progressDrawable="@drawable/rating_bar"
android:rating="3.5"
android:stepSize="0.01"
/>
You also have to create rating_bar.xml with two SVG drawables:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@android:id/background"
android:drawable="@drawable/ic_unfilled_star"
/>
<item
android:id="@android:id/secondaryProgress"
android:drawable="@drawable/ic_unfilled_star"
/>
<item
android:id="@android:id/progress"
android:drawable="@drawable/ic_filled_star"
/>
</layer-list>
If you see in Design/Split view only one star, refresh layout:
In Kotlin.
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapShader
import android.graphics.Canvas
import android.graphics.Shader
import android.graphics.drawable.*
import android.graphics.drawable.shapes.RoundRectShape
import android.os.Build
import android.util.AttributeSet
import android.view.Gravity
import androidx.appcompat.graphics.drawable.DrawableWrapper
import androidx.appcompat.widget.AppCompatRatingBar
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat
import com.example.R; // Your R.java file for R.attr.ratingBarStyle.
class SvgRatingBar @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null,
defStyleAttr: Int = R.attr.ratingBarStyle) :
AppCompatRatingBar(context, attrs, defStyleAttr) {
private var sampleTile: Bitmap? = null
private val roundedCorners = floatArrayOf(5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f)
private val roundRectShape = RoundRectShape(roundedCorners, null, null)
init {
progressDrawable = createTile(progressDrawable, false) as LayerDrawable
}
/**
* Converts a drawable to a tiled version of itself. It will recursively
* traverse layer and state list drawables.
*/
private fun createTile(drawable: Drawable, clip: Boolean): Drawable =
when {
drawable is DrawableWrapper -> {
@SuppressLint("RestrictedApi")
var inner = drawable.wrappedDrawable
if (inner != null) {
inner = createTile(inner, clip)
@SuppressLint("RestrictedApi")
drawable.wrappedDrawable = inner
}
drawable
}
drawable is LayerDrawable -> {
val n = drawable.numberOfLayers
val outDrawables = arrayOfNulls<Drawable>(n)
for (i in 0 until n) {
val id = drawable.getId(i)
outDrawables[i] = createTile(drawable.getDrawable(i),
id == android.R.id.progress || id == android.R.id.secondaryProgress)
}
val newBg = LayerDrawable(outDrawables)
for (i in 0 until n) {
newBg.setId(i, drawable.getId(i))
}
newBg
}
drawable is BitmapDrawable -> {
val tileBitmap = drawable.bitmap
if (sampleTile == null) {
sampleTile = tileBitmap
}
val bitmapShader = BitmapShader(tileBitmap, Shader.TileMode.REPEAT,
Shader.TileMode.CLAMP)
val shapeDrawable = ShapeDrawable(roundRectShape).apply {
paint.shader = bitmapShader
paint.colorFilter = drawable.paint.colorFilter
}
if (clip) ClipDrawable(shapeDrawable, Gravity.START, ClipDrawable.HORIZONTAL)
else shapeDrawable
}
Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && drawable is VectorDrawable -> {
createTile(getBitmapDrawableFromVectorDrawable(drawable), clip)
}
drawable is VectorDrawableCompat -> {
// Pre-Lollipop support.
createTile(getBitmapDrawableFromVectorDrawable(drawable), clip)
}
else -> drawable
}
private fun getBitmapDrawableFromVectorDrawable(drawable: Drawable): BitmapDrawable {
val bitmap = Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight,
Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
drawable.setBounds(0, 0, canvas.width, canvas.height)
drawable.draw(canvas)
return BitmapDrawable(resources, bitmap)
}
@Synchronized override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
if (sampleTile != null) {
val width = sampleTile!!.width * numStars
setMeasuredDimension(resolveSizeAndState(width, widthMeasureSpec, 0),
measuredHeight)
}
}
}
String text = "text";
text += new String(" ");
With pure javascript you can do the following:
var buttons = document.getElementsByTagName("button");
var buttonsCount = buttons.length;
for (var i = 0; i < buttonsCount; i += 1) {
buttons[i].onclick = function(e) {
alert(this.id);
};
}?
check it On JsFiddle
If you're using SSMS (or old school Enterprise Manager) to edit the table directly, press CTRL+0 to add a null.
I've found the following function and regex useful for word counts, especially in dealing with single vs. double hyphens, where the former generally should not count as a word break, eg, well-known, hi-fi; whereas double hyphen is a punctuation delimiter that is not bounded by white-space--such as for parenthetical remarks.
txt <- "Don't you think e-mail is one word--and not two!" #10 words
words <- function(txt) {
length(attributes(gregexpr("(\\w|\\w\\-\\w|\\w\\'\\w)+",txt)[[1]])$match.length)
}
words(txt) #10 words
Stringi is a useful package. But it over-counts words in this example due to hyphen.
stringi::stri_count_words(txt) #11 words
Try to rebase your local master branch onto your remote/origin master branch and resolve any conflicts in the process.
The docs give a pretty good explanation of the difference between apply()
and commit()
:
Unlike
commit()
, which writes its preferences out to persistent storage synchronously,apply()
commits its changes to the in-memorySharedPreferences
immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on thisSharedPreferences
does a regularcommit()
while aapply()
is still outstanding, thecommit()
will block until all async commits are completed as well as the commit itself. AsSharedPreferences
instances are singletons within a process, it's safe to replace any instance ofcommit()
withapply()
if you were already ignoring the return value.
For .NET 4.6.2 or lower, .NET Core 1.x, and .NET Standard 1.x you need to install the NuGet package System.ValueTuple
:
Install-Package "System.ValueTuple"
Or using a package reference in VS 2017:
<PackageReference Include="System.ValueTuple" Version="4.4.0" />
.NET Framework 4.7, .NET Core 2.0, and .NET Standard 2.0 include these types.
Actually pprint seems to sort the keys for you under python2.5
>>> from pprint import pprint
>>> mydict = {'a':1, 'b':2, 'c':3}
>>> pprint(mydict)
{'a': 1, 'b': 2, 'c': 3}
>>> mydict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
>>> pprint(mydict)
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
>>> d = dict(zip("kjihgfedcba",range(11)))
>>> pprint(d)
{'a': 10,
'b': 9,
'c': 8,
'd': 7,
'e': 6,
'f': 5,
'g': 4,
'h': 3,
'i': 2,
'j': 1,
'k': 0}
But not always under python 2.4
>>> from pprint import pprint
>>> mydict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
>>> pprint(mydict)
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}
>>> d = dict(zip("kjihgfedcba",range(11)))
>>> pprint(d)
{'a': 10,
'b': 9,
'c': 8,
'd': 7,
'e': 6,
'f': 5,
'g': 4,
'h': 3,
'i': 2,
'j': 1,
'k': 0}
>>>
Reading the source code of pprint.py (2.5) it does sort the dictionary using
items = object.items()
items.sort()
for multiline or this for single line
for k, v in sorted(object.items()):
before it attempts to print anything, so if your dictionary sorts properly like that then it should pprint properly. In 2.4 the second sorted() is missing (didn't exist then) so objects printed on a single line won't be sorted.
So the answer appears to be use python2.5, though this doesn't quite explain your output in the question.
Python3 Update
Pretty print by sorted keys (lambda x: x[0]):
for key, value in sorted(dict_example.items(), key=lambda x: x[0]):
print("{} : {}".format(key, value))
Pretty print by sorted values (lambda x: x[1]):
for key, value in sorted(dict_example.items(), key=lambda x: x[1]):
print("{} : {}".format(key, value))
As a basic example...
HTML:
<input type="text" name="Thing" value="" />
Script:
/* event listener */
document.getElementsByName("Thing")[0].addEventListener('change', doThing);
/* function */
function doThing(){
alert('Horray! Someone wrote "' + this.value + '"!');
}
Here's a fiddle: http://jsfiddle.net/Niffler/514gg4tk/
Here's a cross-browser less mixin for using CSS's calc
with any property:
.calc(@prop; @val) {
@{prop}: calc(~'@{val}');
@{prop}: -moz-calc(~'@{val}');
@{prop}: -webkit-calc(~'@{val}');
@{prop}: -o-calc(~'@{val}');
}
Example usage:
.calc(width; "100% - 200px");
And the CSS that's output:
width: calc(100% - 200px);
width: -moz-calc(100% - 200px);
width: -webkit-calc(100% - 200px);
width: -o-calc(100% - 200px);
A codepen of this example: http://codepen.io/patrickberkeley/pen/zobdp
I would use python-dpkt. Here is the documentation: http://www.commercialventvac.com/dpkt.html
This is all I know how to do though sorry.
#!/usr/local/bin/python2.7
import dpkt
counter=0
ipcounter=0
tcpcounter=0
udpcounter=0
filename='sampledata.pcap'
for ts, pkt in dpkt.pcap.Reader(open(filename,'r')):
counter+=1
eth=dpkt.ethernet.Ethernet(pkt)
if eth.type!=dpkt.ethernet.ETH_TYPE_IP:
continue
ip=eth.data
ipcounter+=1
if ip.p==dpkt.ip.IP_PROTO_TCP:
tcpcounter+=1
if ip.p==dpkt.ip.IP_PROTO_UDP:
udpcounter+=1
print "Total number of packets in the pcap file: ", counter
print "Total number of ip packets: ", ipcounter
print "Total number of tcp packets: ", tcpcounter
print "Total number of udp packets: ", udpcounter
Update:
Seems like it's quite a popular question, so I will try to make my humble contribution.
The code below is Swift 4 solution for no-storyboard setup. It utilizes some approaches from previous answers, therefore it prevents Auto Layout warning caused on device rotation.
I am sorry if code samples are a bit long. I want to provide an "easy-to-use" solution fully hosted by StackOverflow. If you have any suggestions to the post - please, share the idea and I will update it accordingly.
Two classes: ViewController.swift
and MultilineLabelCell.swift
- Cell containing single UILabel
.
MultilineLabelCell.swift
import UIKit
class MultilineLabelCell: UICollectionViewCell {
static let reuseId = "MultilineLabelCellReuseId"
private let label: UILabel = UILabel(frame: .zero)
override init(frame: CGRect) {
super.init(frame: frame)
layer.borderColor = UIColor.red.cgColor
layer.borderWidth = 1.0
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
let labelInset = UIEdgeInsets(top: 10, left: 10, bottom: -10, right: -10)
contentView.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
label.topAnchor.constraint(equalTo: contentView.layoutMarginsGuide.topAnchor, constant: labelInset.top).isActive = true
label.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor, constant: labelInset.left).isActive = true
label.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor, constant: labelInset.right).isActive = true
label.bottomAnchor.constraint(equalTo: contentView.layoutMarginsGuide.bottomAnchor, constant: labelInset.bottom).isActive = true
label.layer.borderColor = UIColor.black.cgColor
label.layer.borderWidth = 1.0
}
required init?(coder aDecoder: NSCoder) {
fatalError("Storyboards are quicker, easier, more seductive. Not stronger then Code.")
}
func configure(text: String?) {
label.text = text
}
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
label.preferredMaxLayoutWidth = layoutAttributes.size.width - contentView.layoutMargins.left - contentView.layoutMargins.left
layoutAttributes.bounds.size.height = systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
return layoutAttributes
}
}
ViewController.swift
import UIKit
let samuelQuotes = [
"Samuel says",
"Add different length strings here for better testing"
]
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
private(set) var collectionView: UICollectionView
// Initializers
init() {
// Create new `UICollectionView` and set `UICollectionViewFlowLayout` as its layout
collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
// Create new `UICollectionView` and set `UICollectionViewFlowLayout` as its layout
collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Dynamic size sample"
// Register Cells
collectionView.register(MultilineLabelCell.self, forCellWithReuseIdentifier: MultilineLabelCell.reuseId)
// Add `coolectionView` to display hierarchy and setup its appearance
view.addSubview(collectionView)
collectionView.backgroundColor = .white
collectionView.contentInsetAdjustmentBehavior = .always
collectionView.contentInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
// Setup Autolayout constraints
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
collectionView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true
collectionView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
collectionView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true
// Setup `dataSource` and `delegate`
collectionView.dataSource = self
collectionView.delegate = self
(collectionView.collectionViewLayout as! UICollectionViewFlowLayout).estimatedItemSize = UICollectionViewFlowLayout.automaticSize
(collectionView.collectionViewLayout as! UICollectionViewFlowLayout).sectionInsetReference = .fromLayoutMargins
}
// MARK: - UICollectionViewDataSource -
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MultilineLabelCell.reuseId, for: indexPath) as! MultilineLabelCell
cell.configure(text: samuelQuotes[indexPath.row])
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return samuelQuotes.count
}
// MARK: - UICollectionViewDelegateFlowLayout -
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let sectionInset = (collectionViewLayout as! UICollectionViewFlowLayout).sectionInset
let referenceHeight: CGFloat = 100 // Approximate height of your cell
let referenceWidth = collectionView.safeAreaLayoutGuide.layoutFrame.width
- sectionInset.left
- sectionInset.right
- collectionView.contentInset.left
- collectionView.contentInset.right
return CGSize(width: referenceWidth, height: referenceHeight)
}
}
To run this sample create new Xcode project, create corresponding files and replace AppDelegate
contents with the following code:
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var navigationController: UINavigationController?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
if let window = window {
let vc = ViewController()
navigationController = UINavigationController(rootViewController: vc)
window.rootViewController = navigationController
window.makeKeyAndVisible()
}
return true
}
}
"Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an .add() method."
Yes it is possible, and it does have a method that implements this, but you don't want to use it directly.
To demonstrate how and how not to use it, let's create an empty dict with the dict literal, {}
:
my_dict = {}
To update this dict with a single new key and value, you can use the subscript notation (see Mappings here) that provides for item assignment:
my_dict['new key'] = 'new value'
my_dict
is now:
{'new key': 'new value'}
update
method - 2 waysWe can also update the dict with multiple values efficiently as well using the update
method. We may be unnecessarily creating an extra dict
here, so we hope our dict
has already been created and came from or was used for another purpose:
my_dict.update({'key 2': 'value 2', 'key 3': 'value 3'})
my_dict
is now:
{'key 2': 'value 2', 'key 3': 'value 3', 'new key': 'new value'}
Another efficient way of doing this with the update method is with keyword arguments, but since they have to be legitimate python words, you can't have spaces or special symbols or start the name with a number, but many consider this a more readable way to create keys for a dict, and here we certainly avoid creating an extra unnecessary dict
:
my_dict.update(foo='bar', foo2='baz')
and my_dict
is now:
{'key 2': 'value 2', 'key 3': 'value 3', 'new key': 'new value',
'foo': 'bar', 'foo2': 'baz'}
So now we have covered three Pythonic ways of updating a dict
.
__setitem__
, and why it should be avoidedThere's another way of updating a dict
that you shouldn't use, which uses the __setitem__
method. Here's an example of how one might use the __setitem__
method to add a key-value pair to a dict
, and a demonstration of the poor performance of using it:
>>> d = {}
>>> d.__setitem__('foo', 'bar')
>>> d
{'foo': 'bar'}
>>> def f():
... d = {}
... for i in xrange(100):
... d['foo'] = i
...
>>> def g():
... d = {}
... for i in xrange(100):
... d.__setitem__('foo', i)
...
>>> import timeit
>>> number = 100
>>> min(timeit.repeat(f, number=number))
0.0020880699157714844
>>> min(timeit.repeat(g, number=number))
0.005071878433227539
So we see that using the subscript notation is actually much faster than using __setitem__
. Doing the Pythonic thing, that is, using the language in the way it was intended to be used, usually is both more readable and computationally efficient.
A div is a block element and by default 100% wide. You should just have to set the textarea width to 100%.
Hope this will work for you!
You can use library(qpcR)
for combining two matrix with unequal size.
resultant_matrix <- qpcR:::cbind.na(matrix1, matrix2)
NOTE:- The resultant matrix will be of size of matrix2.
jQuery UI has it's own elements, but jQuery alone hasn't.
Working example:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Dialog - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#dialog" ).dialog();
});
</script>
</head>
<body>
<div id="dialog" title="Basic dialog">
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>
</body>
</html>
I can't find a way to create a table with icons in SO, so I am uploading 2 images.
double d;
int rounded = (int)Math.Round(d);
Internet Explorer doesn't fully support Flexbox due to:
Partial support is due to large amount of bugs present (see known issues).
Screenshot and infos taken from caniuse.com
Internet Explorer before 10 doesn't support Flexbox, while IE 11 only supports the 2012 syntax.
display: flex
and flex-direction: column
will not properly calculate their flexed childrens' sizes if the container has min-height
but no explicit height
property. See bug.flex
is 0 0 auto
rather than 0 1 auto
as defined in the latest spec.min-height
is used. See bug.Flexbugs is a community-curated list of Flexbox issues and cross-browser workarounds for them. Here's a list of all the bugs with a workaround available and the browsers that affect.
align-items: center
overflow their containermin-height
on a flex container won't apply to its flex itemsflex
shorthand declarations with unitless flex-basis
values are ignoredflex
items don't always preserve intrinsic aspect ratiosflex-basis
doesn't account for box-sizing: border-box
flex-basis
doesn't support calc()
align-items: baseline
doesn't work with nested flex containersflex-flow: column wrap
do not contain their itemsmargin: auto
on the cross axisflex-basis
cannot be animatedmax-width
is usedTry this:
onclick="javascript:location.href='http://www.uol.com.br/'"
Worked fine for me in Firefox, Chrome and IE (wow!!)
I used an approach similar to the one taken by Josh Fraser, which determines the browser time offset from UTC and whether it recognizes DST or not (but somewhat simplified from his code):
var ClientTZ = {
UTCoffset: 0, // Browser time offset from UTC in minutes
UTCoffsetT: '+0000S', // Browser time offset from UTC in '±hhmmD' form
hasDST: false, // Browser time observes DST
// Determine browser's timezone and DST
getBrowserTZ: function () {
var self = ClientTZ;
// Determine UTC time offset
var now = new Date();
var date1 = new Date(now.getFullYear(), 1-1, 1, 0, 0, 0, 0); // Jan
var diff1 = -date1.getTimezoneOffset();
self.UTCoffset = diff1;
// Determine DST use
var date2 = new Date(now.getFullYear(), 6-1, 1, 0, 0, 0, 0); // Jun
var diff2 = -date2.getTimezoneOffset();
if (diff1 != diff2) {
self.hasDST = true;
if (diff1 - diff2 >= 0)
self.UTCoffset = diff2; // East of GMT
}
// Convert UTC offset to ±hhmmD form
diff2 = (diff1 < 0 ? -diff1 : diff1) / 60;
var hr = Math.floor(diff2);
var min = diff2 - hr;
diff2 = hr * 100 + min * 60;
self.UTCoffsetT = (diff1 < 0 ? '-' : '+') + (hr < 10 ? '0' : '') + diff2.toString() + (self.hasDST ? 'D' : 'S');
return self.UTCoffset;
}
};
// Onload
ClientTZ.getBrowserTZ();
Upon loading, the ClientTZ.getBrowserTZ()
function is executed, which sets:
ClientTZ.UTCoffset
to the browser time offset from UTC in minutes (e.g., CST is -360 minutes, which is -6.0 hours from UTC);ClientTZ.UTCoffsetT
to the offset in the form '±hhmmD'
(e.g., '-0600D'
), where the suffix is D
for DST and S
for standard (non-DST);ClientTZ.hasDST
(to true or false).The ClientTZ.UTCoffset
is provided in minutes instead of hours, because some timezones have fractional hourly offsets (e.g., +0415).
The intent behind ClientTZ.UTCoffsetT
is to use it as a key into a table of timezones (not provided here), such as for a drop-down <select>
list.
List is just an interface. The question is: is your actual List implementation serializable? Speaking about the standard List implementations (ArrayList, LinkedList) from the Java run-time, most of them actually are already.
One trick is to add a random number to the end of the URL. That way you don't have to rename the file every time. E.g.:
echo "<img src='temp.jpg?r=3892384947438'>"
The browser will not cache it as long as the random number is different, but the web server will ignore it.
scanf
needs to know the size of the data being pointed at by &d
to fill it properly, whereas variadic functions promote floats to doubles (not entirely sure why), so printf
is always getting a double
.
@user264892
I found that when using a String variable I needed to either prefix with an String of "" or explicitly cast to CharSequence.
So instead of:
String Status = "Asking Server...";
txtStatus.setText(Status);
try:
String Status = "Asking Server...";
txtStatus.setText((CharSequence) Status);
or:
String Status = "Asking Server...";
txtStatus.setText("" + Status);
or, since your string is not dynamic, even better:
txtStatus.setText("AskingServer...");
Found another solution for the same. It will be more helpful.
START C:\"Program Files (x86)"\Test\"Test Automation"\finger.exe ConfigFile="C:\Users\PCName\Desktop\Automation\Documents\Validation_ZoneWise_Default.finger.Config"
finger.exe is a parent program that is calling config solution. Note: if your path folder name consists of spaces, then do not forget to add "".
When you use git push origin :staleStuff
, it automatically removes origin/staleStuff
, so when you ran git remote prune origin
, you have pruned some branch that was removed by someone else. It's more likely that your co-workers now need to run git prune
to get rid of branches you have removed.
So what exactly git remote prune
does? Main idea: local branches (not tracking branches) are not touched by git remote prune
command and should be removed manually.
Now, a real-world example for better understanding:
You have a remote repository with 2 branches: master
and feature
. Let's assume that you are working on both branches, so as a result you have these references in your local repository (full reference names are given to avoid any confusion):
refs/heads/master
(short name master
)refs/heads/feature
(short name feature
)refs/remotes/origin/master
(short name origin/master
)refs/remotes/origin/feature
(short name origin/feature
)Now, a typical scenario:
feature
, merges it into master
and removes feature
branch from remote repository.git fetch
(or git pull
), no references are removed from your local repository, so you still have all those 4 references.git remote prune origin
.feature
branch no longer exists, so refs/remotes/origin/feature
is a stale branch which should be removed. refs/heads/feature
, because git remote prune
does not remove any refs/heads/*
references.It is possible to identify local branches, associated with remote tracking branches, by branch.<branch_name>.merge
configuration parameter. This parameter is not really required for anything to work (probably except git pull
), so it might be missing.
(updated with example & useful info from comments)
The main difference is that SurfaceView
can be drawn on by background theads but Views
can't.
SurfaceViews
use more resources though so you don't want to use them unless you have to.
I think you can change your query and try it like :
$res=User::where('id',$id)->delete();
None of the current solutions worked for me with git bash 2.26.2. This should work in any case if you are using the windows credential manager.
One issue is the windows credential manager runs for the logged user. In my case for example, I run git bash with right click, run as admin. Therefore, my stored credentials are in a credentials manager which I can't access with the windows GUI if I don't login to windows as admin.
To fix this:
cmdkey /list
. Your old credentials should appear here, with a part that reads ...target:xxx...cmdkey /delete:xxx
, where xxx is the target from the previous lineIt should confirm you that your credentials have been removed. Next time you do any operation in git bash that requires authentication, a popup will ask for your credentials.
You can either append a unique querystring (I believe this is what jQuery does with the cache: false option) to the request.
$http({
url: '...',
params: { 'foobar': new Date().getTime() }
})
A perhaps better solution is if you have access to the server, then you can make sure that necessary headers are set to prevent caching. If you're using ASP.NET MVC
this answer might help.
When you created the WebForm, did you select the Master page it is attached to in the "Add New Item" dialog itself ? Or did you attach it manually using the MasterPageFile
attribute of the @Page
directive ? If it was the latter, it might explain the error message you receive.
VS automatically inserts certain markup in each kind of page. If you select the MasterPage at the time of page creation itself, it does not generate any markup except the @Page
declaration and the top level Content control.
I went ahead and made a function for you:
Object.prototype.getValueByIndex = function (index) {
/*
Object.getOwnPropertyNames() takes in a parameter of the object,
and returns an array of all the properties.
In this case it would return: ["something","evenmore"].
So, this[Object.getOwnPropertyNames(this)[index]]; is really just the same thing as:
this[propertyName]
*/
return this[Object.getOwnPropertyNames(this)[index]];
};
let obj = {
'something' : 'awesome',
'evenmore' : 'crazy'
};
console.log(obj.getValueByIndex(0)); // Expected output: "awesome"
_x000D_
yes you can, just set the NODE_PATH env variable :
export NODE_PATH='yourdir'/node_modules
According to the doc :
If the NODE_PATH environment variable is set to a colon-delimited list of absolute paths, then node will search those paths for modules if they are not found elsewhere. (Note: On Windows, NODE_PATH is delimited by semicolons instead of colons.)
Additionally, node will search in the following locations:
1: $HOME/.node_modules
2: $HOME/.node_libraries
3: $PREFIX/lib/node
Where $HOME is the user's home directory, and $PREFIX is node's configured node_prefix.
These are mostly for historic reasons. You are highly encouraged to place your dependencies locally in node_modules folders. They will be loaded faster, and more reliably.
For 2D matrix:
mat.rows – Number of rows in a 2D array.
mat.cols – Number of columns in a 2D array.
Or: C++: Size Mat::size() const
The method returns a matrix size: Size(cols, rows) . When the matrix is more than 2-dimensional, the returned size is (-1, -1).
For multidimensional matrix, you need to use
int thisSizes[3] = {2, 3, 4};
cv::Mat mat3D(3, thisSizes, CV_32FC1);
// mat3D.size tells the size of the matrix
// mat3D.size[0] = 2;
// mat3D.size[1] = 3;
// mat3D.size[2] = 4;
Note, here 2 for z axis, 3 for y axis, 4 for x axis. By x, y, z, it means the order of the dimensions. x index changes the fastest.
No need to calculate the actual height of the contents; you can just scroll down a lot:
$(function () {
$('.messageScrollArea').scrollTop(1E10);
});
Apparently it's possible to do this in jQuery:
$("#tabs").css("cssText", "height: 650px !important;");
I use an immediately invoked lambda for these scenarios:
const config = (() => {
try {
return JSON.parse(fs.readFileSync('config.json'));
} catch (error) {
return {};
}
})();
async
version:
const config = await (async () => {
try {
return JSON.parse(await fs.readFileAsync('config.json'));
} catch (error) {
return {};
}
})();
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="jquery-3.1.0.js"></script>
<script>
$(function () {
$('#selectnumber').change(function(){
alert('.val() = ' + $('#selectnumber').val() + ' AND html() = ' + $('#selectnumber option:selected').html() + ' AND .text() = ' + $('#selectnumber option:selected').text());
})
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<select id="selectnumber">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</select>
</div>
</form>
</body>
</html>
Thanks...:)
The accepted answer works well for scripts that have not been symlinked elsewhere, such as into $PATH
.
#!/bin/bash
cd "$(dirname "$0")"
However if the script is run via a symlink,
ln -sv ~/project/script.sh ~/bin/;
~/bin/script.sh
This will cd into the ~/bin/
directory and not the ~/project/
directory, which will probably break your script if the purpose of the cd
is to include dependencies relative to ~/project/
The symlink safe answer is below:
#!/bin/bash
cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")"
readlink -f
is required to resolve the absolute path of the potentially symlinked file.
The quotes are required to support filepaths that could potentially contain whitespace (bad practice, but its not safe to assume this won't be the case)
If you have a text file with loads of packages you need to add the -r flag
pip install --upgrade --no-deps --force-reinstall -r requirements.txt
Create file ~/.config/autostart/MyScript.desktop with
[Desktop Entry]
Encoding=UTF-8
Name=MyScript
Comment=MyScript
Icon=gnome-info
Exec=python /home/your_path/script.py
Terminal=false
Type=Application
Categories=
X-GNOME-Autostart-enabled=true
X-GNOME-Autostart-Delay=0
It helps me!
Try using the SQL_NO_CACHE (MySQL 5.7) option in your query. (MySQL 5.6 users click HERE )
eg.
SELECT SQL_NO_CACHE * FROM TABLE
This will stop MySQL caching the results, however be aware that other OS and disk caches may also impact performance. These are harder to get around.
open(destination, 'wb').write(open(source, 'rb').read())
Open the source file in read mode, and write to destination file in write mode.
You can also delete the branch on the remote directly. Having done that, the next update will remove it from your working copy.
svn rm "^/reponame/branches/name_of_branch" -m "cleaning up old branch name_of_branch"
The ^
is short for the URL of the remote, as seen in 'svn info'. The double quotes are necessary on Windows command line, because ^
is a special character.
This command will also work if you have never checked out the branch.
How about mkString ?
theStrings.mkString(",")
A variant exists in which you can specify a prefix and suffix too.
See here for an implementation using foldLeft, which is much more verbose, but perhaps worth looking at for education's sake.
NewValue = (((OldValue - OldMin) * (NewMax - NewMin)) / (OldMax - OldMin)) + NewMin
Or a little more readable:
OldRange = (OldMax - OldMin)
NewRange = (NewMax - NewMin)
NewValue = (((OldValue - OldMin) * NewRange) / OldRange) + NewMin
Or if you want to protect for the case where the old range is 0 (OldMin = OldMax):
OldRange = (OldMax - OldMin)
if (OldRange == 0)
NewValue = NewMin
else
{
NewRange = (NewMax - NewMin)
NewValue = (((OldValue - OldMin) * NewRange) / OldRange) + NewMin
}
Note that in this case we're forced to pick one of the possible new range values arbitrarily. Depending on context, sensible choices could be: NewMin
(see sample), NewMax
or (NewMin + NewMax) / 2
As @Ofer said, when you are using another libraries or modules, you should import all of them inside the if __name__ == '__main__':
So, in my case, ended like this:
if __name__ == '__main__':
import librosa
import os
import pandas as pd
run_my_program()
I think it's a matter of preference. I personally use:
if($something){
$execute_something;
}
Why aren't you doing this:
[chr(x) for x in [66,53,0,94]]
It's called a list comprehension. You can find plenty of information on Google, but here's the link to the Python (2.6) documentation on list comprehensions. You might be more interested in the Python 3 documenation, though.
this solved it to me:
sudo apt-get update
sudo apt-get install libglfw3
sudo apt-get install libglfw3-dev
taken from https://github.com/glfw/glfw/issues/808
You've basically answered anything and everything already, so I'm no sure what the point is here?
FWIW I would use an httphandler - there seems no point in invoking a page lifecycle and having to deal with clipping off the bits of viewstate and session and what have you which don't make sense for an XML doc. It's like buying a car and stripping it for parts to make your motorbike.
And content-type is all important, it's how the requester knows what to do with the response.
I'm not sure what wget is, but to get a file from the web and store it locally, you can use NSData:
NSString *stringURL = @"http://www.somewhere.com/thefile.png";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"filename.png"];
[urlData writeToFile:filePath atomically:YES];
}
You can use select2 . it is the best js for this job.
https://select2.org/dropdown
$(document).ready(function () {_x000D_
//change selectboxes to selectize mode to be searchable_x000D_
$("select").select2();_x000D_
});
_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<select id="select_page" style="width:200px;" class="operator"> _x000D_
<option value="">Select a Page...</option>_x000D_
<option value="alpha">alpha</option> _x000D_
<option value="beta">beta</option>_x000D_
<option value="theta">theta</option>_x000D_
<option value="omega">omega</option>_x000D_
</select>_x000D_
</body>_x000D_
</html>
_x000D_
You could have the CSS first style the textbox, then have js change it:
<input type="text" style="background-color: yellow;" id="subEmail" />
js:
function changeColor() {
document.getElementById("subEmail").style.backgroundColor = "Insert color here"
}
For kotlin check out
val string = "<<<First Grade>>>"
println(string.drop(6)) // st Grade>>>
println(string.dropLast(6)) // <<<First Gr
println(string.dropWhile { !it.isLetter() }) // First Grade>>>
println(string.dropLastWhile { !it.isLetter() }) // <<<First Grade
Simple. On your code first, set the type of DateTime to DateTime?. So you can work with nullable DateTime type in database. Entity example:
public class Alarme
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public DateTime? DataDisparado { get; set; }//.This allow you to work with nullable datetime in database.
public DateTime? DataResolvido { get; set; }//.This allow you to work with nullable datetime in database.
public long Latencia { get; set; }
public bool Resolvido { get; set; }
public int SensorId { get; set; }
[ForeignKey("SensorId")]
public virtual Sensor Sensor { get; set; }
}
I don't know if how much this will help but I wanted to remove <b>
and </b>
from my string
so I used
mystring.replace('<b>',' ').replace('</b>','');
so basically if you want a limited number of character to be reduced and don't waste time this will be useful.
Firstly, BEGIN..END
are merely syntactic elements, and have nothing to do with transactions.
Secondly, in Oracle all individual DML statements are atomic (i.e. they either succeed in full, or rollback any intermediate changes on the first failure) (unless you use the EXCEPTIONS INTO option, which I won't go into here).
If you wish a group of statements to be treated as a single atomic transaction, you'd do something like this:
BEGIN
SAVEPOINT start_tran;
INSERT INTO .... ; -- first DML
UPDATE .... ; -- second DML
BEGIN ... END; -- some other work
UPDATE .... ; -- final DML
EXCEPTION
WHEN OTHERS THEN
ROLLBACK TO start_tran;
RAISE;
END;
That way, any exception will cause the statements in this block to be rolled back, but any statements that were run prior to this block will not be rolled back.
Note that I don't include a COMMIT - usually I prefer the calling process to issue the commit.
It is true that a BEGIN..END block with no exception handler will automatically handle this for you:
BEGIN
INSERT INTO .... ; -- first DML
UPDATE .... ; -- second DML
BEGIN ... END; -- some other work
UPDATE .... ; -- final DML
END;
If an exception is raised, all the inserts and updates will be rolled back; but as soon as you want to add an exception handler, it won't rollback. So I prefer the explicit method using savepoints.
For that to work there needs to be an executable named 'code' in your bash path, which some installers add for you, but this one apparently did not. The best way to do this could be to add a symlink to the visual studio code app in your /usr/local/bin
folder. You can do this by using a command like the following in your terminal.
ln -s "/Path/To/Visual Studio Code" "/usr/local/bin/code"
You will likely need to put sudo
in front of that to have the permissions for it to complete successfully.
That's not work on option
entry because it's a "system" generated drop-down menu but you can set the padding
of a select.
Just reset the box-sizing
property to content-box
in your CSS.
The default value of select
is border-box
.
select {
box-sizing: content-box;
padding: 5px 0;
}
Using VsVim for Visual Studio?
I came across this when experimenting with VsVim, which provides bindings for Vim commands in Visual Studio.
I know about Ctrlr in Vim itself, but this particular binding does not work in VsVim (at least not in my setup?).
What does work however, is the command :red
. This is a little bit more of a hassle than the above, but it is still fine when you really need it.
for (Bullet bullet : gunList.get(2).getBullet()) System.out.println(bullet);
Tested with PyCharm 4.0.6 (OSX 10.10.3) following this steps:
Problem solved!
You can add your own css property for button size as follows:
.btn {
min-width: 250px;
}
Just to complement the other answers as I don't think anyone mentioned this here: notifyDataSetChanged()
should be executed on the main thread (other notify<Something>
methods of RecyclerView.Adapter
as well, of course)
From what I gather, since you have the parsing procedures and the call to notifyDataSetChanged()
in the same block, either you're calling it from a worker thread, or you're doing JSON parsing on main thread (which is also a no-no as I'm sure you know). So the proper way would be:
protected void parseResponse(JSONArray response, String url) {
// insert dummy data for demo
// <yadda yadda yadda>
mBusinessAdapter = new BusinessAdapter(mBusinesses);
// or just use recyclerView.post() or [Fragment]getView().post()
// instead, but make sure views haven't been destroyed while you were
// parsing
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
mBusinessAdapter.notifyDataSetChanged();
}
});
}
PS Weird thing is, I don't think you get any indications about the main thread thing from either IDE or run-time logs. This is just from my personal observations: if I do call notifyDataSetChanged()
from a worker thread, I don't get the obligatory Only the original thread that created a view hierarchy can touch its views message or anything like that - it just fails silently (and in my case one off-main-thread call can even prevent succeeding main-thread calls from functioning properly, probably because of some kind of race condition)
Moreover, neither the RecyclerView.Adapter api reference nor the relevant official dev guide explicitly mention the main thread requirement at the moment (the moment is 2017) and none of the Android Studio lint inspection rules seem to concern this issue either.
But, here is an explanation of this by the author himself
Here is one possiblity for you if you are using Bootstrap 3
live view: http://fiddle.jshell.net/panchroma/vPH8N/10/show/
edit view: http://jsfiddle.net/panchroma/vPH8N/
I'm using the resposive table code from http://getbootstrap.com/css/#tables-responsive
ie:
<div class="table-responsive">
<table class="table">
...
</table>
</div>
Oskar Persson's answer is the best way to handle it because makes it easier to pass the data to the context and treat it normally from the template as we get the object instances (easily iterable to get props) instead of a plain value list.
After that you can just easily get the wanted prop:
for employee in employees:
print(employee.eng_name)
Or in the template:
{% for employee in employees %}
<p>{{ employee.eng_name }}</p>
{% endfor %}
calculate distance in Mysql
SELECT (6371 * acos(cos(radians(lat2)) * cos(radians(lat1) ) * cos(radians(long1) -radians(long2)) + sin(radians(lat2)) * sin(radians(lat1)))) AS distance
thus distance value will be calculated and anyone can apply as required.
You could use the string.join method in this case.
Split over a few of lines for clarity - here's an interactive session
>>> a = ['a','b','c']
>>> first = '", "'.join(a)
>>> second = '"%s"' % first
>>> print second
"a", "b", "c"
Or as a single line
>>> print ('"%s"') % '", "'.join(a)
"a", "b", "c"
However, you may have a problem is your strings have got embedded quotes. If this is the case you'll need to decide how to escape them.
The CSV module can take care of all of this for you, allowing you to choose between various quoting options (all fields, only fields with quotes and seperators, only non numeric fields, etc) and how to esacpe control charecters (double quotes, or escaped strings). If your values are simple, string.join will probably be OK but if you're having to manage lots of edge cases, use the module available.
Already tested by me, it works fine
For i =0 To ListBox2.items.count - 1
ListBox2.Items.removeAt(0)
Next
Dan Tello fix worked well for me.
One additional issue I found with IE8 was that if the PNG was held in a DIV with smaller CSS width or height dimensions than the PNG then the black edge prob was re-triggered.
Correcting the width and height CSS or removing them altogether fixed.
Follow below steps to do this or simply use apkToJava gem for this process, it even takes care of installing the required tools for it to work.
I think much confusion is generated by not communicating what is meant by passed by reference. When some people say pass by reference they usually mean not the argument itself, but rather the object being referenced. Some other say that pass by reference means that the object can't be changed in the callee. Example:
struct Object {
int i;
};
void sample(Object* o) { // 1
o->i++;
}
void sample(Object const& o) { // 2
// nothing useful here :)
}
void sample(Object & o) { // 3
o.i++;
}
void sample1(Object o) { // 4
o.i++;
}
int main() {
Object obj = { 10 };
Object const obj_c = { 10 };
sample(&obj); // calls 1
sample(obj) // calls 3
sample(obj_c); // calls 2
sample1(obj); // calls 4
}
Some people would claim that 1 and 3 are pass by reference, while 2 would be pass by value. Another group of people say all but the last is pass by reference, because the object itself is not copied.
I would like to draw a definition of that here what i claim to be pass by reference. A general overview over it can be found here: Difference between pass by reference and pass by value. The first and last are pass by value, and the middle two are pass by reference:
sample(&obj);
// yields a `Object*`. Passes a *pointer* to the object by value.
// The caller can change the pointer (the parameter), but that
// won't change the temporary pointer created on the call side (the argument).
sample(obj)
// passes the object by *reference*. It denotes the object itself. The callee
// has got a reference parameter.
sample(obj_c);
// also passes *by reference*. the reference parameter references the
// same object like the argument expression.
sample1(obj);
// pass by value. The parameter object denotes a different object than the
// one passed in.
I vote for the following definition:
An argument (1.3.1) is passed by reference if and only if the corresponding parameter of the function that's called has reference type and the reference parameter binds directly to the argument expression (8.5.3/4). In all other cases, we have to do with pass by value.
That means that the following is pass by value:
void f1(Object const& o);
f1(Object()); // 1
void f2(int const& i);
f2(42); // 2
void f3(Object o);
f3(Object()); // 3
Object o1; f3(o1); // 4
void f4(Object *o);
Object o1; f4(&o1); // 5
1
is pass by value, because it's not directly bound. The implementation may copy the temporary and then bind that temporary to the reference. 2
is pass by value, because the implementation initializes a temporary of the literal and then binds to the reference. 3
is pass by value, because the parameter has not reference type. 4
is pass by value for the same reason. 5
is pass by value because the parameter has not got reference type. The following cases are pass by reference (by the rules of 8.5.3/4 and others):
void f1(Object *& op);
Object a; Object *op1 = &a; f1(op1); // 1
void f2(Object const& op);
Object b; f2(b); // 2
struct A { };
struct B { operator A&() { static A a; return a; } };
void f3(A &);
B b; f3(b); // passes the static a by reference
Because strip()
only strips trailing and leading characters, based on what you provided. I suggest:
>>> import re
>>> name = "Barack (of Washington)"
>>> name = re.sub('[\(\)\{\}<>]', '', name)
>>> print(name)
Barack of Washington
I had the same problem... a JDK and plug-in version conflict.
I compiled using 1.8 ... the latest one, and that message started to appear. So I've searched for the JRE 7 (http://www.oracle.com/technetwork/java/javase/downloads/server-jre7-downloads-1931105.html)... and installed it... again... Now 1.8 and 1.7 in the same computer.
Using NetBeans, and compiling, and targeting to version 1.7, fixed my problem.
to set RichTextBox text:
richTextBox1.Document.Blocks.Clear();
richTextBox1.Document.Blocks.Add(new Paragraph(new Run("Text")));
to get RichTextBox text:
string richText = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text;
You can try:
int sum = startingNumber;
for (int i=0; i < positiveInteger; i++) {
sum += i;
}
cout << sum;
But much easier is to note that the sum 1+2+...+n = n*(n+1) / 2
, so you do not need a loop at all, just use the formula n*(n+1)/2
.
None of the highly upvoted answers worked for me. They threw various undefined errors and ended up calculating inf/nan for angles. I suspect perhaps the behavior of LatLngBounds has changed over time. In any case, I found this code to work for my needs, perhaps it can help someone:
function latRad(lat) {
var sin = Math.sin(lat * Math.PI / 180);
var radX2 = Math.log((1 + sin) / (1 - sin)) / 2;
return Math.max(Math.min(radX2, Math.PI), -Math.PI) / 2;
}
function getZoom(lat_a, lng_a, lat_b, lng_b) {
let latDif = Math.abs(latRad(lat_a) - latRad(lat_b))
let lngDif = Math.abs(lng_a - lng_b)
let latFrac = latDif / Math.PI
let lngFrac = lngDif / 360
let lngZoom = Math.log(1/latFrac) / Math.log(2)
let latZoom = Math.log(1/lngFrac) / Math.log(2)
return Math.min(lngZoom, latZoom)
}
Change your declarations to this:
double lateFee = 0.0;
double monthlyCharge = 0.0;
double annualRate = 0.0;
The error is caused because there is at least one path through your code where these variables end up not getting set to anything.
if(navigator.vendor.indexOf('Goog') > -1){
//Your code here
}
I think your only option is to wrap java in a script that substitutes the environment variables into the command line
I use HAVING for constraining a query based on the results of an aggregate function. E.G. select * in blahblahblah group by SOMETHING having count(SOMETHING)>0
You can specify a Python version for pip
to use:
pip3.4 install requests
Python 3.4 has pip support built-in, so you can also use:
python3.4 -m pip install
If you're running Ubuntu (or probably Debian as well), you'll need to install the system pip3
separately:
sudo apt-get install python3-pip
This will install the pip3
executable, so you can use it, as well as the earlier mentioned python3.4 -m pip
:
pip3 install requests
One practical difference is that browsers and webservers have a limit on the number of characters that can exist in a URL. It's different from application to application, but it's certainly possible to hit it if you've got textarea
s in your forms.
Another gotcha with GETs - they get indexed by search engines and other automatic systems. Google once had a product that would pre-fetch links on the page you were viewing, so they'd be faster to load if you clicked those links. It caused major havoc on sites that had links like delete.php?id=1
- people lost their entire sites.
int i = 0;
Console.WriteLine(i++); // Prints 0. Then value of "i" becomes 1.
Console.WriteLine(--i); // Value of "i" becomes 0. Then prints 0.
Does this answer your question ?
A list of HTTP Status Codes
The good-practice regarding status response is to, predictably, send the proper HTTP status code depending on the error (4xx for client errors, 5xx for server errors), regarding the actual JSON response there's no "bible" but a good idea could be to send (again) the status and data as 2 different properties of the root object in a successful response (this way you are giving the client the chance to capture the status from the HTTP headers and the payload itself) and a 3rd property explaining the error in a human-understandable way in the case of an error.
Stripe's API behaves similarly in the real world.
i.e.
OK
200, {status: 200, data: [...]}
Error
400, {status: 400, data: null, message: "You must send foo and bar to baz..."}
add display:block;
and it'll work. Images are inline by default
To clarify, the default width for a block
element is auto
, which of course fills the entire available width of the containing element.
By setting the margin to auto
, the browser assigns half the remaining space to margin-left
and the other half to margin-right
.
For me, none of the above did directly work for me. What I did is the following:
Additionally to @Rodrigo Villalba Zayas answer up there I added
implements InitializingBean
to the class
and implemented the method
@Override
public void afterPropertiesSet() {
String path = env.getProperty("userBucket.path");
}
So that will look like
import org.springframework.core.env.Environment;
public class xyz implements InitializingBean {
@Autowired
private Environment env;
private String path;
....
@Override
public void afterPropertiesSet() {
path = env.getProperty("userBucket.path");
}
public void method() {
System.out.println("Path: " + path);
}
}
Check if you have missed to call this method in your adapter
@Override
public int getItemCount() {
return list.size();
}
You missed break statements. Don't forget to use break
-statements even in the default
case.
switch (searchType)
{
case "SearchBooks":
Selenium.Type("//*[@id='SearchBooks_TextInput']", searchText);
Selenium.Click("//*[@id='SearchBooks_SearchBtn']");
break;
case "SearchAuthors":
Selenium.Type("//*[@id='SearchAuthors_TextInput']", searchText);
Selenium.Click("//*[@id='SearchAuthors_SearchBtn']");
break;
default:
Console.WriteLine("Default case handling");
break;
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Data;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
SqlConnection conn = new SqlConnection(@"Data Source=WKS09\SQLEXPRESS;Initial Catalog = StudentManagementSystem;Integrated Security=True");
SqlCommand insert = new SqlCommand("insert into dbo.StudentRegistration(ID, Name,Age,DateOfBirth,Email,Comment) values(@ID, @Name,@Age,@DateOfBirth,@mail,@comment)", conn);
insert.Parameters.AddWithValue("@ID", textBox1.Text);
insert.Parameters.AddWithValue("@Name", textBox2.Text);
insert.Parameters.AddWithValue("@Age", textBox3.Text);
insert.Parameters.AddWithValue("@DateOfBirth", textBox4.Text);
insert.Parameters.AddWithValue("@mail", textBox5.Text);
insert.Parameters.AddWithValue("@comment", textBox6.Text);
if (textBox1.Text == string.Empty)
{
MessageBox.Show("ID Cannot be Null");
return;
}
else if (textBox2.Text == string.Empty)
{
MessageBox.Show("Name Cannot be Null");
return;
}
try
{
conn.Open();
insert.ExecuteNonQuery();
MessageBox.Show("Register done !");
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex.Message);
conn.Close();
}
}
private void btnRetrive_Click(object sender, RoutedEventArgs e)
{
bool temp = false;
SqlConnection con = new SqlConnection("server=WKS09\\SQLEXPRESS;database=StudentManagementSystem;Trusted_Connection=True");
con.Open();
SqlCommand cmd = new SqlCommand("select * from dbo.StudentRegistration where ID = '" + textBox1.Text.Trim() + "'", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox2.Text = dr.GetString(1);
textBox3.Text = dr.GetInt32(2).ToString();
textBox4.Text = dr.GetDateTime(3).ToString();
textBox5.Text = dr.GetString(4);
textBox6.Text = dr.GetString(5);
temp = true;
}
if (temp == false)
MessageBox.Show("not found");
con.Close();
}
private void btnClear_Click(object sender, RoutedEventArgs e)
{
SqlConnection connection = new SqlConnection("Data Source=WKS09\\SQLEXPRESS;Initial Catalog = StudentManagementSystem;Integrated Security=True");
string sqlStatement = "DELETE FROM dbo.StudentRegistration WHERE ID = @ID";
try
{
connection.Open();
SqlCommand cmd = new SqlCommand(sqlStatement, connection);
cmd.Parameters.AddWithValue("@ID", textBox1.Text);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
MessageBox.Show("Done");
}
finally
{
Clear();
connection.Close();
}
}
public void Clear()
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
}
}
}
i did a test on a 64bit system with c# console, the exception is type of out of memory, using 2949 threads.
I realize we should be using threading pool, which I do, but this answer is in response to the main question ;)
For text files, you can use:
import requests
url = 'https://WEBSITE.com'
req = requests.get(url)
path = "C:\\YOUR\\FILE.html"
with open(path, 'wb') as f:
f.write(req.content)
Or just :
var a:Int = 3
var b:Int = 3
println(pow(Double(a),Double(b)))
Both Sweet and Slinky seem to be unmaintanted for about a year. Sweet Maven repo sweetsoftwaredesign.com is dead so there's even no way to download dependencies.
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}
So you can use:
myvar = getURLParameter('myvar');
Here is some help if you do the download through a server (this way you can name/convert/post-process/etc your file):
-Post data using toDataURL
-Set the headers
$filename = "test.jpg"; //or png
header('Content-Description: File Transfer');
if($msie = !strstr($_SERVER["HTTP_USER_AGENT"],"MSIE")==false)
header("Content-type: application/force-download");else
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Transfer-Encoding: binary");
header("Expires: 0"); header("Cache-Control: must-revalidate");
header("Pragma: public");
-create image
$data = $_POST['data'];
$img = imagecreatefromstring(base64_decode(substr($data,strpos($data,',')+1)));
-export image as JPEG
$width = imagesx($img);
$height = imagesy($img);
$output = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($output, 255, 255, 255);
imagefilledrectangle($output, 0, 0, $width, $height, $white);
imagecopy($output, $img, 0, 0, 0, 0, $width, $height);
imagejpeg($output);
exit();
imagesavealpha($img, true);
imagepng($img);
die($img);
Include the jQuery file first:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript" src="./javascript.js"></script>
<script
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCJnj2nWoM86eU8Bq2G4lSNz3udIkZT4YY&sensor=false">
</script>
I know this is an old question, but nobody mentioned that when your data looks like an array, numpy's loadtxt comes in handy:
>>> import numpy as np
>>> np.loadtxt("myfile.txt")[:, 1]
array([10., 20., 30., 40., 23., 13.])
This is not a bug in either implementation. There is no requirement to escape U+00B0. To quote the RFC:
2.5. Strings
The representation of strings is similar to conventions used in the C family of programming languages. A string begins and ends with quotation marks. All Unicode characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark, reverse solidus, and the control characters (U+0000 through U+001F).
Any character may be escaped.
Escaping everything inflates the size of the data (all code points can be represented in four or fewer bytes in all Unicode transformation formats; whereas encoding them all makes them six or twelve bytes).
It is more likely that you have a text transcoding bug somewhere in your code and escaping everything in the ASCII subset masks the problem. It is a requirement of the JSON spec that all data use a Unicode encoding.
Okay, it took me a while to see this, but there's no way this compiles:
return String.(ConfigurationManager.AppSettings[paramName]);
You're not even calling a method on the String
type. Just do this:
return ConfigurationManager.AppSettings[paramName];
The AppSettings
KeyValuePair already returns a string. If the name doesn't exist, it will return null
.
Based on your edit you have not yet added a Reference to the System.Configuration
assembly for the project you're working in.
On Android, network operations cannot be run on the main thread. You can use Thread
, AsyncTask
(short-running tasks), Service
(long-running tasks) to do network operations. android.os.NetworkOnMainThreadException
is thrown when an application attempts to perform a networking operation on its main thread. If your task took above five seconds, it takes a force close.
Run your code in AsyncTask
:
class FeedTask extends AsyncTask<String, Void, Boolean> {
protected RSSFeed doInBackground(String... urls) {
// TODO: Connect
}
protected void onPostExecute(RSSFeed feed) {
// TODO: Check this.exception
// TODO: Do something with the feed
}
}
OR
new Thread(new Runnable(){
@Override
public void run() {
try {
// Your implementation
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}).start();
This is not recommended. But for DEBUG purpose you can disable the strict mode as well using the following code:
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
You are asking Jackson to parse a StudentList
. Tell it to parse a List
(of students) instead. Since List
is generic you will typically use a TypeReference
List<Student> participantJsonList = mapper.readValue(jsonString, new TypeReference<List<Student>>(){});
In windows ,open Command Prompt and type MySQL -V
or MySQL --version
. If you use Linux get terminal and type MySQL -v