Postman will query Google API impersonating a Web Application
Generate an OAuth 2.0 token:
Create an OAuth 2.0 client ID
getpostman.com
to the Authorized domains. Click Save.https://www.getpostman.com/oauth2/callback
Client ID
and Client secret
fields for later useIn Postman select Authorization tab and select "OAuth 2.0" type. Click 'Get New Access Token'
https://www.getpostman.com/oauth2/callback
https://accounts.google.com/o/oauth2/auth
https://accounts.google.com/o/oauth2/token
Client ID
generated in the step 2 (e.g., '123456789012-abracadabra1234546789blablabla12.apps.googleusercontent.com')Client secret
generated in the step 2 (e.g., 'ABRACADABRAus1ZMGHvq9R-L')I have been researching this for a while, tested and wrote apps.
If you have no option in Settings ? Phone ? Use proximity sensor
, then the only choice, seem to be to disable or modify its settings in rooted devices.
Also consider, that if you plug the headset, the screen will remain on :D
As documented in ?legend
you do this like so:
plot(1:10,type = "n")
abline(v=seq(1,10,1), col='grey', lty='dotted')
legend(1, 5, "This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",box.lwd = 0,box.col = "white",bg = "white")
points(1:10,1:10)
Line breaks are achieved with the new line character \n
. Making the points still visible is done simply by changing the order of plotting. Remember that plotting in R is like drawing on a piece of paper: each thing you plot will be placed on top of whatever's currently there.
Note that the legend text is cut off because I made the plot dimensions smaller (windows.options does not exist on all R platforms).
You just need to transfer the first value to float, before it gets involved in further computations:
float z = x * 1.0 / y;
You could use logging libraries instead of re-inventing the wheel. Log4j for instance will provide methods for different messages like info()
, warn()
and error()
.
or simply make a println
method of your own and call it:
void println(Object line) {
System.out.println(line);
}
println("Hello World");
IntelliJ IDEA and NetBeans:
you type sout
then press TAB, and it types System.out.println()
for you, with the cursor in the right place.
Eclipse:
Type syso
then press CTRL + SPACE.
Other
Find a "snippets" plugin for your favorite text editor/IDE
import static java.lang.System.out;
out.println("Hello World");
println("Hello, World!")
println "Hello, World!"
print "Hello, World!"
puts "Hello, World!"
(println "Hello, World!")
print('Hello, World!');
It depends, how big is the data set and what are your performance requirements?
If it's nothing gigantic use the most readable form, which for myself is any, because it's shorter and readable rather than an equation.
I fixed it by changing the quotation mark (") with apostrophe (') inside Values. For instance:
insert into trucks ("id","datetime") VALUES (862,"10-09-2002 09:15:59");
Becomes this:
insert into trucks ("id","datetime") VALUES (862,'10-09-2002 09:15:59');
Assuming datetime
column is VarChar.
Inconsolata (http://www.levien.com/type/myfonts/inconsolata.html) is a great monospaced font for programming. Earlier versions tend to act weird on OS X, but the newer versions work out very well.
You update core-js with the following command:
npm install --save core-js@^3
If you read the React Docs you will find that the command is derived from when you need to upgrade React itself.
Jenkins 1.627, OS X 10.10.5
/Users/Shared/Jenkins/Home/jobs/{project_name}/config.xml
You can look in a saved figure it's size, like 1920x983 px (size when i saved a maximized window), then I set the dpi as 100 and the size as 19.20x9.83 and it worked fine. Saved exactly equal to the maximized figure.
import numpy as np
import matplotlib.pyplot as plt
x, y = np.genfromtxt('fname.dat', usecols=(0,1), unpack=True)
a = plt.figure(figsize=(19.20,9.83))
a = plt.plot(x, y, '-')
plt.savefig('file.png',format='png',dpi=100)
TableA LEFT OUTER JOIN TableB
is equivalent to TableB RIGHT OUTER JOIN Table A
.
In Oracle, (+)
denotes the "optional" table in the JOIN. So in your first query, it's a P LEFT OUTER JOIN S
. In your second query, it's S RIGHT OUTER JOIN P
. They're functionally equivalent.
In the terminology, RIGHT or LEFT specify which side of the join always has a record, and the other side might be null. So in a P LEFT OUTER JOIN S
, P
will always have a record because it's on the LEFT
, but S
could be null.
See this example from java2s.com for additional explanation.
To clarify, I guess I'm saying that terminology doesn't matter, as it's only there to help visualize. What matters is that you understand the concept of how it works.
I've seen some confusion about what matters in determining RIGHT vs LEFT in implicit join syntax.
LEFT OUTER JOIN
SELECT *
FROM A, B
WHERE A.column = B.column(+)
RIGHT OUTER JOIN
SELECT *
FROM A, B
WHERE B.column(+) = A.column
All I did is swap sides of the terms in the WHERE clause, but they're still functionally equivalent. (See higher up in my answer for more info about that.) The placement of the (+)
determines RIGHT or LEFT. (Specifically, if the (+)
is on the right, it's a LEFT JOIN. If (+)
is on the left, it's a RIGHT JOIN.)
The two styles of JOIN are implicit JOINs and explicit JOINs. They are different styles of writing JOINs, but they are functionally equivalent.
See this SO question.
Implicit JOINs simply list all tables together. The join conditions are specified in a WHERE clause.
Implicit JOIN
SELECT *
FROM A, B
WHERE A.column = B.column(+)
Explicit JOINs associate join conditions with a specific table's inclusion instead of in a WHERE clause.
Explicit JOIN
SELECT *
FROM A
LEFT OUTER JOIN B ON A.column = B.column
These Implicit JOINs can be more difficult to read and comprehend, and they also have a few limitations since the join conditions are mixed in other WHERE conditions. As such, implicit JOINs are generally recommended against in favor of explicit syntax.
How about NOT throwing exceptions and NOT using slow regex?
return str1 != null && str2 != null
&& typeof str1 === 'string' && typeof str2 === 'string'
&& str1.toUpperCase() === str2.toUpperCase();
The above snippet assumes you don't want to match if either string is null or undefined.
If you want to match null/undefined, then:
return (str1 == null && str2 == null)
|| (str1 != null && str2 != null
&& typeof str1 === 'string' && typeof str2 === 'string'
&& str1.toUpperCase() === str2.toUpperCase());
If for some reason you care about undefined vs null:
return (str1 === undefined && str2 === undefined)
|| (str1 === null && str2 === null)
|| (str1 != null && str2 != null
&& typeof str1 === 'string' && typeof str2 === 'string'
&& str1.toUpperCase() === str2.toUpperCase());
Not sure if this is a best practice with SSIS but sometimes I find their tools are a bit clunky when you want to do this type of activity.
Instead of using their components you can convert the data within your query
Instead of doing
SELECT myField = myNvarchar20Field
FROM myTable
You could do
SELECT myField = CONVERT(VARCHAR(20),myNvarchar20Field)
FROM myTable
Install Multiple Versions Of Xcode using the Xcode-Install Ruby Gem
You can do this whole process a lot easier if you use the
xcode-install RubyGem.
If you already have a working installation of the Xcode CommandLineTools and Ruby (I'd suggest using Homebrew for installing Ruby) but I think it works with the Ruby supplied by macOS as well if you install the Gem either using sudo or as a user install. (Details on the GitHub page) Basically:
$ gem install xcode-install
$ xcversion list
6.0.1
6.1
6.1.1
6.2 (installed)
6.3
$ xcversion install 8
######################################################################## 100.0%
Please authenticate for Xcode installation...
Xcode 8
Build version 6D570
To select a version as active, you'll run:
$ xcversion select 8
To select a version as active and change the symlink at /Applications/Xcode, you'll run:
$ xcversion select 8 --symlink
xcode-install can also manage your local simulators using the simulators command.
Read the instructions on the GitHub Project page for more info.
You could try this notattion:
SELECT * from table1,table2
More complicated one :
SELECT table1.field1,table1.field2, table2.field3,table2.field8 from table1,table2 where table1.field2 = something and table2.field3 = somethingelse
Use IPython display to render PIL images in a notebook.
from PIL import Image # to load images
from IPython.display import display # to display images
pil_im = Image.open('path/to/image.jpg')
display(pil_im)
You can't call _doPostBack()
because it forces submition of the form. Why don't you disable the PostBack
on the UpdatePanel
?
To solve, you need to import Private Certificate (PFX).
If you don't have PFX, use OpenSSL to generate it:
Open command line and run:
openssl pkcs12 -export -in public_certificate.cer -inkey server.key -out private_certificate.pfx
Than, install private_certificate.pfx (right click -> Install Certificate).
Now, your certificate does not disappear anymore and you can bind Website over SSL.
A great resource: https://blog.lextudio.com/the-whole-story-of-server-certificate-disappears-in-iis-7-7-5-8-8-5-10-0-after-installing-it-why-b66e802baa38
Using pure Eloquent, implement it like so. This code returns all logged in users whose accounts are active.
$users = \App\User::where('status', 'active')->where('logged_in', true)->get();
The short answer taken from the announcement of jQuery 3.0 Final Release :
Along with the regular version of jQuery that includes the ajax and effects modules, we’re releasing a “slim” version that excludes these modules. All in all, it excludes ajax, effects, and currently deprecated code.
The file size (gzipped) is about 6k smaller, 23.6k vs 30k.
Only call time pass-by-reference is removed. So change:
call_user_func($func, &$this, &$client ...
To this:
call_user_func($func, $this, $client ...
&$this
should never be needed after PHP4 anyway period.
If you absolutely need $client to be passed by reference, update the function ($func) signature instead (function func(&$client) {
)
Only the "Continue For" is an acceptable standard (the rest leads to "spaghetti code").
At least with "continue for" the programmer knows the code goes directly to the top of the loop.
For purists though, something like this is best since it is pure "non-spaghetti" code.
Dim bKeepGoing as Boolean
For Each I As Item In Items
bKeepGoing = True
If I = x Then
bKeepGoing = False
End If
if bKeepGoing then
' Do something
endif
Next
For ease of coding though, "Continue For" is OK. (Good idea to comment it though).
Using "Continue For"
For Each I As Item In Items
If I = x Then
Continue For 'skip back directly to top of loop
End If
' Do something
Next
Just click on form and go to JFrame properties, then Code tab and check Generate Center
.
It's a good practice to use a config file like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="MyConnString" connectionString="Data Source=(local);Initial Catalog=MyDB; Integrated Security=SSPI" ;Timeout=30"/>
</connectionStrings>
<appSettings>
<add key="BackupFolder" value="C:/temp/"/>
</appSettings>
</configuration>
Your C# code will be something like this:
// read connectionstring from config file
var connectionString = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString;
// read backup folder from config file ("C:/temp/")
var backupFolder = ConfigurationManager.AppSettings["BackupFolder"];
var sqlConStrBuilder = new SqlConnectionStringBuilder(connectionString);
// set backupfilename (you will get something like: "C:/temp/MyDatabase-2013-12-07.bak")
var backupFileName = String.Format("{0}{1}-{2}.bak",
backupFolder, sqlConStrBuilder.InitialCatalog,
DateTime.Now.ToString("yyyy-MM-dd"));
using (var connection = new SqlConnection(sqlConStrBuilder.ConnectionString))
{
var query = String.Format("BACKUP DATABASE {0} TO DISK='{1}'",
sqlConStrBuilder.InitialCatalog, backupFileName);
using (var command = new SqlCommand(query, connection))
{
connection.Open();
command.ExecuteNonQuery();
}
}
Would a View work better in this case?
CREATE VIEW vwTable
as
SELECT
col1
, col2
, col3
, col..
, col53
FROM table
Configuration Options:
$(document).ready(function () {
$("#companiesTable").dataTable({
"sPaginationType": "full_numbers",
"bJQueryUI": true,
"bAutoWidth": false, // Disable the auto width calculation
"aoColumns": [
{ "sWidth": "30%" }, // 1st column width
{ "sWidth": "30%" }, // 2nd column width
{ "sWidth": "40%" } // 3rd column width and so on
]
});
});
Specify the css for the table:
table.display {
margin: 0 auto;
width: 100%;
clear: both;
border-collapse: collapse;
table-layout: fixed; // add this
word-wrap:break-word; // add this
}
HTML:
<table id="companiesTable" class="display">
<thead>
<tr>
<th>Company name</th>
<th>Address</th>
<th>Town</th>
</tr>
</thead>
<tbody>
<% for(Company c: DataRepository.GetCompanies()){ %>
<tr>
<td><%=c.getName()%></td>
<td><%=c.getAddress()%></td>
<td><%=c.getTown()%></td>
</tr>
<% } %>
</tbody>
</table>
It works for me!
changing:
.ui-menu .ui-menu-item {
margin: 0;
padding: 0;
zoom: 1;
width: 100%;
}
to:
.ui-menu .ui-menu-item {
margin: 0;
padding: 0;
zoom: 1;
width: auto;
float:left;
}
should start you off.
A neater way of applying @Helzgate's reply is possibly to replace your 'for .. in' with
for (const field of Object.keys(this.formErrors)) {
You should remove navbar-fixed-top
class otherwise navbar stays fixed on top of page where you want logo.
If you want to place logo inside navbar:
Navbar height (set in @navbarHeight
LESS variable) is 40px
by default. Your logo has to fit inside or you have to make navbar higher first.
Then use brand
class:
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a href="/" class="brand"><img alt="" src="/logo.gif" /></a>
</div>
</div>
</div>
If your logo is higher than 20px
, you have to fix stylesheets as well.
If you do that in LESS:
.navbar .brand {
@elementHeight: 32px;
padding: ((@navbarHeight - @elementHeight) / 2 - 2) 20px ((@navbarHeight - @elementHeight) / 2 + 2);
}
@elementHeight
should be set to your image height.
Padding calculation is taken from Twitter Bootstrap LESS - https://github.com/twitter/bootstrap/blob/v2.0.4/less/navbar.less#L51-52
Alternatively you can calculate padding values yourself and use pure CSS.
This works for Twitter Bootstrap versions 2.0.x, should work in 2.1 as well, but padding calculation was changed a bit: https://github.com/twitter/bootstrap/blob/v2.1.0/less/navbar.less#L50
Currently, the NASDAQ web site publicly provides CSV files containing bulk listings -- it is broken up by first letter.
http://www.nasdaq.com/screening/companies-by-name.aspx?letter=A&render=download
Its simple. JDK bin directory or JRE bin directory should be in path variable Example : Java Installed directory: Assume your java installed in 'C:\Program Files\java\Jdk1.8.0_144' directory Now you can find bin directory in 'C:\Program Files\java\Jdk1.8.0_144\bin'
Navigate to user's environment variable
Control Panel --> User Accounts --> User Accounts --> Change my environment variables
In popup click Path under User variables for section Click Edit... button and another popup will appear
Click New button and enter C:\Program Files\java\Jdk1.8.0_144\bin
Click OK button and again OK button in Environment variables popup.
Now you can open your eclipse without error
Since the data is not free, you can use this Bloomberg API Emulator (disclaimer: it's my project) to learn how to send requests and make subscriptions. This emulator looks and acts just like the real Bloomberg API, although it doesn't return real data. In my time developing applications that use the Bloomberg API, I rarely care about the actual data that I'm handling; I care about how to retrieve data.
If you want to learn how to use the Bloomberg API give it a try. If you want to test out your code without an account, use this. A Bloomberg account costs about $2,000 a month, so you can save a lot with this project.
The emulator now supports Java and C++ in addition to C#.
C#, C++, and Java:
I just wanted to post this because this issue frustrated me for about 3 hours today. I have not tried any of the methods listed in the other answers, though they all seem reasonable. In fact, I was just about to try going through each of the above proposed solutions, but somehow I got this stroke of inspiration. Here is what worked for me to get me back working -- YMMV:
1) Find your .env file. 2) Rename your .env file to something else. Laravel 5 must be using this file as an override for settings somewhere else in the framework. I renamed mine to .env.old 3) You may need to restart your web server, but I did not have to.
Good luck!
Why not to try simple (but powerful) html()
method:
iElement.html('<svg width="600" height="100" class="svg"></svg>');
Or append
as an alternative:
iElement.append('<svg width="600" height="100" class="svg"></svg>');
And , of course , more cleaner way:
var svg = angular.element('<svg width="600" height="100" class="svg"></svg>');
iElement.append(svg);
' To remove items from string based on Dictionary key values. ' VB.net code
Dim stringArr As String() = "file1,file2,file3,file4,file5,file6".Split(","c)
Dim test As Dictionary(Of String, String) = New Dictionary(Of String, String)
test.Add("file3", "description")
test.Add("file5", "description")
stringArr = stringArr.Except(test.Keys).ToArray()
/* Assuming this is a while loop -> e.g. video stream where img is obtained from say web camera.*/
cvShowImage("Window",img);
/* A small interval of 10 milliseconds. This may be necessary to display the image correctly */
cvWaitKey(10);
/* to wait until user feeds keyboard input replace with cvWaitKey(0); */
You only need the async
pipe:
<li *ngFor="let afd of afdeling | async">
{{afd.patientid}}
</li>
always use the async
pipe when dealing with Observables directly without explicitly unsubscribe.
@Bean
MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
factory.setMaxFileSize("5120MB");
factory.setMaxRequestSize("5120MB");
return factory.createMultipartConfig();
}
put it in class where you are defining beans
Ideally, I'd have something like tail.getNewData() that I could call every time I wanted more data
We've already got one and itsa very nice. Just call f.read() whenever you want more data. It will start reading where the previous read left off and it will read through the end of the data stream:
f = open('somefile.log')
p = 0
while True:
f.seek(p)
latest_data = f.read()
p = f.tell()
if latest_data:
print latest_data
print str(p).center(10).center(80, '=')
For reading line-by-line, use f.readline(). Sometimes, the file being read will end with a partially read line. Handle that case with f.tell() finding the current file position and using f.seek() for moving the file pointer back to the beginning of the incomplete line. See this ActiveState recipe for working code.
imageView is a subview of the main view. It works this way
image.frame = CGRectMake(0 , 0, super.view.frame.width, super.view.frame.height * 0.2)
OnClick is triggered when the user releases the button. But if you still want to use the TouchListener you need to add it in code. It's just:
myView.setOnTouchListener(new View.OnTouchListener()
{
// Implementation;
});
Just use the ES6 find()
function in a functional way:
var data=[{name:"Afghanistan",code:"AF"},{name:"Åland Islands",code:"AX"},{name:"Albania",code:"AL"},{name:"Algeria",code:"DZ"}];
let country = data.find(el => el.code === "AL");
// => {name: "Albania", code: "AL"}
console.log(country["name"]);
_x000D_
or Lodash _.find:
var data=[{name:"Afghanistan",code:"AF"},{name:"Åland Islands",code:"AX"},{name:"Albania",code:"AL"},{name:"Algeria",code:"DZ"}];
let country = _.find(data, ["code", "AL"]);
// => {name: "Albania", code: "AL"}
console.log(country["name"]);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
_x000D_
If you're still having issues with the simple approach, creating an empty bucket then Redirect all requests to another host name
under Static web hosting in properties via the console. Ensure that you have set 2 A records in route53, one for final-destination.com
and one for redirect-to.final-destination.com
. The settings for each of these will be identical, but the name will be different so it matches the names that you set for your buckets / URLs.
The difference is in the subsystem that each executable targets.
java.exe
targets the CONSOLE
subsystem.javaw.exe
targets the WINDOWS
subsystem.Another variation you could also use
MyType[] Temp = new MyType[myDico.Count];
myDico.Values.CopyTo(Temp, 0);
List<MyType> items = Temp.ToList();
As an alternative, you could add it as a script parameter for input as part of script execution
param(
[Parameter(Mandatory = $True,valueFromPipeline=$true)][String] $value1,
[Parameter(Mandatory = $True,valueFromPipeline=$true)][String] $value2
)
I understand the accepted answer, and have up-voted it but thought I'd dump my laymen's answer here...
Creating a hash
Checking a password against a hash
To check a password that a user inputs.
The Hash
Under the covers the hash is generated using the SHA1 hash function (https://en.wikipedia.org/wiki/SHA-1). This function is iteratively called 1000 times (In the default Identity implementation)
Why is this secure
Put this in your code (preferably in a general js functions library):
String.prototype.nl2br = function()
{
return this.replace(/\n/g, "<br />");
}
Usage:
var myString = "test\ntest2";
myString.nl2br();
creating a string prototype function allows you to use this on any string.
mime-types starting with x-
are not standardized. In case of javascript it's kind of outdated.
Additional the second code snippet
<?Header('Content-Type: text/javascript');?>
requires short_open_tags
to be enabled. you should avoid it.
<?php Header('Content-Type: text/javascript');?>
However, the completely correct mime-type for javascript is
application/javascript
http://www.iana.org/assignments/media-types/application/index.html
You could extend the String object with your own function that does what you need (useful if there's ever missing functionality):
String.prototype.replaceArray = function(find, replace) {
var replaceString = this;
for (var i = 0; i < find.length; i++) {
replaceString = replaceString.replace(find[i], replace[i]);
}
return replaceString;
};
For global replace you could use regex:
String.prototype.replaceArray = function(find, replace) {
var replaceString = this;
var regex;
for (var i = 0; i < find.length; i++) {
regex = new RegExp(find[i], "g");
replaceString = replaceString.replace(regex, replace[i]);
}
return replaceString;
};
To use the function it'd be similar to your PHP example:
var textarea = $(this).val();
var find = ["<", ">", "\n"];
var replace = ["<", ">", "<br/>"];
textarea = textarea.replaceArray(find, replace);
GPS, the Global Positioning System run by the United States Military, is free for civilian use, though the reality is that we're paying for it with tax dollars.
However, GPS on cell phones is a bit more murky. In general, it won't cost you anything to turn on the GPS in your cell phone, but when you get a location it usually involves the cell phone company in order to get it quickly with little signal, as well as get a location when the satellites aren't visible (since the gov't requires a fix even if the satellites aren't visible for emergency 911 purposes). It uses up some cellular bandwidth. This also means that for phones without a regular GPS receiver, you cannot use the GPS at all if you don't have cell phone service.
For this reason most cell phone companies have the GPS in the phone turned off except for emergency calls and for services they sell you (such as directions).
This particular kind of GPS is called assisted GPS (AGPS), and there are several levels of assistance used.
A normal GPS receiver listens to a particular frequency for radio signals. Satellites send time coded messages at this frequency. Each satellite has an atomic clock, and sends the current exact time as well.
The GPS receiver figures out which satellites it can hear, and then starts gathering those messages. The messages include time, current satellite positions, and a few other bits of information. The message stream is slow - this is to save power, and also because all the satellites transmit on the same frequency and they're easier to pick out if they go slow. Because of this, and the amount of information needed to operate well, it can take 30-60 seconds to get a location on a regular GPS.
When it knows the position and time code of at least 3 satellites, a GPS receiver can assume it's on the earth's surface and get a good reading. 4 satellites are needed if you aren't on the ground and you want altitude as well.
As you saw above, it can take a long time to get a position fix with a normal GPS. There are ways to speed this up, but unless you're carrying an atomic clock with you all the time, or leave the GPS on all the time, then there's always going to be a delay of between 5-60 seconds before you get a location.
In order to save cost, most cell phones share the GPS receiver components with the cellular components, and you can't get a fix and talk at the same time. People don't like that (especially when there's an emergency) so the lowest form of GPS does the following:
This saves a lot of money on the phone design, but it has a heavy load on cellular bandwidth, and with a lot of requests coming it requires a lot of fast servers. Still, overall it can be cheaper and faster to implement. They are reluctant, however, to release GPS based features on these phones due to this load - so you won't see turn by turn navigation here.
More recent designs include a full GPS chip. They still get data from the phone company - such as current location based on tower positioning, and current satellite locations - this provides sub 1 second fix times. This information is only needed once, and the GPS can keep track of everything after that with very little power. If the cellular network is unavailable, then they can still get a fix after awhile. If the GPS satellites aren't visible to the receiver, then they can still get a rough fix from the cellular towers.
But to completely answer your question - it's as free as the phone company lets it be, and so far they do not charge for it at all. I doubt that's going to change in the future. In the higher end phones with a full GPS receiver you may even be able to load your own software and access it, such as with mologogo on a motorola iDen phone - the J2ME development kit is free, and the phone is only $40 (prepaid phone with $5 credit). Unlimited internet is about $10 a month, so for $40 to start and $10 a month you can get an internet tracking system. (Prices circa August 2008)
It's only going to get cheaper and more full featured from here on out...
Re: Google maps and such
Yes, Google maps and all other cell phone mapping systems require a data connection of some sort at varying times during usage. When you move far enough in one direction, for instance, it'll request new tiles from its server. Your average phone doesn't have enough storage to hold a map of the US, nor the processor power to render it nicely. iPhone would be able to if you wanted to use the storage space up with maps, but given that most iPhones have a full time unlimited data plan most users would rather use that space for other things.
Can you provide an example, because put should work fine as well?
Documentation -
The type of request to make ("POST" or "GET"); the default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.
Have the example in fiddle and the form parameters are passed fine (as it is put it will not be appended to url
) -
$.ajax({
url: '/echo/html/',
type: 'PUT',
data: "name=John&location=Boston",
success: function(data) {
alert('Load was performed.');
}
});
Demo tested from jQuery 1.3.2 onwards on Chrome.
WebClient to fetch the contents from the remote url and JavaScriptSerializer or Json.NET to deserialize the JSON into a .NET object. For example you define a model class which will reflect the JSON structure and then:
using (var client = new WebClient())
{
var json = client.DownloadString("http://example.com/json");
var serializer = new JavaScriptSerializer();
SomeModel model = serializer.Deserialize<SomeModel>(json);
// TODO: do something with the model
}
There are also some REST client frameworks you may checkout such as RestSharp.
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {
if (INSTANCE != null)
throw new IllegalStateException(“Already instantiated...”);
}
public synchronized static Singleton getInstance() {
return INSTANCE;
}
}
As we have added the Synchronized keyword before getInstance, we have avoided the race condition in the case when two threads call the getInstance at the same time.
This maybe help somebody who is looking for the way to sort table by two columns, but in paralel way. This means to combine two sorts using aggregate sorting function. It's very useful when for example retrieving articles using fulltext search and also concerning the article publish date.
This is only example, but if you catch the idea you can find a lot of aggregate functions to use. You can even weight the columns to prefer one over second. The function of mine takes extremes from both sorts, thus the most valued rows are on the top.
Sorry if there exists simplier solutions to do this job, but I haven't found any.
SELECT
`id`,
`text`,
`date`
FROM
(
SELECT
k.`id`,
k.`text`,
k.`date`,
k.`match_order_id`,
@row := @row + 1 as `date_order_id`
FROM
(
SELECT
t.`id`,
t.`text`,
t.`date`,
@row := @row + 1 as `match_order_id`
FROM
(
SELECT
`art_id` AS `id`,
`text` AS `text`,
`date` AS `date`,
MATCH (`text`) AGAINST (:string) AS `match`
FROM int_art_fulltext
WHERE MATCH (`text`) AGAINST (:string IN BOOLEAN MODE)
LIMIT 0,101
) t,
(
SELECT @row := 0
) r
ORDER BY `match` DESC
) k,
(
SELECT @row := 0
) l
ORDER BY k.`date` DESC
) s
ORDER BY (1/`match_order_id`+1/`date_order_id`) DESC
Assuming your dataframe is mydf:
mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))
Setting the icon
property when creating the BrowserWindow
only has an effect on Windows and Linux.
To set the icon on OS X, you can use electron-packager and set the icon using the --icon
switch.
It will need to be in .icns format for OS X. There is an online icon converter which can create this file from your .png.
Addition to @BalusC 's answer. You also need to set width of headers. In my case, below css can only apply to my table's column width.
.myTable td:nth-child(1),.myTable th:nth-child(1) {
width: 20px;
}
In jsp you can do it like this:
<%
boolean checkboxDisabled = true; //do your logic here
String checkboxState = checkboxDisabled ? "disabled" : "";
%>
<input type="checkbox" <%=checkboxState%>>
Without moment.js:
var time_to_show = 1509968436; // unix timestamp in seconds_x000D_
_x000D_
var t = new Date(time_to_show * 1000);_x000D_
var formatted = ('0' + t.getHours()).slice(-2) + ':' + ('0' + t.getMinutes()).slice(-2);_x000D_
_x000D_
document.write(formatted);
_x000D_
A way to do this programmatically would be to create a UIView
over the top part of the UIView
that has the rounded corners. Or you could hide the top underneath something.
If you define classproperty
as follows, then your example works exactly as you requested.
class classproperty(object):
def __init__(self, f):
self.f = f
def __get__(self, obj, owner):
return self.f(owner)
The caveat is that you can't use this for writable properties. While e.I = 20
will raise an AttributeError
, Example.I = 20
will overwrite the property object itself.
You could just create a new database and then go to tasks, import data, and import all the data from the database you want to duplicate to the database you just created.
If you're interested in learning a language which supports massive parallelism better go for OpenCL since you don't have an NVIDIA GPU. You can run OpenCL on Intel CPUs, but at best you can learn to program SIMDs. Optimization on CPU and GPU are different. I really don't think you can use Intel card for GPGPU.
Change display:inline to display:inline-block
.test {
width:200px;
display:inline-block;
overflow: auto;
white-space: nowrap;
margin:0px auto;
border:1px red solid;
}
I don't think it is possible, because function definitions do not match in your example.
Your lambda expression is evaluated exactly as
void action() { }
whereas your declaration looks like
Void action(Void v) {
//must return Void type.
}
as an example, if you have following interface
public interface VoidInterface {
public Void action(Void v);
}
the only kind of function (while instantiating) that will be compatibile looks like
new VoidInterface() {
public Void action(Void v) {
//do something
return v;
}
}
and either lack of return statement or argument will give you a compiler error.
Therefore, if you declare a function which takes an argument and returns one, I think it is impossible to convert it to function which does neither of mentioned above.
In this three class Bootstrap invalid class
.text-right {
text-align: right; }
.text-center {
text-align: center; }
.text-left {
text-align: left; }
This is how sed
and mv
can be used together to do rename:
for f in fgh*; do mv "$f" $(echo "$f" | sed 's/^fgh/jkl/g'); done
As per comment below, if the file names have spaces in them, quotes may need to surround the sub-function that returns the name to move the files to:
for f in fgh*; do mv "$f" "$(echo $f | sed 's/^fgh/jkl/g')"; done
It's possible that your configuration variables are cached. Verify your config/app.php
as well as your .env
file then try
php artisan cache:clear
on the command line.
Multiple questions require input for several integers on single line. The best way is to input the whole string of numbers one one line and then split them to integers. Here is a Python 3 version:
a = []
p = input()
p = p.split()
for i in p:
a.append(int(i))
Also a list comprehension can be used
p = input().split("whatever the seperator is")
And to convert all the inputs from string to int we do the following
x = [int(i) for i in p]
print(x, end=' ')
shall print the list elements in a straight line.
Instead of using a temporary file, you can avoid creating a subshell around the while
loop by using process substitution.
while ...
do
...
done < <(grep ...)
By the way, you should be able to transform all that grep, grep, awk, awk, awk
into a single awk
.
Starting with Bash 4.2, there is a lastpipe
option that
runs the last command of a pipeline in the current shell context. The lastpipe option has no effect if job control is enabled.
bash -c 'echo foo | while read -r s; do c=3; done; echo "$c"'
bash -c 'shopt -s lastpipe; echo foo | while read -r s; do c=3; done; echo "$c"'
3
The first example changes the interface for that object only. The second example changes the interface for all object of that class.
The dataset:
dat <- read.table(text = "A B C D E F G
1 480 780 431 295 670 360 190
2 720 350 377 255 340 615 345
3 460 480 179 560 60 735 1260
4 220 240 876 789 820 100 75", header = TRUE)
Now you can convert the data frame into a matrix and use the barplot
function.
barplot(as.matrix(dat))
diff
and then grep
for the edit type you want.
diff -u A1 A2 | grep -E "^\+"
Maybe this table helps.
Calling the callme()
method of class Parent
or class Child
.
As a principle:
UPCASTING --> Hiding
DOWNCASTING --> Revealing
DO LIKE THIS
<LinearLayout
android:id="@+id/LinearLayouts02"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="bottom|end">
<TextView
android:id="@+id/texts1"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_weight="2"
android:text="@string/forgotpass"
android:padding="7dp"
android:gravity="bottom|center_horizontal"
android:paddingLeft="10dp"
android:layout_marginBottom="30dp"
android:bottomLeftRadius="10dp"
android:bottomRightRadius="50dp"
android:fontFamily="sans-serif-condensed"
android:textColor="@color/colorAccent"
android:textStyle="bold"
android:textSize="16sp"
android:topLeftRadius="10dp"
android:topRightRadius="10dp"
/>
</LinearLayout>
To get the format you want:
SELECT (substring(CONVERT(VARCHAR,GETDATE(),22),10,8) + ' ' +
SUBSTRING(CONVERT(VARCHAR,getdate(),22), 19,2))
Why are you pulling this from sql?
I figured it out. It's:
DBCC CHECKIDENT ('tablename', RESEED, newseed)
radioButton.isChecked()
function returns true if the Radion button is chosen, false otherwise.
A 'button' is just that, a button, to which you can add additional functionality using Javascript. A 'submit' input type has the default functionality of submitting the form it's placed in (though, of course, you can still add additional functionality using Javascript).
Another way, for completeness:
>>> chr(random.randrange(97, 97 + 26))
Use the fact that ascii
'a' is 97, and there are 26 letters in the alphabet.
When determining the upper and lower bound of the random.randrange()
function call, remember that random.randrange()
is exclusive on its upper bound, meaning it will only ever generate an integer up to 1 unit less that the provided value.
In your component's template you can use multiple arguments by separating them with colons:
{{ myData | myPipe: 'arg1':'arg2':'arg3'... }}
From your code it will look like this:
new MyPipe().transform(myData, arg1, arg2, arg3)
And in your transform function inside your pipe you can use the arguments like this:
export class MyPipe implements PipeTransform {
// specify every argument individually
transform(value: any, arg1: any, arg2: any, arg3: any): any { }
// or use a rest parameter
transform(value: any, ...args: any[]): any { }
}
Beta 16 and before (2016-04-26)
Pipes take an array that contains all arguments, so you need to call them like this:
new MyPipe().transform(myData, [arg1, arg2, arg3...])
And your transform function will look like this:
export class MyPipe implements PipeTransform {
transform(value:any, args:any[]):any {
var arg1 = args[0];
var arg2 = args[1];
...
}
}
For Ubuntu you can use the prebuilt versions downloadable from the PhantomJS site.
If you have some serious time on your hands you can also build it yourself. (This is exactly the procedure from Nikhil's answer).
The guys over at PhantomJS recommend using the binaries to save time:
Warning: Compiling PhantomJS from source takes a long time, mainly due to thousands of files in the WebKit module. With 4 parallel compile jobs on a modern machine, the entire process takes roughly 30 minutes. It is highly recommended to download and install the ready-made binary package if it is available.
With a modern machine they mean > 4 cores, > 8gb mem I think. I tried it on a micro AWS instance and gave up after 2 hours.
In short: install the prebuilt packages from the PhantomJS site per their instructions.
I know this is question is a year old, but here's some pretty simple code (mostly from this tutorial) that's working well for me:
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var imageView: UIImageView!
var imagePicker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
self.imagePicker.delegate = self
}
@IBAction func loadImageButtonTapped(sender: AnyObject) {
print("hey!")
self.imagePicker.allowsEditing = false
self.imagePicker.sourceType = .SavedPhotosAlbum
self.presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
self.imageView.contentMode = .ScaleAspectFit
self.imageView.image = pickedImage
}
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
self.imagePicker = UIImagePickerController()
dismissViewControllerAnimated(true, completion: nil)
}
You just need to delete the branch you are on. You can't use git branch -D
as this has a safety check against doing this. You can use update-ref
to do this.
git update-ref -d HEAD
Do not use rm -rf .git
or anything like this as this will completely wipe your entire repository including all other branches as well as the branch that you are trying to reset.
date.ToString("HH:mm:ss"); // for 24hr format
date.ToString("hh:mm:ss"); // for 12hr format, it shows AM/PM
Refer this link for other Formatters in DateTime.
You need to access the layout via it's layout resource, not an id resource which is not guaranteed unique. The resource reference should look like R.layout.my_cool_layout where your above XML layout is stored in res/layout/my_cool_layout.xml.
This would work very well -- You can use HTML5 to allow only image files to be uploaded. This is the code for uploader.htm --
<html>
<head>
<script>
function validateForm(){
var image = document.getElementById("image").value;
var name = document.getElementById("name").value;
if (image =='')
{
return false;
}
if(name =='')
{
return false;
}
else
{
return true;
}
return false;
}
</script>
</head>
<body>
<form method="post" action="upload.php" enctype="multipart/form-data">
<input type="text" name="ext" size="30"/>
<input type="text" name="name" id="name" size="30"/>
<input type="file" accept="image/*" name="image" id="image" />
<input type="submit" value='Save' onclick="return validateForm()"/>
</form>
</body>
</html>
Now the code for upload.php --
<?php
$name = $_POST['name'];
$ext = $_POST['ext'];
if (isset($_FILES['image']['name']))
{
$saveto = "$name.$ext";
move_uploaded_file($_FILES['image']['tmp_name'], $saveto);
$typeok = TRUE;
switch($_FILES['image']['type'])
{
case "image/gif": $src = imagecreatefromgif($saveto); break;
case "image/jpeg": // Both regular and progressive jpegs
case "image/pjpeg": $src = imagecreatefromjpeg($saveto); break;
case "image/png": $src = imagecreatefrompng($saveto); break;
default: $typeok = FALSE; break;
}
if ($typeok)
{
list($w, $h) = getimagesize($saveto);
$max = 100;
$tw = $w;
$th = $h;
if ($w > $h && $max < $w)
{
$th = $max / $w * $h;
$tw = $max;
}
elseif ($h > $w && $max < $h)
{
$tw = $max / $h * $w;
$th = $max;
}
elseif ($max < $w)
{
$tw = $th = $max;
}
$tmp = imagecreatetruecolor($tw, $th);
imagecopyresampled($tmp, $src, 0, 0, 0, 0, $tw, $th, $w, $h);
imageconvolution($tmp, array( // Sharpen image
array(-1, -1, -1),
array(-1, 16, -1),
array(-1, -1, -1)
), 8, 0);
imagejpeg($tmp, $saveto);
imagedestroy($tmp);
imagedestroy($src);
}
}
?>
Combine the SUBSTRING()
, LEFT()
, and CHARINDEX()
functions.
SELECT LEFT(SUBSTRING(YOUR_FIELD,
CHARINDEX(';', YOUR_FIELD) + 1, 100),
CHARINDEX('[', YOUR_FIELD) - 1)
FROM YOUR_TABLE;
This assumes your field length will never exceed 100, but you can make it smarter to account for that if necessary by employing the LEN()
function. I didn't bother since there's enough going on in there already, and I don't have an instance to test against, so I'm just eyeballing my parentheses, etc.
My IDE left a mix of spaces and tabs in my Makefile.
Setting my Makefile to use only tabs fixed this error for me.
I know this is an older post, but I just got hit with a similar issue and was able to resolve it, so I thought I'd share.
(Update: As noted in the comments below, this answer was before the inclusion of the "git stash" feature to eGit.)
What I did was:
Hope that helps.
Maybe this is a little bit late but I found a web site which gives social media account details by know email addreess. It is https://www.fullcontact.com
You can use Person Api there and get the info.
This is a type of get : https://api.fullcontact.com/v2/person.xml?email=someone@****&apiKey=********
Also there is xml or json choice.
If your strings are compile time constants (as in your case) you can use the following trick:
#define USER_JACK strcmp(USER, "jack")
#define USER_QUEEN strcmp(USER, "queen")
#if $USER_JACK == 0
#define USER_VS USER_QUEEN
#elif USER_QUEEN == 0
#define USER_VS USER_JACK
#endif
The compiler can tell the result of the strcmp in advance and will replace the strcmp with its result, thus giving you a #define that can be compared with preprocessor directives. I don't know if there's any variance between compilers/dependance on compiler options, but it worked for me on GCC 4.7.2.
EDIT: upon further investigation, it look like this is a toolchain extension, not GCC extension, so take that into consideration...
This: "\0"
is a string, not a character. A character uses single quotes, like '\0'
.
To diagnose it, follow this answer.
But to fix it, knowing you are the only one changing it, do:
1 - backup your project (I did only the files on git, ./src folder)
2 - git pull
3 - restore you backup over the many "messed" files (with merge indicators)
I tried git pull -s recursive -X ours
but didnt work the way I wanted, it could be an option tho, but backup first!!!
Make sure the differences/changes (at git gui) are none. This is my case, there is nothing to merge at all, but github keeps saying I should merge...
You can also use something like this
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Add / Remove Table Rows Dynamically</title>
<style type="text/css">
form{
margin: 20px 0;
}
form input, button{
padding: 5px;
}
table{
width: 100%;
margin-bottom: 20px;
border-collapse: collapse;
}
table, th, td{
border: 1px solid #cdcdcd;
}
table th, table td{
padding: 10px;
text-align: left;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".add-row").click(function(){
var name = $("#name").val();
var email = $("#email").val();
var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + name + "</td><td>" + email + "</td></tr>";
$("table tbody").append(markup);
});
// Find and remove selected table rows
$(".delete-row").click(function(){
$("table tbody").find('input[name="record"]').each(function(){
if($(this).is(":checked")){
$(this).parents("tr").remove();
}
});
});
});
</script>
</head>
<body>
<form>
<input type="text" id="name" placeholder="Name">
<input type="text" id="email" placeholder="Email Address">
<input type="button" class="add-row" value="Add Row">
</form>
<table>
<thead>
<tr>
<th>Select</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" name="record"></td>
<td>Peter Parker</td>
<td>[email protected]</td>
</tr>
</tbody>
</table>
<button type="button" class="delete-row">Delete Row</button>
</body>
</html>
If you're building from Unity3D 5 and also using a Prime31 plugin and you're getting this error it's probably due to a duplicate .dll. If you look through your warnings in Unity's editor one of them will tell you this and warn that it could cause build errors. To see if this is the case, type P31 in your project search field and it should pop right up, maybe even more than one. The duplicate's will have a ' 1' at the end of the file name. This is probably caused from updating the plugin in editor via the store or the Prime31 menu tab.
Your team members must be accessing the repository using SSH & for that they have to have their ssh key mapped with github account. This will work if they map their ssh key with github account and also the repository has public rights, which they want to access.
when we run application in eclipse apk generate is sign by default Keystore which is provided by android .
But if you want to upload your application on play store you need to create your own keystore. Eclipse already provides GUI interface to create new keystore. And you also can create keystore through command line.
default alias is
androiddebugkey
You can use CustomMultiChildLayout to draw this kind of layouts. Here you can find a tutorial: How to Create Custom Layout Widgets in Flutter.
Extensions make our lives easier:
static public class StringExtensions
{
static public string ReplaceInsensitive(this string str, string from, string to)
{
str = Regex.Replace(str, from, to, RegexOptions.IgnoreCase);
return str;
}
}
For me to make it work again I just deleted the files
ib_logfile0
and
ib_logfile1
.
from :
/Applications/MAMP/db/mysql56/ib_logfile0
Mac 10.13.3
MAMP:Version 4.3 (853)
You can use body or * to make margin and padding 0px;
*{
margin: 0px;
padding:0px;
}
Just as Daniel said "Git and TFVC are the two source control options in TFS
". Fortunately both are supported for now in VS Code.
You need to install the Azure Repos Extension for Visual Studio Code. The process of installing is pretty straight forward.
Add the following lines to your user settings
If you have VS 2015 installed on your machine, your path to Team Foundation tool (tf.exe) may look like this:
{ "tfvc.location": "C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\IDE\\tf.exe", "tfvc.restrictWorkspace": true }
Or for VS 2017:
{ "tfvc.location": "C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Enterprise\\Common7\\IDE\\CommonExtensions\\Microsoft\\TeamFoundation\\Team Explorer\\tf.exe", "tfvc.restrictWorkspace": true }
Open a local folder (repository), From View -> Command Pallette ..., type team signin
Provide user name --> Enter --> Provide password to connect to TFS.
Please refer to below links for more details:
Note that Server Workspaces are not supported:
"TFVC support is limited to Local workspaces":
The problems is that dropboxes don't work the same as listboxes, at least the way ASP.NET MVC2 design expects: A dropbox allows only zero or one values, as listboxes can have a multiple value selection. So, being strict with HTML, that value shouldn't be in the option list as "selected" flag, but in the input itself.
See the following example:
<select id="combo" name="combo" value="id2">
<option value="id1">This is option 1</option>
<option value="id2" selected="selected">This is option 2</option>
<option value="id3">This is option 3</option>
</select>
<select id="listbox" name="listbox" multiple>
<option value="id1">This is option 1</option>
<option value="id2" selected="selected">This is option 2</option>
<option value="id3">This is option 3</option>
</select>
The combo has the option selected, but also has its value attribute set. So, if you want ASP.NET MVC2 to render a dropbox and also have a specific value selected (i.e., default values, etc.), you should give it a value in the rendering, like this:
// in my view
<%=Html.DropDownList("UserId", selectListItems /* (SelectList)ViewData["UserId"]*/, new { @Value = selectedUser.Id } /* Your selected value as an additional HTML attribute */)%>
function GetPixel(context, x, y)
{
var p = context.getImageData(x, y, 1, 1).data;
var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
return hex;
}
function rgbToHex(r, g, b) {
if (r > 255 || g > 255 || b > 255)
throw "Invalid color component";
return ((r << 16) | (g << 8) | b).toString(16);
}
Your first CSS selector—social.h2
—is looking for the "social" element in the "h2", class, e.g.:
<social class="h2">
Class selectors are proceeded with a dot (.
). Also, use a space () to indicate that one element is inside of another. To find an
<h2>
descendant of an element in the social
class, try something like:
.social h2 {
color: pink;
font-size: 14px;
}
To get a better understanding of CSS selectors and how they are used to reference your HTML, I suggest going through the interactive HTML and CSS tutorials from CodeAcademy. I hope that this helps point you in the right direction.
In section "12.2 Specification of Mappings" of the Servlet Specification, it says:
A string containing only the ’/’ character indicates the "default" servlet of the application.
So in theory, you could make your Servlet mapped to /*
do:
getServletContext().getNamedDispatcher("/").forward(req,res);
... if you didn't want to handle it yourself.
However, in practice, it doesn't work.
In both Tomcat and Jetty, the call to getServletContext().getNamedDispatcher('/')
returns null
if there is a servlet mapped to '/*'
this worked fine for me
@import 'folder/*';
run this command on your terminal(here -v11 is for version 11(java11))-:
/usr/libexec/java_home -v11
you will get the path on your terminal something like this -:
/Library/Java/JavaVirtualMachines/jdk-11.0.9.jdk/Contents/Home
now you need to open your bash profile in any editor for eg VS Code
if you want to edit your bash_profile in vs code then run this command -:
code ~/.bash_profile
else run this command and then press i to insert the path. -:
open ~/.bash_profile
you will get your .bash_profile now you need to add the path so add this in .bash_profile (path which you get from 1st command)-:
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-11.0.9.jdk/Contents/Home
if you were using code editor then now go to terminal and run this command to save the changes -:
source ~/.bash_profile
else press esc then :wq to exit from bash_profile then go to terminal and run the command given above. process completed. now you can check using this command -:
echo $JAVA_HOME
you will get/Library/Java/JavaVirtualMachines/jdk-11.0.9.jdk/Contents/Home
Don't read out of date articles under MSDN. .NET Core relevant materials are under docs.microsoft.com
https://docs.microsoft.com/en-us/dotnet/articles/core/testing/
Generally speaking you need a .NET Core console app to contain the unit test cases.
You could make it into a module and expose your inner function by returning it in an Object.
function outer() {
function inner() {
console.log("hi");
}
return {
inner: inner
};
}
var foo = outer();
foo.inner();
As of today, Windows PowerShell 5.1 is the latest version. It can be installed as part of Windows Management Framework 5.1. It was released in January 2017.
Quoting from the official Microsoft download page here.
Some of the new and updated features in this release include:
- Constrained file copying to/from JEA endpoints
- JEA support for Group Managed Service Accounts and Conditional Access Policies
- PowerShell console support for VT100 and redirecting stdin with interactive input
- Support for catalog signed modules in PowerShell Get
- Specifying which module version to load in a script
- Package Management cmdlet support for proxy servers
- PowerShellGet cmdlet support for proxy servers
- Improvements in PowerShell Script Debugging
- Improvements in Desired State Configuration (DSC)
- Improved PowerShell usage auditing using Transcription and Logging
- New and updated cmdlets based on community feedback
Here's a sample code:
Exec sp_add_schedule
@schedule_name = N'SchedulName'
@freq_type = 1
@active_start_time = 08300
After reading many pages about FRP I finally came across this enlightening writing about FRP, it finally made me understand what FRP really is all about.
I quote below Heinrich Apfelmus (author of reactive banana).
What is the essence of functional reactive programming?
A common answer would be that “FRP is all about describing a system in terms of time-varying functions instead of mutable state”, and that would certainly not be wrong. This is the semantic viewpoint. But in my opinion, the deeper, more satisfying answer is given by the following purely syntactic criterion:
The essence of functional reactive programming is to specify the dynamic behavior of a value completely at the time of declaration.
For instance, take the example of a counter: you have two buttons labelled “Up” and “Down” which can be used to increment or decrement the counter. Imperatively, you would first specify an initial value and then change it whenever a button is pressed; something like this:
counter := 0 -- initial value on buttonUp = (counter := counter + 1) -- change it later on buttonDown = (counter := counter - 1)
The point is that at the time of declaration, only the initial value for the counter is specified; the dynamic behavior of counter is implicit in the rest of the program text. In contrast, functional reactive programming specifies the whole dynamic behavior at the time of declaration, like this:
counter :: Behavior Int counter = accumulate ($) 0 (fmap (+1) eventUp `union` fmap (subtract 1) eventDown)
Whenever you want to understand the dynamics of counter, you only have to look at its definition. Everything that can happen to it will appear on the right-hand side. This is very much in contrast to the imperative approach where subsequent declarations can change the dynamic behavior of previously declared values.
So, in my understanding an FRP program is a set of equations:
j
is discrete: 1,2,3,4...
f
depends on t
so this incorporates the possiblilty to model external stimuli
all state of the program is encapsulated in variables x_i
The FRP library takes care of progressing time, in other words, taking j
to j+1
.
I explain these equations in much more detail in this video.
EDIT:
About 2 years after the original answer, recently I came to the conclusion that FRP implementations have another important aspect. They need to (and usually do) solve an important practical problem: cache invalidation.
The equations for x_i
-s describe a dependency graph. When some of the x_i
changes at time j
then not all the other x_i'
values at j+1
need to be updated, so not all the dependencies need to be recalculated because some x_i'
might be independent from x_i
.
Furthermore, x_i
-s that do change can be incrementally updated. For example let's consider a map operation f=g.map(_+1)
in Scala, where f
and g
are List
of Ints
. Here f
corresponds to x_i(t_j)
and g
is x_j(t_j)
. Now if I prepend an element to g
then it would be wasteful to carry out the map
operation for all the elements in g
. Some FRP implementations (for example reflex-frp) aim to solve this problem. This problem is also known as incremental computing.
In other words, behaviours (the x_i
-s ) in FRP can be thought as cache-ed computations. It is the task of the FRP engine to efficiently invalidate and recompute these cache-s (the x_i
-s) if some of the f_i
-s do change.
From Docker documentation:
docker export
does not export the contents of volumes associated with the container. If a volume is mounted on top of an existing directory in the container,docker export
will export the contents of the underlying directory, not the contents of the volume. Refer to Backup, restore, or migrate data volumes in the user guide for examples on exporting data in a volume.
I know this is late, but the answer is simply removing "time" from the word, datetimepicker
to change it to datepicker
. You can format it with dateFormat
.
jQuery( "#datetimepicker4" ).datepicker({
dateFormat: "MM dd, yy",
});
Install the CSS Usage add-on for Firebug and run it on that page. It will tell you which styles are being used and not used by that page.
Weston Ruther built a similar thing using the WebKit proposal for css transitions:
http://weston.ruter.net/projects/jquery-css-transitions/
This implementation might be useful for you.
The real limits for the alert text are not documented anywhere. The only thing the documentation says is:
In iOS 8 and later, the maximum size allowed for a notification payload is 2 kilobytes; Apple Push Notification Service refuses any notification that exceeds this limit. (Prior to iOS 8 and in OS X, the maximum payload size is 256 bytes.)
This is what I could find doing some experiments.
Just as a reminder here is a very good note from the official documentation:
If necessary, iOS truncates your message so that it fits well in each notification delivery style; for best results, you shouldn’t truncate your message.
The accepted answer here gave me unpredictable results, sometimes weirdly adding months and years.
The most reliable way I could find was found here Add days to Javascript Date object, and also increment month
var dayOffset = 20;
var millisecondOffset = dayOffset * 24 * 60 * 60 * 1000;
december.setTime(december.getTime() + millisecondOffset);
EDIT: Even though it has worked for some people, I don't think it is entirely correct. I would recommend going with a more popular answer or using something like http://momentjs.com/
I was able to get jsPDF to print dynamically created tables from a div.
$(document).ready(function() {
$("#pdfDiv").click(function() {
var pdf = new jsPDF('p','pt','letter');
var specialElementHandlers = {
'#rentalListCan': function (element, renderer) {
return true;
}
};
pdf.addHTML($('#rentalListCan').first(), function() {
pdf.save("caravan.pdf");
});
});
});
Works great with Chrome and Firefox... formatting is all blown up in IE.
I also included these:
<script src="js/jspdf.js"></script>
<script src="js/jspdf.plugin.from_html.js"></script>
<script src="js/jspdf.plugin.addhtml.js"></script>
<script src="//mrrio.github.io/jsPDF/dist/jspdf.debug.js"></script>
<script src="http://html2canvas.hertzen.com/build/html2canvas.js"></script>
<script type="text/javascript" src="./libs/FileSaver.js/FileSaver.js"></script>
<script type="text/javascript" src="./libs/Blob.js/Blob.js"></script>
<script type="text/javascript" src="./libs/deflate.js"></script>
<script type="text/javascript" src="./libs/adler32cs.js/adler32cs.js"></script>
<script type="text/javascript" src="js/jspdf.plugin.addimage.js"></script>
<script type="text/javascript" src="js/jspdf.plugin.sillysvgrenderer.js"></script>
<script type="text/javascript" src="js/jspdf.plugin.split_text_to_size.js"></script>
<script type="text/javascript" src="js/jspdf.plugin.standard_fonts_metrics.js"></script>
The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the distinct
approach is executed like:
business_key
values to a temporary tableThe group by
could be executed like:
business key
in a hashtableThe first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.
Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.
I just discovered a nice way to set your page title if you're using routing:
JavaScript:
var myApp = angular.module('myApp', ['ngResource'])
myApp.config(
['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {
title: 'Home',
templateUrl: '/Assets/Views/Home.html',
controller: 'HomeController'
});
$routeProvider.when('/Product/:id', {
title: 'Product',
templateUrl: '/Assets/Views/Product.html',
controller: 'ProductController'
});
}]);
myApp.run(['$rootScope', function($rootScope) {
$rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
$rootScope.title = current.$$route.title;
});
}]);
HTML:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title ng-bind="'myApp — ' + title">myApp</title>
...
Edit: using the ng-bind
attribute instead of curlies {{}}
so they don't show on load
It depends on what you are trying to do.
file, err := os.Open("file.txt")
fmt.print(file)
The reason it outputs &{0xc082016240}, is because you are printing the pointer value of a file-descriptor (*os.File
), not file-content. To obtain file-content, you may READ
from a file-descriptor.
To read all file content(in bytes) to memory, ioutil.ReadAll
package main
import (
"fmt"
"io/ioutil"
"os"
"log"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
b, err := ioutil.ReadAll(file)
fmt.Print(b)
}
But sometimes, if the file size is big, it might be more memory-efficient to just read in chunks: buffer-size, hence you could use the implementation of io.Reader.Read
from *os.File
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
buf := make([]byte, 32*1024) // define your buffer size here.
for {
n, err := file.Read(buf)
if n > 0 {
fmt.Print(buf[:n]) // your read buffer.
}
if err == io.EOF {
break
}
if err != nil {
log.Printf("read %d bytes: %v", n, err)
break
}
}
}
Otherwise, you could also use the standard util package: bufio
, try Scanner
. A Scanner
reads your file in tokens: separator.
By default, scanner advances the token by newline (of course you can customise how scanner should tokenise your file, learn from here the bufio test).
package main
import (
"fmt"
"os"
"log"
"bufio"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
scanner := bufio.NewScanner(file)
for scanner.Scan() { // internally, it advances token based on sperator
fmt.Println(scanner.Text()) // token in unicode-char
fmt.Println(scanner.Bytes()) // token in bytes
}
}
Lastly, I would also like to reference you to this awesome site: go-lang file cheatsheet. It encompassed pretty much everything related to working with files in go-lang, hope you'll find it useful.
No. Its not possible to add link through css. But you can use jquery
$('.case').each(function() {
var link = $(this).html();
$(this).contents().wrap('<a href="example.com/script.php?id="></a>');
});
Here the demo: http://jsfiddle.net/r5uWX/1/
Just needs to go:
Solution Explorer-->Go to Properties --->change(Single Startup project) from.dll to .web
Then try to debug it.
Surely your problem will be solved.
Based on the error you showed ('footballforum' is missing required Java project: 'ApiDemos'), I would check your build path. Right-click the footballforum project and choose Build Path > Configure Build Path. Make sure ApiDemos is on the projects tab of the build path options.
Try this code,
$('#1').on('mousedown',function(e) {
if (e.button==0 && e.ctrlKey) {
alert('is Left Click');
} else if (e.button==2 && e.ctrlKey){
alert('is Right Click');
}
});
Sorry I added e.ctrlKey.
You can also use EXIT_SUCCESS
instead of return 0;
. The macro EXIT_SUCCESS
is actually defined as zero, but makes your program more readable.
According to documentation:
random.sample(population, k)
Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.
Basically, it picks k unique random elements, a sample, from a sequence:
>>> import random
>>> c = list(range(0, 15))
>>> c
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> random.sample(c, 5)
[9, 2, 3, 14, 11]
random.sample
works also directly from a range:
>>> c = range(0, 15)
>>> c
range(0, 15)
>>> random.sample(c, 5)
[12, 3, 6, 14, 10]
In addition to sequences, random.sample
works with sets too:
>>> c = {1, 2, 4}
>>> random.sample(c, 2)
[4, 1]
However, random.sample
doesn't work with arbitrary iterators:
>>> c = [1, 3]
>>> random.sample(iter(c), 5)
TypeError: Population must be a sequence or set. For dicts, use list(d).
$('#column-left form').hide();
$('.show-search').click(function() {
$('#column-left form').stop(true, true).slideToggle(300); //this will slide but not hide that's why
$('#column-left form').hide();
if(!($('#column-left form').is(":visible"))) {
$("#offers").show();
} else {
$('#offers').hide();
}
});
Retrofit 2.0 :
UPDATE: @by Marcus Pöhls
Logging In Retrofit 2
Retrofit 2 completely relies on OkHttp for any network operation. Since OkHttp is a peer dependency of Retrofit 2, you won’t need to add an additional dependency once Retrofit 2 is released as a stable release.
OkHttp 2.6.0 ships with a logging interceptor as an internal dependency and you can directly use it for your Retrofit client. Retrofit 2.0.0-beta2 still uses OkHttp 2.5.0. Future releases will bump the dependency to higher OkHttp versions. That’s why you need to manually import the logging interceptor. Add the following line to your gradle imports within your build.gradle file to fetch the logging interceptor dependency.
compile 'com.squareup.okhttp3:logging-interceptor:3.9.0'
You can also visit Square's GitHub page about this interceptor
Add Logging to Retrofit 2
While developing your app and for debugging purposes it’s nice to have a log feature integrated to show request and response information. Since logging isn’t integrated by default anymore in Retrofit 2, we need to add a logging interceptor for OkHttp. Luckily OkHttp already ships with this interceptor and you only need to activate it for your OkHttpClient.
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// set your desired log level
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
// add your other interceptors …
// add logging as last interceptor
httpClient.addInterceptor(logging); // <-- this is the important line!
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
We recommend to add logging as the last interceptor, because this will also log the information which you added with previous interceptors to your request.
Log Levels
Logging too much information will blow up your Android monitor, that’s why OkHttp’s logging interceptor has four log levels: NONE, BASIC, HEADERS, BODY. We’ll walk you through each of the log levels and describe their output.
further information please visit : Retrofit 2 — Log Requests and Responses
OLD ANSWER:
no logging in Retrofit 2 anymore. The development team removed the logging feature. To be honest, the logging feature wasn’t that reliable anyway. Jake Wharton explicitly stated that the logged messages or objects are the assumed values and they couldn’t be proofed to be true. The actual request which arrives at the server may have a changed request body or something else.
Even though there is no integrated logging by default, you can leverage any Java logger and use it within a customized OkHttp interceptor.
further information about Retrofit 2 please refer : Retrofit — Getting Started and Create an Android Client
Reverse the entire string, then reverse the letters of each individual word.
After the first pass the string will be
s1 = "Z Y X si eman yM"
and after the second pass it will be
s1 = "Z Y X is name My"
.xlsx
loads 4 times longer than .xlsb
and saves 2 times longer and has 1.5 times a bigger file. I tested this on a generated worksheet with 10'000 rows * 1'000 columns = 10'000'000 (10^7) cells of simple chained =…+1
formulas:
?--------------------------------?
¦ ¦ .xlsx ¦ .xlsb ¦
¦--------------+--------+--------¦
¦ loading time ¦ 165s ¦ 43s ¦
+--------------+--------+--------¦
¦ saving time ¦ 115s ¦ 61s ¦
+--------------+--------+--------¦
¦ file size ¦ 91 MB ¦ 65 MB ¦
?--------------------------------?
(Hardware: Core2Duo 2.3 GHz, 4 GB RAM, 5.400 rpm SATA II HD; Windows 7, under somewhat heavy load from other processes.)
Beside this, there should be no differences. More precisely,
both formats support exactly the same feature set
cites this blog post from 2006-08-29. So maybe the info that .xlsb
does not support Ribbon code is newer than the upper citation, but I figure that forum source of yours is just wrong. When cracking open the binary file, it seems to condensedly mimic the OOXML file structure 1-to-1: Blog article from 2006-08-07
Another way is to subtract 15 days from the current date and compare CreationTime
against that value:
$root = 'C:\root\folder'
$limit = (Get-Date).AddDays(-15)
Get-ChildItem $root -Recurse | ? {
-not $_.PSIsContainer -and $_.CreationTime -lt $limit
} | Remove-Item
Serialize and Deserialize (XML/JSON):
public static T XmlDeserialize<T>(this string toDeserialize)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
using(StringReader textReader = new StringReader(toDeserialize))
{
return (T)xmlSerializer.Deserialize(textReader);
}
}
public static string XmlSerialize<T>(this T toSerialize)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
using(StringWriter textWriter = new StringWriter())
{
xmlSerializer.Serialize(textWriter, toSerialize);
return textWriter.ToString();
}
}
public static T JsonDeserialize<T>(this string toDeserialize)
{
return JsonConvert.DeserializeObject<T>(toDeserialize);
}
public static string JsonSerialize<T>(this T toSerialize)
{
return JsonConvert.SerializeObject(toSerialize);
}
To get the entire request URL string:
HttpContext.Current.Request.Url
To get the www.foo.com portion of the request:
HttpContext.Current.Request.Url.Host
Note that you are, to some degree, at the mercy of factors outside your ASP.NET application. If IIS is configured to accept multiple or any host header for your application, then any of those domains which resolved to your application via DNS may show up as the Request Url, depending on which one the user entered.
and If you want to set proxy for wget you should put these line in your Dockerfile
ENV http_proxy YOUR-PROXY-IP:PORT/
ENV https_proxy YOUR-PROXY-IP:PORT/
ENV all_proxy YOUR-PROXY-IP:PORT/
You were right regarding how you want to generate salt i.e. its nothing but a random number. For this particular case it would protect your system from possible Dictionary attacks. Now, for the second problem what you could do is instead of using UTF-8 encoding you may want to use Base64. Here, is a sample for generating a hash. I am using Apache Common Codecs for doing the base64 encoding you may select one of your own
public byte[] generateSalt() {
SecureRandom random = new SecureRandom();
byte bytes[] = new byte[20];
random.nextBytes(bytes);
return bytes;
}
public String bytetoString(byte[] input) {
return org.apache.commons.codec.binary.Base64.encodeBase64String(input);
}
public byte[] getHashWithSalt(String input, HashingTechqniue technique, byte[] salt) throws NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance(technique.value);
digest.reset();
digest.update(salt);
byte[] hashedBytes = digest.digest(stringToByte(input));
return hashedBytes;
}
public byte[] stringToByte(String input) {
if (Base64.isBase64(input)) {
return Base64.decodeBase64(input);
} else {
return Base64.encodeBase64(input.getBytes());
}
}
Here is some additional reference of the standard practice in password hashing directly from OWASP
Simply put, in the first case, you are assigning multiple names to a list
. Only one copy of list is created in memory and all names refer to that location. So changing the list using any of the names will actually modify the list in memory.
In the second case, multiple copies of same value are created in memory. So each copy is independent of one another.
Use git format-patch
to slice out the part of the commit you care about and git am
to apply it to another branch
git format-patch <sha> -- path/to/file
git checkout other-branch
git am *.patch
<% ViewData.ModelState.IsValid %>
or
<% ViewData.ModelState.Values.Any(x => x.Errors.Count >= 1) %>
and for a specific property...
<% ViewData.ModelState["Property"].Errors %> // Note this returns a collection
exit code 139 (people say this means memory fragmentation)
No, it means that your program died with signal 11
(SIGSEGV
on Linux and most other UNIXes), also known as segmentation fault
.
Could anybody tell me why the run fails but debug doesn't?
Your program exhibits undefined behavior, and can do anything (that includes appearing to work correctly sometimes).
Your first step should be running this program under Valgrind, and fixing all errors it reports.
If after doing the above, the program still crashes, then you should let it dump core (ulimit -c unlimited; ./a.out
) and then analyze that core dump with GDB: gdb ./a.out core
; then use where
command.
I had the exact same problem when manually compiling through the command line, my solution was I didn't include the -sourcepath directory so that way all the subdirectory java files would be compiled too!
You can delete column like this:
df.drop("column Name).columns
In your case :
df.drop("id").columns
If you want to drop more than one column you can do:
dfWithLongColName.drop("ORIGIN_COUNTRY_NAME", "DEST_COUNTRY_NAME")
I had a similar issue using Apache 2.4 and PHP 7.
My client sent a lot of requests when refreshing (hard reloading) my application page in the browser and every time some of the last requests resulted in this error in console:
GET
http://example.com/api/v1/my/resource
net::ERR_CONNECTION_RESET
It turned out that my client was reaching the maximum amount of threads that was allowed. The threads exceeding this configured ceiling are simply not handled by Apache at all resulting in the connection reset error response.
The amount of threads can be easily raised by setting the ThreadsPerChild
value for the module in question.
The easiest way to make such change is to uncomment the Server-pool management config file conf/extra/httpd-mpm.conf
and then editing the preset values in the file to desired values.
1) Uncomment the Server-pool management file
# Server-pool management (MPM specific)
Include conf/extra/httpd-mpm.conf
2) Open and edit the file conf/extra/httpd-mpm.conf
and raise the amount of threads
In my case I had to change the threads for the mpm_winnt_module
:
# raised the amount of threads for mpm_winnt_module to 250
<IfModule mpm_winnt_module>
ThreadsPerChild 250
MaxConnectionsPerChild 0
</IfModule>
A comprehensive explanation on these Server-pool management configuration settings can be found in this post on StackOverflow.
An update to @jrgns (with some slight syntax differences) solution.
$result = mysql_query('SELECT * FROM `some_table`');
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++)
{
$headers[] = mysql_field_name($result , $i);
}
$fp = fopen('php://output', 'w');
if ($fp && $result)
{
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = mysql_fetch_row($result))
{
fputcsv($fp, array_values($row));
}
die;
}
One technique is to create a copy of the collection you want to modify, change the copy as needed, then replace the original collection with the copy at the end.
You can simply check out a new branch, and then commit:
git checkout -b my_new_branch
git commit
Checking out the new branch will not discard your changes.
In the case where you have multiple variables containing the arguments for a command you're running, and not just a single string, you should not use eval directly, as it will fail in the following case:
function echo_arguments() {
echo "Argument 1: $1"
echo "Argument 2: $2"
echo "Argument 3: $3"
echo "Argument 4: $4"
}
# Note we are passing 3 arguments to `echo_arguments`, not 4
eval echo_arguments arg1 arg2 "Some arg"
Result:
Argument 1: arg1
Argument 2: arg2
Argument 3: Some
Argument 4: arg
Note that even though "Some arg" was passed as a single argument, eval
read it as two.
Instead, you can just use the string as the command itself:
# The regular bash eval works by jamming all its arguments into a string then
# evaluating the string. This function treats its arguments as individual
# arguments to be passed to the command being run.
function eval_command() {
"$@";
}
Note the difference between the output of eval
and the new eval_command
function:
eval_command echo_arguments arg1 arg2 "Some arg"
Result:
Argument 1: arg1
Argument 2: arg2
Argument 3: Some arg
Argument 4:
[host_group]
host-1 ansible_ssh_host=192.168.0.21 node_name=foo
host-2 ansible_ssh_host=192.168.0.22 node_name=bar
[host_group:vars]
custom_var=asdasdasd
You can access host group vars using:
{{ hostvars['host_group'].custom_var }}
If you need a specific value from specific host, you can use:
{{ hostvars[groups['host_group'][0]].node_name }}
It is not what is asked directly. But looking for how to do drop tables properly, I stumbled over this question, as I guess many others do too.
From SQL Server 2016+ you can use
DROP TABLE IF EXISTS dbo.Table
For SQL Server <2016 what I do is the following for a permanent table
IF OBJECT_ID('dbo.Table', 'U') IS NOT NULL
DROP TABLE dbo.Table;
Or this, for a temporary table
IF OBJECT_ID('tempdb.dbo.#T', 'U') IS NOT NULL
DROP TABLE #T;
It's this simple:
var a = [[12, 'AAA'], [58, 'BBB'], [28, 'CCC'],[18, 'DDD']];
a.sort(sortFunction);
function sortFunction(a, b) {
if (a[0] === b[0]) {
return 0;
}
else {
return (a[0] < b[0]) ? -1 : 1;
}
}
I invite you to read the documentation.
If you want to sort by the second column, you can do this:
a.sort(compareSecondColumn);
function compareSecondColumn(a, b) {
if (a[1] === b[1]) {
return 0;
}
else {
return (a[1] < b[1]) ? -1 : 1;
}
}
you can solve it
sudo nano /etc/apache2/ports.conf
and changed Listen to 8080
If you want happen to be using LESS it can be achieved like so:
li {
.glyphicon-ok();
&:before {
.glyphicon();
margin-left:-25px;
float:left;
}
}
It's not really something you need jQuery to do. There is a very simple plain old javascript method for doing this:
window.open('http://www.google.com','GoogleWindow', 'width=800, height=600');
That's it.
The first arg is the url, the second is the name of the window, this should be specified because IE will throw a fit about trying to use window.opener
later if there was no window name specified (just a little FYI), and the last two params are width/height.
EDIT: Full specification can be found in the link mmmshuddup provided.
I was trying to also sort by a DateTime field descending and this seems to do the trick:
var ud = (from d in env
orderby -d.ReportDate.Ticks
select d.ReportDate.ToString("yyyy-MMM") ).Distinct();
You want this:
AAPL:
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
The YAML equivalent of a JSON object is a mapping, which looks like these:
# flow style
{ foo: 1, bar: 2 }
# block style
foo: 1
bar: 2
Note that the first characters of the keys in a block mapping must be in the same column. To demonstrate:
# OK
foo: 1
bar: 2
# Parse error
foo: 1
bar: 2
The equivalent of a JSON array in YAML is a sequence, which looks like either of these (which are equivalent):
# flow style
[ foo bar, baz ]
# block style
- foo bar
- baz
In a block sequence the -
s must be in the same column.
Let's turn your JSON into YAML. Here's your JSON:
{"AAPL": [
{
"shares": -75.088,
"date": "11/27/2015"
},
{
"shares": 75.088,
"date": "11/26/2015"
},
]}
As a point of trivia, YAML is a superset of JSON, so the above is already valid YAML—but let's actually use YAML's features to make this prettier.
Starting from the inside out, we have objects that look like this:
{
"shares": -75.088,
"date": "11/27/2015"
}
The equivalent YAML mapping is:
shares: -75.088
date: 11/27/2015
We have two of these in an array (sequence):
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
Note how the -
s line up and the first characters of the mapping keys line up.
Finally, this sequence is itself a value in a mapping with the key AAPL
:
AAPL:
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
Parsing this and converting it back to JSON yields the expected result:
{
"AAPL": [
{
"date": "11/27/2015",
"shares": -75.088
},
{
"date": "11/26/2015",
"shares": 75.088
}
]
}
You can see it (and edit it interactively) here.
The server at x3.chatforyoursite.com
needs to output the following header:
Access-Control-Allow-Origin: http://www.example.com
Where http://www.example.com
is your website address. You should check your settings on chatforyoursite.com
to see if you can enable this - if not their technical support would probably be the best way to resolve this. However to answer your question, you need the remote site to allow your site to access AJAX responses client side.
I suggest this as a clean solution for US numbers.
public static string PhoneNumber(string value)
{
if (string.IsNullOrEmpty(value)) return string.Empty;
value = new System.Text.RegularExpressions.Regex(@"\D")
.Replace(value, string.Empty);
value = value.TrimStart('1');
if (value.Length == 7)
return Convert.ToInt64(value).ToString("###-####");
if (value.Length == 10)
return Convert.ToInt64(value).ToString("###-###-####");
if (value.Length > 10)
return Convert.ToInt64(value)
.ToString("###-###-#### " + new String('#', (value.Length - 10)));
return value;
}
Following suit from the suggestions here, I added an extension method to return a list of the selected items using LINQ for any type that Inherits from System.Web.UI.WebControls.ListControl
.
Every ListControl
object has an Items
property of type ListItemCollection
. ListItemCollection
exposes a collection of ListItems
, each of which have a Selected
property.
public static IEnumerable<ListItem> GetSelectedItems(this ListControl checkBoxList)
{
return from ListItem li in checkBoxList.Items where li.Selected select li;
}
<Extension()> _
Public Function GetSelectedItems(ByVal checkBoxList As ListControl) As IEnumerable(Of ListItem)
Return From li As ListItem In checkBoxList.Items Where li.Selected
End Function
Then, just use like this in either language:
myCheckBoxList.GetSelectedItems()
Files in your project are available to you relative to your src folder. if you know which package or folder myfile.txt will be in, say it is in
----src
--------package1
------------myfile.txt
------------Prog.java
you can specify its path as "src/package1/myfile.txt" from Prog.java
I found it to be pretty nice to do it like this (usage in the view):
@Html.HiddenJsonFor(m => m.TrackingTypes)
Here is the according helper method Extension class:
public static class DataHelpers
{
public static MvcHtmlString HiddenJsonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
return HiddenJsonFor(htmlHelper, expression, (IDictionary<string, object>) null);
}
public static MvcHtmlString HiddenJsonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
{
return HiddenJsonFor(htmlHelper, expression, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
public static MvcHtmlString HiddenJsonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes)
{
var name = ExpressionHelper.GetExpressionText(expression);
var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var tagBuilder = new TagBuilder("input");
tagBuilder.MergeAttributes(htmlAttributes);
tagBuilder.MergeAttribute("name", name);
tagBuilder.MergeAttribute("type", "hidden");
var json = JsonConvert.SerializeObject(metadata.Model);
tagBuilder.MergeAttribute("value", json);
return MvcHtmlString.Create(tagBuilder.ToString());
}
}
It is not super-sofisticated, but it solves the problem of where to put it (in Controller or in view?) The answer is obviously: neither ;)
Use UIAlertController instead of UIAlertView
-(void)showMessage:(NSString*)message withTitle:(NSString *)title
{
UIAlertController * alert= [UIAlertController
alertControllerWithTitle:title
message:message
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
//do something when click button
}];
[alert addAction:okAction];
UIViewController *vc = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
[vc presentViewController:alert animated:YES completion:nil];
}
The Python standard library comes with an e-mail parsing function: email.utils.parseaddr()
.
It returns a two-tuple containing the real name and the actual address parts of the e-mail:
>>> from email.utils import parseaddr
>>> parseaddr('[email protected]')
('', '[email protected]')
>>> parseaddr('Full Name <[email protected]>')
('Full Name', '[email protected]')
>>> parseaddr('"Full Name with quotes and <[email protected]>" <[email protected]>')
('Full Name with quotes and <[email protected]>', '[email protected]')
And if the parsing is unsuccessful, it returns a two-tuple of empty strings:
>>> parseaddr('[invalid!email]')
('', '')
An issue with this parser is that it's accepting of anything that is considered as a valid e-mail address for RFC-822 and friends, including many things that are clearly not addressable on the wide Internet:
>>> parseaddr('invalid@example,com') # notice the comma
('', 'invalid@example')
>>> parseaddr('invalid-email')
('', 'invalid-email')
So, as @TokenMacGuy put it, the only definitive way of checking an e-mail address is to send an e-mail to the expected address and wait for the user to act on the information inside the message.
However, you might want to check for, at least, the presence of an @-sign on the second tuple element, as @bvukelic suggests:
>>> '@' in parseaddr("invalid-email")[1]
False
If you want to go a step further, you can install the dnspython project and resolve the mail servers for the e-mail domain (the part after the '@'), only trying to send an e-mail if there are actual MX
servers:
>>> from dns.resolver import query
>>> domain = 'foo@[email protected]'.rsplit('@', 1)[-1]
>>> bool(query(domain, 'MX'))
True
>>> query('example.com', 'MX')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
[...]
dns.resolver.NoAnswer
>>> query('not-a-domain', 'MX')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
[...]
dns.resolver.NXDOMAIN
You can catch both NoAnswer
and NXDOMAIN
by catching dns.exception.DNSException
.
And Yes, foo@[email protected]
is a syntactically valid address. Only the last @
should be considered for detecting where the domain part starts.
Format to send a WhatsApp message to a specific number (updated Nov 2018)
<a href="https://wa.me/whatsappphonenumber/?text=urlencodedtext"></a>
where
whatsappphonenumber is a full phone number in international format
urlencodedtext is the URL-encoded pre-filled message.
Create a link with a pre-filled message that will automatically appear in the text field of a chat, to be sent to a specific number
Send I am interested in your car for sale to +001-(555)1234567
https://wa.me/15551234567?text=I%20am%20interested%20in%20your%20car%20for%20sale
Note :
Use: https://wa.me/15551234567
Don't use: https://wa.me/+001-(555)1234567
Create a link with just a pre-filled message that will automatically appear in the text field of a chat, number will be chosen by the user
Send I am enquiring about the apartment listing
https://wa.me/?text=I%20am%20enquiring%20about%20the%20apartment%20listing
After clicking on the link, user will be shown a list of contacts they can send the pre-filled message to.
For more information, see https://www.whatsapp.com/faq/en/general/26000030
--
P.S : Older format (before updation) for reference
<a href="https://api.whatsapp.com/send?phone=whatsappphonenumber&text=urlencodedtext"></a>
please try following to generate
function addRow()
{
var e1 = document.createElement("input");
e1.type = "text";
e1.name = "name1";
var cont = document.getElementById("content")
cont.appendChild(e1);
}
I had the same problem while working on an installer script. I took a look at what the bin/activate_this.py did and reversed it.
Example:
#! /usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
# Path to virtualenv
venv_path = os.path.join('/home', 'sixdays', '.virtualenvs', 'test32')
# Save old values
old_os_path = os.environ['PATH']
old_sys_path = list(sys.path)
old_sys_prefix = sys.prefix
def deactivate():
# Change back by setting values to starting values
os.environ['PATH'] = old_os_path
sys.prefix = old_sys_prefix
sys.path[:0] = old_sys_path
# Activate the virtualenvironment
activate_this = os.path.join(venv_path, 'bin/activate_this.py')
execfile(activate_this, dict(__file__=activate_this))
# Print list of pip packages for virtualenv for example purpose
import pip
print str(pip.get_installed_distributions())
# Unload pip module
del pip
# Deactivate/switch back to initial interpreter
deactivate()
# Print list of initial environment pip packages for example purpose
import pip
print str(pip.get_installed_distributions())
I am not 100% sure if it works as intended. I may have missed something completely.
That's not exactly what I had in mind. What do you do if you have a generic type to only be known at runtime?
public MyDTO toObject() {
try {
var methodInfo = MethodBase.GetCurrentMethod();
if (methodInfo.DeclaringType != null) {
var fullName = methodInfo.DeclaringType.FullName + "." + this.dtoName;
Type type = Type.GetType(fullName);
if (type != null) {
var obj = JsonConvert.DeserializeObject(payload);
//var obj = JsonConvert.DeserializeObject<type.MemberType.GetType()>(payload); // <--- type ?????
...
}
}
// Example for java.. Convert this to C#
return JSONUtil.fromJSON(payload, Class.forName(dtoName, false, getClass().getClassLoader()));
} catch (Exception ex) {
throw new ReflectInsightException(MethodBase.GetCurrentMethod().Name, ex);
}
}
$query = "INSERT INTO myTable VALUES (NULL,'Fname', 'Lname', 'Website')";
Just leaving the value of the AI primary key NULL
will assign an auto incremented value.
[ -z "${DEPLOY_ENV}" ]
checks whether DEPLOY_ENV
has length equal to zero. So you could run:
if [[ -z "${DEPLOY_ENV}" ]]; then
MY_SCRIPT_VARIABLE="Some default value because DEPLOY_ENV is undefined"
else
MY_SCRIPT_VARIABLE="${DEPLOY_ENV}"
fi
# or using a short-hand version
[[ -z "${DEPLOY_ENV}" ]] && MyVar='default' || MyVar="${DEPLOY_ENV}"
# or even shorter use
MyVar="${DEPLOY_ENV:-default_value}"
The standard solution:
expr $d1 - $d2
You can also do:
echo $(( d1 - d2 ))
but beware that this will treat 07
as an octal number! (so 07
is the same as 7
, but 010
is different than 10
).
You cannot concatenate raw strings like this. operator+
only works with two std::string
objects or with one std::string
and one raw string (on either side of the operation).
std::string s("...");
s + s; // OK
s + "x"; // OK
"x" + s; // OK
"x" + "x" // error
The easiest solution is to turn your raw string into a std::string
first:
"Do you feel " + std::string(AGE) + " years old?";
Of course, you should not use a macro in the first place. C++ is not C. Use const
or, in C++11 with proper compiler support, constexpr
.
I would use nearly the same way but with list as buffer for read integers:
static Object[] readFile(String fileName) {
Scanner scanner = new Scanner(new File(fileName));
List<Integer> tall = new ArrayList<Integer>();
while (scanner.hasNextInt()) {
tall.add(scanner.nextInt());
}
return tall.toArray();
}
In my case, VS 2019 on Windows 10 x64,
I followed mostly what it was said in the answers but pasted rc.exe
and rcdll.dll
from C:\Program Files (x86)\Windows Kits\10\bin\10.0.18362.0\x86
to C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin
, which is where link.exe
is.
No one suggests threading? Writing the smaller files looks like text book example of where threads are useful. Set up a bunch of threads to create the smaller files. this way, you can create them all in parallel and you don't need to wait for each one to finish. My assumption is that creating the files(disk operation) will take WAY longer than splitting up the data. and of course you should verify first that a sequential approach is not adequate.
There's a GROUP Aggregate function, GROUP_CONCAT.
Thank you #DangerDave this solved my problem on Magento 2, and this is how I did
I am on a vps
root@myvps [~]# cd /var/lib/mysql/mydatabasename/
root@myvps [~]# ls
check for tables with no .frm fie (only .idb) and delete them,
rm customer_grid_flat.ibd
System will regenerate tables after running index:reindex command
For two or multiple arrays, this simple and clean utility method can be used:
/**
* Append the given byte arrays to one big array
*
* @param arrays The arrays to append
* @return The complete array containing the appended data
*/
public static final byte[] append(final byte[]... arrays) {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
if (arrays != null) {
for (final byte[] array : arrays) {
if (array != null) {
out.write(array, 0, array.length);
}
}
}
return out.toByteArray();
}
There are at least five different ways to rename specific columns in pandas, and I have listed them below along with links to the original answers. I also timed these methods and found them to perform about the same (though YMMV depending on your data set and scenario). The test case below is to rename columns A
M
N
Z
to A2
M2
N2
Z2
in a dataframe with columns A
to Z
containing a million rows.
# Import required modules
import numpy as np
import pandas as pd
import timeit
# Create sample data
df = pd.DataFrame(np.random.randint(0,9999,size=(1000000, 26)), columns=list('ABCDEFGHIJKLMNOPQRSTUVWXYZ'))
# Standard way - https://stackoverflow.com/a/19758398/452587
def method_1():
df_renamed = df.rename(columns={'A': 'A2', 'M': 'M2', 'N': 'N2', 'Z': 'Z2'})
# Lambda function - https://stackoverflow.com/a/16770353/452587
def method_2():
df_renamed = df.rename(columns=lambda x: x + '2' if x in ['A', 'M', 'N', 'Z'] else x)
# Mapping function - https://stackoverflow.com/a/19758398/452587
def rename_some(x):
if x=='A' or x=='M' or x=='N' or x=='Z':
return x + '2'
return x
def method_3():
df_renamed = df.rename(columns=rename_some)
# Dictionary comprehension - https://stackoverflow.com/a/58143182/452587
def method_4():
df_renamed = df.rename(columns={col: col + '2' for col in df.columns[
np.asarray([i for i, col in enumerate(df.columns) if 'A' in col or 'M' in col or 'N' in col or 'Z' in col])
]})
# Dictionary comprehension - https://stackoverflow.com/a/38101084/452587
def method_5():
df_renamed = df.rename(columns=dict(zip(df[['A', 'M', 'N', 'Z']], ['A2', 'M2', 'N2', 'Z2'])))
print('Method 1:', timeit.timeit(method_1, number=10))
print('Method 2:', timeit.timeit(method_2, number=10))
print('Method 3:', timeit.timeit(method_3, number=10))
print('Method 4:', timeit.timeit(method_4, number=10))
print('Method 5:', timeit.timeit(method_5, number=10))
Output:
Method 1: 3.650640267
Method 2: 3.163998427
Method 3: 2.998530871
Method 4: 2.9918436889999995
Method 5: 3.2436501520000007
Use the method that is most intuitive to you and easiest for you to implement in your application.
A jQuery version of the iframe answers:
function download(files) {
$.each(files, function(key, value) {
$('<iframe></iframe>')
.hide()
.attr('src', value)
.appendTo($('body'))
.load(function() {
var that = this;
setTimeout(function() {
$(that).remove();
}, 100);
});
});
}
I have found the answer and solution to this problem. Before, I did not know that php.ini resides where in wordpress files. Now I have found that file in wp-admin directory where I placed the code
post_max_size 33M
upload_max_filesize 32M
then it worked. It increases the upload file size for my worpdress website. But, it is the same 2M as was before on cPanel.
Something important when dealing with outliers is that one should try to use estimators as robust as possible. The mean of a distribution will be biased by outliers but e.g. the median will be much less.
Building on eumiro's answer:
def reject_outliers(data, m = 2.):
d = np.abs(data - np.median(data))
mdev = np.median(d)
s = d/mdev if mdev else 0.
return data[s<m]
Here I have replace the mean with the more robust median and the standard deviation with the median absolute distance to the median. I then scaled the distances by their (again) median value so that m
is on a reasonable relative scale.
Note that for the data[s<m]
syntax to work, data
must be a numpy array.
Inspired in this answer I came up with a bit more object-oriented solution.
This is only valid if you're intending to read characters
You can override BufferedReader and implement something like this:
public class SafeBufferedReader extends BufferedReader{
private long millisTimeout;
( . . . )
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
try {
waitReady();
} catch(IllegalThreadStateException e) {
return 0;
}
return super.read(cbuf, off, len);
}
protected void waitReady() throws IllegalThreadStateException, IOException {
if(ready()) return;
long timeout = System.currentTimeMillis() + millisTimeout;
while(System.currentTimeMillis() < timeout) {
if(ready()) return;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
break; // Should restore flag
}
}
if(ready()) return; // Just in case.
throw new IllegalThreadStateException("Read timed out");
}
}
Here's an almost complete example.
I'm returning 0 on some methods, you should change it to -2 to meet your needs, but I think that 0 is more suitable with BufferedReader contract. Nothing wrong happened, it just read 0 chars. readLine method is a horrible performance killer. You should create a entirely new BufferedReader if you actually want to use readLine. Right now, it is not thread safe. If someone invokes an operation while readLines is waiting for a line, it will produce unexpected results
I don't like returning -2 where I am. I'd throw an exception because some people may just be checking if int < 0 to consider EOS. Anyway, those methods claim that "can't block", you should check if that statement is actually true and just don't override'em.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.nio.CharBuffer;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
/**
*
* readLine
*
* @author Dario
*
*/
public class SafeBufferedReader extends BufferedReader{
private long millisTimeout;
private long millisInterval = 100;
private int lookAheadLine;
public SafeBufferedReader(Reader in, int sz, long millisTimeout) {
super(in, sz);
this.millisTimeout = millisTimeout;
}
public SafeBufferedReader(Reader in, long millisTimeout) {
super(in);
this.millisTimeout = millisTimeout;
}
/**
* This is probably going to kill readLine performance. You should study BufferedReader and completly override the method.
*
* It should mark the position, then perform its normal operation in a nonblocking way, and if it reaches the timeout then reset position and throw IllegalThreadStateException
*
*/
@Override
public String readLine() throws IOException {
try {
waitReadyLine();
} catch(IllegalThreadStateException e) {
//return null; //Null usually means EOS here, so we can't.
throw e;
}
return super.readLine();
}
@Override
public int read() throws IOException {
try {
waitReady();
} catch(IllegalThreadStateException e) {
return -2; // I'd throw a runtime here, as some people may just be checking if int < 0 to consider EOS
}
return super.read();
}
@Override
public int read(char[] cbuf) throws IOException {
try {
waitReady();
} catch(IllegalThreadStateException e) {
return -2; // I'd throw a runtime here, as some people may just be checking if int < 0 to consider EOS
}
return super.read(cbuf);
}
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
try {
waitReady();
} catch(IllegalThreadStateException e) {
return 0;
}
return super.read(cbuf, off, len);
}
@Override
public int read(CharBuffer target) throws IOException {
try {
waitReady();
} catch(IllegalThreadStateException e) {
return 0;
}
return super.read(target);
}
@Override
public void mark(int readAheadLimit) throws IOException {
super.mark(readAheadLimit);
}
@Override
public Stream<String> lines() {
return super.lines();
}
@Override
public void reset() throws IOException {
super.reset();
}
@Override
public long skip(long n) throws IOException {
return super.skip(n);
}
public long getMillisTimeout() {
return millisTimeout;
}
public void setMillisTimeout(long millisTimeout) {
this.millisTimeout = millisTimeout;
}
public void setTimeout(long timeout, TimeUnit unit) {
this.millisTimeout = TimeUnit.MILLISECONDS.convert(timeout, unit);
}
public long getMillisInterval() {
return millisInterval;
}
public void setMillisInterval(long millisInterval) {
this.millisInterval = millisInterval;
}
public void setInterval(long time, TimeUnit unit) {
this.millisInterval = TimeUnit.MILLISECONDS.convert(time, unit);
}
/**
* This is actually forcing us to read the buffer twice in order to determine a line is actually ready.
*
* @throws IllegalThreadStateException
* @throws IOException
*/
protected void waitReadyLine() throws IllegalThreadStateException, IOException {
long timeout = System.currentTimeMillis() + millisTimeout;
waitReady();
super.mark(lookAheadLine);
try {
while(System.currentTimeMillis() < timeout) {
while(ready()) {
int charInt = super.read();
if(charInt==-1) return; // EOS reached
char character = (char) charInt;
if(character == '\n' || character == '\r' ) return;
}
try {
Thread.sleep(millisInterval);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Restore flag
break;
}
}
} finally {
super.reset();
}
throw new IllegalThreadStateException("readLine timed out");
}
protected void waitReady() throws IllegalThreadStateException, IOException {
if(ready()) return;
long timeout = System.currentTimeMillis() + millisTimeout;
while(System.currentTimeMillis() < timeout) {
if(ready()) return;
try {
Thread.sleep(millisInterval);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Restore flag
break;
}
}
if(ready()) return; // Just in case.
throw new IllegalThreadStateException("read timed out");
}
}
See this example: http://www.p2e.dk/diverse/detectPaste.htm
It essentialy tracks every change with oninput event and then checks if it’s a paste by string comparison. Oh, and in IE there’s an onpaste event. So:
$ (something).bind ("input paste", function (e) {
// check for paste as in example above and
// do something
})
N is input number
case 1: 0<=N<=127 answer=N;
case 2: 128<=N<=256 answer=N-256
case 3: N>256
temp1=N/256;
temp2=N-temp*256;
if temp2<=127 then answer=temp2;
else if temp2>=128 then answer=temp2-256;
case 4: negative number input
do same procedure.just change the sign of the solution
This is an old question, but it's lacking a java8-friendly answer. Here are some ways of reverse-iterating the list, with the help of the Streaming API:
List<Integer> list = new ArrayList<Integer>(Arrays.asList(1, 3, 3, 7, 5));
list.stream().forEach(System.out::println); // 1 3 3 7 5
int size = list.size();
ListIterator<Integer> it = list.listIterator(size);
Stream.generate(it::previous).limit(size)
.forEach(System.out::println); // 5 7 3 3 1
ListIterator<Integer> it2 = list.listIterator(size);
Stream.iterate(it2.previous(), i -> it2.previous()).limit(size)
.forEach(System.out::println); // 5 7 3 3 1
// If list is RandomAccess (i.e. an ArrayList)
IntStream.range(0, size).map(i -> size - i - 1).map(list::get)
.forEach(System.out::println); // 5 7 3 3 1
// If list is RandomAccess (i.e. an ArrayList), less efficient due to sorting
IntStream.range(0, size).boxed().sorted(Comparator.reverseOrder())
.map(list::get).forEach(System.out::println); // 5 7 3 3 1
Yet another solution:
string s = "??"; // or whatever
if (chldNode.Attributes.Cast<XmlAttribute>()
.Select(x => x.Value)
.Contains(attributeName))
s = xe.Attributes[attributeName].Value;
It also avoids the exception when the expected attribute attributeName
actually doesn't exist.
Call the toISOString()
method:
var dt = new Date("30 July 2010 15:05 UTC");
document.write(dt.toISOString());
// Output:
// 2010-07-30T15:05:00.000Z
You can use HttpClient and HttpPost to build and send the request.
HttpClient client= new DefaultHttpClient();
HttpPost request = new HttpPost("www.example.com");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("paramName", "paramValue"));
request.setEntity(new UrlEncodedFormEntity(pairs ));
HttpResponse resp = client.execute(request);
Using suggestions from others, I think I got it to work:
(using SDK v1 R2)
It's not perfect, since i need to delete the entire conversation, but for our purposes, it's a sufficient compromise as we will at least know all messages will be looked at and verified. Our flow will probably need to then listen for the message, capture for the message we want, do a query to get the thread_id of the recently inbounded message and do the delete() call.
In our Activity:
Uri uriSms = Uri.parse("content://sms/inbox");
Cursor c = getContentResolver().query(uriSms, null,null,null,null);
int id = c.getInt(0);
int thread_id = c.getInt(1); //get the thread_id
getContentResolver().delete(Uri.parse("content://sms/conversations/" + thread_id),null,null);
Note: I wasn't able to do a delete on content://sms/inbox/ or content://sms/all/
Looks like the thread takes precedence, which makes sense, but the error message only emboldened me to be angrier. When trying the delete on sms/inbox/ or sms/all/, you will probably get:
java.lang.IllegalArgumentException: Unknown URL
at com.android.providers.telephony.SmsProvider.delete(SmsProvider.java:510)
at android.content.ContentProvider$Transport.delete(ContentProvider.java:149)
at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:149)
For additional reference too, make sure to put this into your manifest for your intent receiver:
<receiver android:name=".intent.MySmsReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"></action>
</intent-filter>
</receiver>
Note the receiver tag does not look like this:
<receiver android:name=".intent.MySmsReceiver"
android:permission="android.permission.RECEIVE_SMS">
When I had those settings, android gave me some crazy permissions exceptions that didn't allow android.phone to hand off the received SMS to my intent. So, DO NOT put that RECEIVE_SMS permission attribute in your intent! Hopefully someone wiser than me can tell me why that was the case.
Starting from Spring Boot version 1.2.0.RELEASE , there is a property you can add to your application.properties
to set a default date format to all of your classes spring.jackson.date-format
.
For your date format example, you would add this line to your properties file:
spring.jackson.date-format=yyyy-MM-dd
I recently had this problem and it ended up being a port issue. My production SQL Server was set up at to be port 1427 instead 1433.
Just change the connection string to be
...data source=MySQLServerName,1427;initial catalog=MyDBName...
Hope this helps anyone who might be seeing this same issue.
The documentation on the Maven site is horrible. What dependencyManagement does is simply move your dependency definitions (version, exclusions, etc) up to the parent pom, then in the child poms you just have to put the groupId and artifactId. That's it (except for parent pom chaining and the like, but that's not really complicated either - dependencyManagement wins out over dependencies at the parent level - but if have a question about that or imports, the Maven documentation is a little better).
After reading all of the 'a', 'b', 'c' garbage on the Maven site and getting confused, I re-wrote their example. So if you had 2 projects (proj1 and proj2) which share a common dependency (betaShared) you could move that dependency up to the parent pom. While you are at it, you can also move up any other dependencies (alpha and charlie) but only if it makes sense for your project. So for the situation outlined in the prior sentences, here is the solution with dependencyManagement in the parent pom:
<!-- ParentProj pom -->
<project>
<dependencyManagement>
<dependencies>
<dependency> <!-- not much benefit defining alpha here, as we only use in 1 child, so optional -->
<groupId>alpha</groupId>
<artifactId>alpha</artifactId>
<version>1.0</version>
<exclusions>
<exclusion>
<groupId>zebra</groupId>
<artifactId>zebra</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>charlie</groupId> <!-- not much benefit defining charlie here, so optional -->
<artifactId>charlie</artifactId>
<version>1.0</version>
<type>war</type>
<scope>runtime</scope>
</dependency>
<dependency> <!-- defining betaShared here makes a lot of sense -->
<groupId>betaShared</groupId>
<artifactId>betaShared</artifactId>
<version>1.0</version>
<type>bar</type>
<scope>runtime</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>
<!-- Child Proj1 pom -->
<project>
<dependencies>
<dependency>
<groupId>alpha</groupId>
<artifactId>alpha</artifactId> <!-- jar type IS DEFAULT, so no need to specify in child projects -->
</dependency>
<dependency>
<groupId>betaShared</groupId>
<artifactId>betaShared</artifactId>
<type>bar</type> <!-- This is not a jar dependency, so we must specify type. -->
</dependency>
</dependencies>
</project>
<!-- Child Proj2 -->
<project>
<dependencies>
<dependency>
<groupId>charlie</groupId>
<artifactId>charlie</artifactId>
<type>war</type> <!-- This is not a jar dependency, so we must specify type. -->
</dependency>
<dependency>
<groupId>betaShared</groupId>
<artifactId>betaShared</artifactId>
<type>bar</type> <!-- This is not a jar dependency, so we must specify type. -->
</dependency>
</dependencies>
</project>
git show
To complete your own answer, the syntax is indeed
git show object
git show $REV:$FILE
git show somebranch:from/the/root/myfile.txt
git show HEAD^^^:test/test.py
The command takes the usual style of revision, meaning you can use any of the following:
HEAD
+ x number of ^
charactersTip It's important to remember that when using "git show
", always specify a path from the root of the repository, not your current directory position.
(Although Mike Morearty mentions that, at least with git 1.7.5.4, you can specify a relative path by putting "./
" at the beginning of the path. For example:
git show HEAD^^:./test.py
)
git restore
With Git 2.23+ (August 2019), you can also use git restore
which replaces the confusing git checkout
command
git restore -s <SHA1> -- afile
git restore -s somebranch -- afile
That would restore on the working tree only the file as present in the "source" (-s
) commit SHA1 or branch somebranch
.
To restore also the index:
git restore -s <SHA1> -SW -- afile
(-SW
: short for --staged --worktree
)
Before git1.5.x, this was done with some plumbing:
git ls-tree <rev>
show a list of one or more 'blob' objects within a commit
git cat-file blob <file-SHA1>
cat a file as it has been committed within a specific revision (similar to svn
cat).
use git ls-tree
to retrieve the value of a given file-sha1
git cat-file -p $(git-ls-tree $REV $file | cut -d " " -f 3 | cut -f 1)::
git-ls-tree
lists the object ID for $file
in revision $REV
, this is cut out of the output and used as an argument to git-cat-file
, which should really be called git-cat-object
, and simply dumps that object to stdout
.
Note: since Git 2.11 (Q4 2016), you can apply a content filter to the git cat-file
output.
See
commit 3214594,
commit 7bcf341 (09 Sep 2016),
commit 7bcf341 (09 Sep 2016), and
commit b9e62f6,
commit 16dcc29 (24 Aug 2016) by Johannes Schindelin (dscho
).
(Merged by Junio C Hamano -- gitster
-- in commit 7889ed2, 21 Sep 2016)
git config diff.txt.textconv "tr A-Za-z N-ZA-Mn-za-m <"
git cat-file --textconv --batch
Note: "git cat-file --textconv
" started segfaulting recently (2017), which has been corrected in Git 2.15 (Q4 2017)
See commit cc0ea7c (21 Sep 2017) by Jeff King (peff
).
(Merged by Junio C Hamano -- gitster
-- in commit bfbc2fc, 28 Sep 2017)