Downloading Wget is not necessary; the .NET Framework has web client classes built in.
$wc = New-Object system.Net.WebClient;
$sms = Read-Host "Enter SMS text";
$sms = [System.Web.HttpUtility]::UrlEncode($sms);
$smsResult = $wc.downloadString("http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$sms&encoding=windows-1255")
You can try this:
For Date:
$date = new DateTime($from_date);
$date = $date->format('d-m-Y');
For Time:
$time = new DateTime($from_date);
$time = $time->format('H:i:s');
I just encountered and solve a similar problem.
First you should check the directory like other threads described. Then you can check whether the Build tool version matches your SDK version.
(e.g. for my project, in build.gradle file, you have:)
android { compileSdkVersion 21 buildToolsVersion "21.1.1" }
and then open you SDK manager, make sure you have the same version of sdk(21.1.1) installed in the selected directoriy:
If not, install it and restart Android Studio. It works for me.
I've also seen other guys saying run Android Studio as administrator would also help:
$request = [System.Net.WebRequest]::Create('http://stackoverflow.com/questions/20259251/powershell-script-to-check-the-status-of-a-url')
$response = $request.GetResponse()
$response.StatusCode
$response.Close()
Assuming you want to read from resources
directory in FileSystem
class.
String file = "dummy.txt";
var path = Paths.get("src/com/company/fs/resources/", file);
System.out.println(path);
System.out.println(Files.readString(path));
Note: Leading .
is not needed.
I've built a function that deals with plotting FFT of real signals. The extra bonus in my function relative to the previous answers is that you get the actual amplitude of the signal.
Also, because of the assumption of a real signal, the FFT is symmetric, so we can plot only the positive side of the x-axis:
import matplotlib.pyplot as plt
import numpy as np
import warnings
def fftPlot(sig, dt=None, plot=True):
# Here it's assumes analytic signal (real signal...) - so only half of the axis is required
if dt is None:
dt = 1
t = np.arange(0, sig.shape[-1])
xLabel = 'samples'
else:
t = np.arange(0, sig.shape[-1]) * dt
xLabel = 'freq [Hz]'
if sig.shape[0] % 2 != 0:
warnings.warn("signal preferred to be even in size, autoFixing it...")
t = t[0:-1]
sig = sig[0:-1]
sigFFT = np.fft.fft(sig) / t.shape[0] # Divided by size t for coherent magnitude
freq = np.fft.fftfreq(t.shape[0], d=dt)
# Plot analytic signal - right half of frequence axis needed only...
firstNegInd = np.argmax(freq < 0)
freqAxisPos = freq[0:firstNegInd]
sigFFTPos = 2 * sigFFT[0:firstNegInd] # *2 because of magnitude of analytic signal
if plot:
plt.figure()
plt.plot(freqAxisPos, np.abs(sigFFTPos))
plt.xlabel(xLabel)
plt.ylabel('mag')
plt.title('Analytic FFT plot')
plt.show()
return sigFFTPos, freqAxisPos
if __name__ == "__main__":
dt = 1 / 1000
# Build a signal within Nyquist - the result will be the positive FFT with actual magnitude
f0 = 200 # [Hz]
t = np.arange(0, 1 + dt, dt)
sig = 1 * np.sin(2 * np.pi * f0 * t) + \
10 * np.sin(2 * np.pi * f0 / 2 * t) + \
3 * np.sin(2 * np.pi * f0 / 4 * t) +\
7.5 * np.sin(2 * np.pi * f0 / 5 * t)
# Result in frequencies
fftPlot(sig, dt=dt)
# Result in samples (if the frequencies axis is unknown)
fftPlot(sig)
I have managed to to do it in a way. Perform all the steps as referenced by Michal Rowicki above.
Tools
bar above that states Code
and select Instant Reverse...
from the drop down menu with Java
language(or other)Then it should appear on your screen and customize it as you wish
However i do not know if the plugin in Android Studio was necessary nevertheless it has worked in a way for me.
Like sgibb said it was an if problem, it had nothing to do with | or ||.
Here is another way to solve your problem:
for (i in 1:nrow(trip)) {
if(trip$Ref.y[i]=='G' & trip$Variant.y[i]=='T'|trip$Ref.y[i]=='C' & trip$Variant.y[i]=='A') {
trip[i, 'mutType'] <- "G:C to T:A"
}
else if(trip$Ref.y[i]=='G' & trip$Variant.y[i]=='C'|trip$Ref.y[i]=='C' & trip$Variant.y[i]=='G') {
trip[i, 'mutType'] <- "G:C to C:G"
}
else if(trip$Ref.y[i]=='G' & trip$Variant.y[i]=='A'|trip$Ref.y[i]=='C' & trip$Variant.y[i]=='T') {
trip[i, 'mutType'] <- "G:C to A:T"
}
else if(trip$Ref.y[i]=='A' & trip$Variant.y[i]=='T'|trip$Ref.y[i]=='T' & trip$Variant.y[i]=='A') {
trip[i, 'mutType'] <- "A:T to T:A"
}
else if(trip$Ref.y[i]=='A' & trip$Variant.y[i]=='G'|trip$Ref.y[i]=='T' & trip$Variant.y[i]=='C') {
trip[i, 'mutType'] <- "A:T to G:C"
}
else if(trip$Ref.y[i]=='A' & trip$Variant.y[i]=='C'|trip$Ref.y[i]=='T' & trip$Variant.y[i]=='G') {
trip[i, 'mutType'] <- "A:T to C:G"
}
}
You do not need the latex2exp
package to do what you wanted to do. The following code would do the trick.
ggplot(smr, aes(Fuel.Rate, Eng.Speed.Ave., color=Eng.Speed.Max.)) +
geom_point() +
labs(title=expression("Fuel Efficiency"~(alpha*Omega)),
color=expression(alpha*Omega), x=expression(Delta~price))
Also, some comments (unanswered as of this point) asked about putting an asterisk (*) after a Greek letter. expression(alpha~"*")
works, so I suggest giving it a try.
More comments asked about getting ? Price
and I find the most straightforward way to achieve that is expression(Delta~price))
. If you need to add something before the Greek letter, you can also do this:
expression(Indicative~Delta~price)
which gets you:
I am not going to use this pattern in my own code since I'm not a big fan of using global variables. However, in a pinch it will work.
User is a promisified Mongoose model.
var globalVar = '';
User.findAsync({}).then(function(users){
globalVar = users;
}).then(function(){
console.log(globalVar);
});
As stated. Gradients aren't currently supported with CSS Transitions. But you could work around it in some cases by setting one of the colors to transparent, so that the background-color of some other wrapping element shines through, and transition that instead.
I think you want to cast your dt
to a date
and fix the format of your date literal:
SELECT *
FROM table
WHERE dt::date = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD
Or the standard version:
SELECT *
FROM table
WHERE CAST(dt AS DATE) = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD
The extract
function doesn't understand "date" and it returns a number.
This trick only requires one command: type net session
into the command prompt.
If you are NOT an admin, you get an access is denied message.
System error 5 has occurred.
Access is denied.
If you ARE an admin, you get a different message, the most common being:
There are no entries in the list.
From MS Technet:
Used without parameters, net session displays information about all sessions with the local computer.
At page translation time, the content of the file given in the include directive is ‘pasted’ as it is, in the place where the JSP include directive is used. Then the source JSP page is converted into a java servlet class. The included file can be a static resource or a JSP page. Generally, JSP include directive is used to include header banners and footers.
Syntax for include a jsp file:
<%@ include file="relative url">
Example
<%@include file="page_name.jsp" %>
In recent browsers you can use:
Object.keys(obj.Data).length
See MDN
For older browsers, use the for-in
loop in Michael Geary's answer.
This worked for me finally : RUN -> RUN CONFIGURATIONS -> DELETE THE RUN CONFIGURATION CLOSE ECLIPSE REOPEN ECLIPSE CREATE RUN CONFIGURATION AGAIN.
Tadaaaa !! It works
Arrays.stream(ints).forEach(list::add);
This basically does 1 (iterate over the array) with 2 (using Java 8). (with 1 and 2 referring to your original question)
After your databind:
drpList.Items.Insert(0, new ListItem(String.Empty, String.Empty));
drpList.SelectedIndex = 0;
...and remember there is no MySQLdb for python3.x
(I know the question is about python2.x but google rates this post quite high)
EDIT: As stated in the comments, there's a MySQLdb's fork that adds Python 3 support: github.com/PyMySQL/mysqlclient-python
I had the same issue, only using a .pug
file (similar to .jade
). I realized that it was also a space issue, following the end of my closing parentheses. In my example, you need to highlight the text after (placeholder="YOUR MESSAGE")
to see:
BEFORE:
form.form-horizontal(method='POST')
.form-group
textarea.form-control(placeholder="YOUR MESSAGE")
.form-group
button.btn.btn-primary(type='submit') SUBMIT
AFTER:
form.form-horizontal(method='POST')
.form-group
textarea.form-control(placeholder="YOUR MESSAGE")
.form-group
button.btn.btn-primary(type='submit') SUBMIT
If you dont have SDK or you are setting up 3rd party app here is another way:
SELECT id FROM table1
WHERE YEARWEEK(date) = YEARWEEK(NOW() - INTERVAL 1 WEEK)
I use the YEARWEEK function specifically to go back to the prior whole calendar week (as opposed to 7 days before today). YEARWEEK also allows a second argument that will set the start of the week or determine how the first/last week of the year are handled. YEARWEEK lets you to keep the number of weeks to go back/forward in a single variable, and will not include the same week number from prior/future years, and it's far shorter than most of the other answers on here.
@Matt Dodges answer put me on the right track. Thanks again for all the answers, which helped a lot of guys in the mean time. Got it working like this:
SELECT *
FROM feeds f
LEFT JOIN artists a ON a.artist_id = (
SELECT artist_id
FROM feeds_artists fa
WHERE fa.feed_id = f.id
LIMIT 1
)
WHERE f.id = '13815'
Perhaps it is late for the party. But there is an alternative solution for this is to use ApiMultipartFormFormatter plugin.
This plugin helps you to receive the multipart/formdata content as ASP.NET Core does.
In the github page, demo is already provided.
Because the enum can be an integral size of varying size (the compiler decides which size a given enum has), the pointer to the enum can also have varying size, since it's an integral type (chars have pointers of a different size on some platforms for instance).
So the compiler can't even let you forward-declare the enum and user a pointer to it, because even there, it needs the size of the enum.
You will have to use the fluent API to do this.
Try adding the following to your DbContext
:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasOptional(a => a.UserDetail)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
}
On macos you can do
ping --apple-time 127.0.0.1
The output looks like
16:07:11.315419 64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.064 ms
16:07:12.319933 64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.157 ms
16:07:13.322766 64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.066 ms
16:07:14.324649 64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.148 ms
16:07:15.328743 64 bytes from 127.0.0.1: icmp_seq=4 ttl=64 time=0.092 ms
If you need to show Form2
as a modal dialog, from within Form1
do:
var form2 = new Form2();
if (form2.ShowDialog() == DialogResult.OK)
{
// process results here
}
A modal dialog will retain focus while it is open; it will set the parent windows (Form1
) "in the background" until it is closed, which is quite a common practice for settings windows.
You can simply get it in the format you want.
String date = String.valueOf(android.text.format.DateFormat.format("dd-MM-yyyy", new java.util.Date()));
(I don't have enough rep points to add a comment, but I want to add some clarity on the answers here)
Application.AskToUpdateLinks = False is probably not what you want.
If set to False, then MS Excel will attempt to update the links automatically it just won't prompt the user beforehand, sorta counter-intuitive.
The correct solution, if you're looking to open a file without updating links should be:
Workbook.Open(UpdateLinks:=0)
Related link: Difference in AskToUpdateLinks=False and UpdateLinks:=0
$Query_String = explode("&", explode("?", $_SERVER['REQUEST_URI'])[1] );
var_dump($Query_String)
Array ( [ 0] => link=www.google.com )
You can try the services of https://www.geoip-db.com They provide a JSON or JSONP-callback solution.
<?php
$json = file_get_contents("https://www.geoip-db.com/json");
$data = json_decode($json);
print $data->country_code . "<br>";
print $data->country_name . "<br>";
print $data->state . "<br>";
print $data->city . "<br>";
print $data->postal . "<br>";
print $data->latitude . "<br>";
print $data->longitude . "<br>";
print $data->IPv4 . "<br>";
?>
Does that work in IE6?
No, IE6 does not support attribute selectors at all, cf. CSS Compatibility and Internet Explorer.
You might find How to workaround: IE6 does not support CSS “attribute” selectors worth the read.
EDIT
If you are to ignore IE6, you could do (CSS2.1):
input[type=submit][disabled=disabled],
button[disabled=disabled] {
...
}
CSS3 (IE9+):
input[type=submit]:disabled,
button:disabled {
...
}
You can substitute [disabled=disabled]
(attribute value) with [disabled]
(attribute presence).
Peter Steinberger just tweeted about the private notification UIWindowFirstResponderDidChangeNotification
, which you can observe if you want to watch the firstResponder change.
In MySQL Workbench:
Left-hand side navigator > Management > Client Connections
It gives you the option to kill queries and connections.
Note: this is not TOAD like the OP asked, but MySQL Workbench users like me may end up here
.NET 5 will be a unified version of all .NET variants coming in November 2020, so there will be no need to choose between variants anymore.
EDIT: Sorry, when writing this answer I was thinking about submit buttons in the general sense. The answer below is not about multiple type="submit"
buttons, as it leaves only one type="submit"
and change the other to type="button"
. I leave the answer here as reference in case helps someone that can change the type
in their form:
To determine what button is pressed when hitting enter, you can mark it up with type="submit"
, and the other buttons mark them with type="button"
. For example:
<input type="button" value="Cancel" />
<input type="submit" value="Submit" />
In IntelliJ, the default maven compiler version is less than version 5, which is not supported, so we have to manually change the version of the maven compiler.
We have two ways to define version.
First way:
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
Second way:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
Use @Kristian Antonsen's answer, or you can use:
$('button').click(function() {
preventDefault();
captureForm();
});
As a noobie to Threading, it took me a long time to understand how to implement Mateusz Kobos's code (above). Here's a clarified version to help understand how to use it.
#!/usr/bin/env python
import sys
import threading
import Queue
class ExThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.__status_queue = Queue.Queue()
def run_with_exception(self):
"""This method should be overriden."""
raise NotImplementedError
def run(self):
"""This method should NOT be overriden."""
try:
self.run_with_exception()
except Exception:
self.__status_queue.put(sys.exc_info())
self.__status_queue.put(None)
def wait_for_exc_info(self):
return self.__status_queue.get()
def join_with_exception(self):
ex_info = self.wait_for_exc_info()
if ex_info is None:
return
else:
raise ex_info[1]
class MyException(Exception):
pass
class MyThread(ExThread):
def __init__(self):
ExThread.__init__(self)
# This overrides the "run_with_exception" from class "ExThread"
# Note, this is where the actual thread to be run lives. The thread
# to be run could also call a method or be passed in as an object
def run_with_exception(self):
# Code will function until the int
print "sleeping 5 seconds"
import time
for i in 1, 2, 3, 4, 5:
print i
time.sleep(1)
# Thread should break here
int("str")
# I'm honestly not sure why these appear here? So, I removed them.
# Perhaps Mateusz can clarify?
# thread_name = threading.current_thread().name
# raise MyException("An error in thread '{}'.".format(thread_name))
if __name__ == '__main__':
# The code lives in MyThread in this example. So creating the MyThread
# object set the code to be run (but does not start it yet)
t = MyThread()
# This actually starts the thread
t.start()
print
print ("Notice 't.start()' is considered to have completed, although"
" the countdown continues in its new thread. So you code "
"can tinue into new processing.")
# Now that the thread is running, the join allows for monitoring of it
try:
t.join_with_exception()
# should be able to be replace "Exception" with specific error (untested)
except Exception, e:
print
print "Exceptioon was caught and control passed back to the main thread"
print "Do some handling here...or raise a custom exception "
thread_name = threading.current_thread().name
e = ("Caught a MyException in thread: '" +
str(thread_name) +
"' [" + str(e) + "]")
raise Exception(e) # Or custom class of exception, such as MyException
struct var e2 address pushed as arg to callee stack and values gets assigned there. In fact, get() returns e2's address in eax reg. This works like call by reference.
webView.setBackgroundColor(Color.TRANSPARENT)
before or after loadUrl()
/loadData()
.android:hardwareAccelerated="false"
in the manifest.Tested on IceCream Sandwich
<div style="width:100%;">
<div style="margin-left:45px;">
<asp:TextBox ID="txtTitle" runat="server" Width="100%"></asp:TextBox><br />
</div>
</div>
As you explicitly state that you want obscurity not security, we'll avoid reprimanding you for the weakness of what you suggest :)
So, using PyCrypto:
import base64
from Crypto.Cipher import AES
msg_text = b'test some plain text here'.rjust(32)
secret_key = b'1234567890123456'
cipher = AES.new(secret_key,AES.MODE_ECB) # never use ECB in strong systems obviously
encoded = base64.b64encode(cipher.encrypt(msg_text))
print(encoded)
decoded = cipher.decrypt(base64.b64decode(encoded))
print(decoded)
If someone gets a hold of your database and your code base, they will be able to decode the encrypted data. Keep your secret_key
safe!
I found this worked in my scenario.
The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
$.get("urlToCheck.com").done(function () {
alert("success");
}).fail(function () {
alert("failed.");
});
Why not just use substring... string.substring(0, 7);
The first argument (0) is the starting point. The second argument (7) is the ending point (exclusive). More info here.
var string = "this is a string";
var length = 7;
var trimmedString = string.substring(0, length);
hmm. why don't you use onClick()
<select id="mySelect" onChange="enable();">
<option onClick="disable();">No</option>
<option onClick="enable();">Yes</option>
</select>
If you still need to do this, I ran across the same problem. Somehow, EDGE renders all the scripts even if they are not via HTTP, HTTPS etc... Open the html/js file directly from the filesystem with Edge, and it will work.
You can use javascript Number method to parse it to an number,
var num=Number (num_str);
For anyone else ever looking for an IIS WCF error 413 : Request entity to large and using a WCF service in Sharepoint, this is the information for you. The settings in the application host and web.config suggested in other sites/posts don't work in SharePoint if using the MultipleBaseAddressBasicHttpBindingServiceHostFactory. You can use SP Powershell to get the SPWebService.Content service, create a new SPWcvSettings object and update the settings as above for your service (they won't exist). Remember to just use the name of the service (e.g. [yourservice.svc]) when creating and adding the settings. See this site for more info https://robertsep.wordpress.com/2010/12/21/set-maximum-upload-filesize-sharepoint-wcf-service
I think you haven't messed up yet. Try:
git reset HEAD^
This will bring the dir to state before you've made the commit, HEAD^
means the parent of the current commit (the one you don't want anymore), while keeping changes from it (unstaged).
On Windows pip3
should be in the Scripts
path of your Python installation:
C:\path\to\python\Scripts\pip3
Use:
where python
to find out where your Python executable(s) is/are located. The result should look like this:
C:\path\to\python\python.exe
or:
C:\path\to\python\python3.exe
You can check if pip3
works with this absolute path:
C:\path\to\python\Scripts\pip3
if yes, add C:\path\to\python\Scripts
to your environmental variable PATH
.
Everybody seems to refer to date being a column in the table.
I dont think this is good practice. The word date might just be a keyword in some coding language (maybe Oracle) so please change the columnname date to maybe JDate.
So will the following work better:
SELECT * FROM jokes WHERE JDate >= CURRENT_DATE() ORDER BY JScore DESC;
So we have a table called Jokes with columns JScore and JDate.
Thanks, MEnnabah, just to add to your code where you are missing the =
sign in the declaration statement:
let someImageView: UIImageView = {
let theImageView = UIImageView()
theImageView.image = UIImage(named: "yourImage.png")
theImageView.translatesAutoresizingMaskIntoConstraints = false //You need to call this property so the image is added to your view
return theImageView
}()
Everything else is, all perfect for Swift 3.
You may want to use:
SELECT Name, 'Unpaid' AS Status FROM table;
The SELECT
clause syntax, as defined in MSDN: SELECT Clause (Transact-SQL), is as follows:
SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ]
<select_list>
Where the expression
can be a constant, function, any combination of column names, constants, and functions connected by an operator or operators, or a subquery.
function blinkTab() {
const browserTitle = document.title;
let timeoutId;
let message = 'My New Title';
const stopBlinking = () => {
document.title = browserTitle;
clearInterval(timeoutId);
};
const startBlinking = () => {
document.title = document.title === message ? browserTitle : message;
};
function registerEvents() {
window.addEventListener("focus", function(event) {
stopBlinking();
});
window.addEventListener("blur", function(event) {
const timeoutId = setInterval(startBlinking, 500);
});
};
registerEvents();
};
blinkTab();
I believe you can call a constructor from a constructor. It will compile and run. I recently saw someone do this and it ran on both Windows and Linux.
It just doesn't do what you want. The inner constructor will construct a temporary local object which gets deleted once the outer constructor returns. They would have to be different constructors as well or you would create a recursive call.
div {
text-align: center;
}
div ul {
display: inline-table;
}
ul as inline-table fixes the with issue. I used the parent div to align the text to center. this way it looks good even in other languages (translation, different width)
In Jenkins , we have the format is as:
Minute(0-59) Hour(0-23) Day(1-7) Month(1-12) Day of the Week
You can use HttpServletRequest.getRequestURL and HttpServletRequest.getRequestURI.
StringBuffer url = request.getRequestURL();
String uri = request.getRequestURI();
int idx = (((uri != null) && (uri.length() > 0)) ? url.indexOf(uri) : url.length());
String host = url.substring(0, idx); //base url
idx = host.indexOf("://");
if(idx > 0) {
host = host.substring(idx); //remove scheme if present
}
How about mkString ?
theStrings.mkString(",")
A variant exists in which you can specify a prefix and suffix too.
See here for an implementation using foldLeft, which is much more verbose, but perhaps worth looking at for education's sake.
- How do I find Android SDK on my machine? Or prove to myself it's not there?
When you install Android studio, it allows you to choose if you want to download SDK or not
- If it's not there how do I install it?
you can get SDK from here http://developer.android.com/sdk/index.html
- How do I change PATH to include Android SDK?
Try this
ALTER TABLE users
ADD COLUMN `count` SMALLINT(6) NOT NULL AFTER `lastname`,
ADD COLUMN `log` VARCHAR(12) NOT NULL AFTER `count`,
ADD COLUMN `status` INT(10) UNSIGNED NOT NULL AFTER `log`;
check the syntax
use - !important - to override default black
.fa-heart:hover{_x000D_
color:red !important;_x000D_
}_x000D_
.fa-heart-o:hover{_x000D_
color:red !important;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">_x000D_
_x000D_
<i class="fa fa-heart fa-2x"></i>_x000D_
<i class="fa fa-heart-o fa-2x"></i>
_x000D_
In 2020, I did it with Fastlane -
Here is the command I used
$ fastlane run resign ipa:"/Users/my_user/path/to/app.ipa" signing_identity:"iPhone Distribution: MY Company (XXXXXXXX)" provisioning_profile:"/Users/my_user/path/to/profile.mobileprovision" bundle_id:com.company.new.bundle.name
Full docs here - https://docs.fastlane.tools/actions/resign/
A common pre-C++11 idiom is to pass a reference to the object being filled.
Then there is no copying of the vector.
void f( std::vector & result )
{
/*
Insert elements into result
*/
}
Not sure if MySQL has row_number function. If so you can use it to get the desired result. On SQL Server you can do something similar to:
CREATE TABLE p
(
person NVARCHAR(10),
gp INT,
age INT
);
GO
INSERT INTO p
VALUES ('Bob', 1, 32);
INSERT INTO p
VALUES ('Jill', 1, 34);
INSERT INTO p
VALUES ('Shawn', 1, 42);
INSERT INTO p
VALUES ('Jake', 2, 29);
INSERT INTO p
VALUES ('Paul', 2, 36);
INSERT INTO p
VALUES ('Laura', 2, 39);
GO
SELECT t.person, t.gp, t.age
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY gp ORDER BY age DESC) row
FROM p
) t
WHERE t.row = 1;
It is related to generics in java. If I mentioned ArrayList<String>
that means I can add only String type object to that ArrayList.
The two major benefits of generics in Java are:
It's for the same reason you don't write every method of every class to return "object". You should be as specific as you can. This is especially valuable if you're planning to write unit tests. No more testing return types and/or casting the result.
If we have a greater number of such svg images we can also take the help of font-files.
Sites like https://glyphter.com/ can get us a font file from our svgs.
E.g.
@font-face {
font-family: 'iconFont';
src: url('iconFont.eot');
}
#target{
color: white;
font-size:96px;
font-family:iconFont;
}
Use the below query to store the result in a CSV file
\copy (your query) to 'file path' csv header;
Example
\copy (select name,date_order from purchase_order) to '/home/ankit/Desktop/result.csv' cvs header;
Hope this helps you.
I have solve this problem by just deleting .gradle folder within my application project..
Delete folder .gradle from your project no need to delete main .gradle folder which is located at C:\Users\<username>
I'm not sure if this is the best way (or if it works), but you could try:
private void on_btnClose_clicked(ActionEvent actionEvent) {
Window window = getScene().getWindow();
if (window instanceof Stage){
((Stage) window).close();
}
}
(Assuming your controller is a Node. Otherwise you have to get the node first (getScene() is a method of Node)
If your project already depends on Apache Commons you can use StringUtils.ordinalIndexOf
, otherwise, here's an implementation:
public static int ordinalIndexOf(String str, String substr, int n) {
int pos = str.indexOf(substr);
while (--n > 0 && pos != -1)
pos = str.indexOf(substr, pos + 1);
return pos;
}
This post has been rewritten as an article here.
For fresh setup of LAMP running php 7 edit the file /etc/httpd/conf/httpd.conf Note: make sure to make backup for it before changing anything.
Paste this at the very bottom of the file:
<IfModule php7_module>
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps
<IfModule dir_module>
DirectoryIndex index.html index.php
</IfModule>
Then, search for LoadModule and paste the following line:
LoadModule php7_module modules/libphp7.so
This line will simply ask httpd to load the php 7 module
Then restart httpd
I found a solution for my problem while writing my question !
Going into my remote session i tried two key combinations, and it solved the problem on my Desktop : Alt+Enter and Ctrl+Enter (i don't know which one solved the problem though)
I tried to reproduce the problem, but i couldn't... but i'm almost sure it's one of the key combinations described in the question above (since i experienced this problem several times)
So it seems the problem comes from the use of RDP (windows7 and 8)
Update 2017: Problem occurs on Windows 10 aswell.
In order to navigate to a different drive just use
cd /E/Study/Codes
It will solve your problem.
<Directory /uploads>
Options +Indexes
</Directory>
I finally settled on typeof(MyClass).GetTypeInfo().Assembly.GetName().Version
for a netstandard1.6 app. All of the other proposed answers presented a partial solution. This is the only thing that got me exactly what I needed.
Sourced from a combination of places:
https://msdn.microsoft.com/en-us/library/x4cw969y(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/2exyydhb(v=vs.110).aspx
POSTMAN : A google chrome extension
Use postman to send message instead of server. Postman settings are as follows :
Request Type: POST
URL: https://android.googleapis.com/gcm/send
Header
Authorization : key=your key //Google API KEY
Content-Type : application/json
JSON (raw) :
{
"registration_ids":["yours"],
"data": {
"Hello" : "World"
}
}
on success you will get
Response :
{
"multicast_id": 6506103988515583000,
"success": 1,
"failure": 0,
"canonical_ids": 0,
"results": [
{
"message_id": "0:1432811719975865%54f79db3f9fd7ecd"
}
]
}
I had a similar problem and solve it using the function encodeURIComponent
from JavaScript (documentation)
For example, in your case if you use:
<input id='hiddenId' type='hidden' value='chalk & cheese' />
and
encodeURIComponent($('#hiddenId').attr('value'))
you will get chalk%20%26%20cheese
. Even spaces are kept.
In my case, I had to encode one backslash and this code works perfectly
encodeURIComponent('name/surname')
and I got name%2Fsurname
String s1 = "";
means that the empty String
is assigned to s1
.
In this case, s1.length()
is the same as "".length()
, which will yield 0
as expected.
String s2 = null;
means that (null
) or "no value at all" is assigned to s2
. So this one, s2.length()
is the same as null.length()
, which will yield a NullPointerException
as you can't call methods on null
variables (pointers, sort of) in Java.
Also, a point, the statement
String s1;
Actually has the same effect as:
String s1 = null;
Whereas
String s1 = "";
Is, as said, a different thing.
You don't need an array to do it.
var ItemNode = this.state.data.map(function(itemData) {
return (
<ComponentName title={itemData.title} key={itemData.id} number={itemData.id}/>
);
});
In my case I was modifying the request to append a header (using Fiddler) to an https
request, but I did not configure it to decrypt https traffic. You can export a manually-created certificate from Fiddler, so you can trust/import the certificate by your browsers. See above link for details, some steps include:
The following commands worked for me:
git push origin :old-name-of-branch-on-github
git branch -m old-name-of-branch-on-github new-name-for-branch-you-want
git push origin new-name-for-branch-you-want
It has no special meaning, other than that the last process to exit did so with an exit status of 127.
However, it is also used by bash (assuming you're using bash as a shell) to tell you that the command you tried to execute couldn't be executed (i.e. it couldn't be found). It's unfortunately not immediately deducible though, if the process exited with status 127, or if it couldn't found.
EDIT:
Not immediately deducible, except for the output on the console, but this is stack overflow, so I assume you're doing this in a script.
Labelling the attribute is ideal way. MACRO leads to sometime confusion. and by using void(x),we are adding an overhead in processing.
If not using input argument, use
void foo(int __attribute__((unused))key)
{
}
If not using the variable defined inside the function
void foo(int key)
{
int hash = 0;
int bkt __attribute__((unused)) = 0;
api_call(x, hash, bkt);
}
Now later using the hash variable for your logic but doesn’t need bkt. define bkt as unused, otherwise compiler says'bkt set bt not used".
NOTE: This is just to suppress the warning not for optimization.
This works for me
/**
* Returns List of the List argument passed to this function with size = chunkSize
*
* @param largeList input list to be portioned
* @param chunkSize maximum size of each partition
* @param <T> Generic type of the List
* @return A list of Lists which is portioned from the original list
*/
public static <T> List<List<T>> chunkList(List<T> list, int chunkSize) {
if (chunkSize <= 0) {
throw new IllegalArgumentException("Invalid chunk size: " + chunkSize);
}
List<List<T>> chunkList = new ArrayList<>(list.size() / chunkSize);
for (int i = 0; i < list.size(); i += chunkSize) {
chunkList.add(list.subList(i, i + chunkSize >= list.size() ? list.size()-1 : i + chunkSize));
}
return chunkList;
}
Eg :
List<Integer> stringList = new ArrayList<>();
stringList.add(0);
stringList.add(1);
stringList.add(2);
stringList.add(3);
stringList.add(4);
stringList.add(5);
stringList.add(6);
stringList.add(7);
stringList.add(8);
stringList.add(9);
List<List<Integer>> chunkList = getChunkList1(stringList, 2);
(You should you as Else-If
statement to check the for the three different state (positive, negative, 0)
Here is a simple example (excludes the possibility of non-integer values)
import java.util.Scanner;
public class Compare {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = input.nextInt();
if( number == 0)
{ System.out.println("Number is equal to zero"); }
else if (number > 0)
{ System.out.println("Number is positive"); }
else
{ System.out.println("Number is negative"); }
}
}
One function is enough, you don't need to use any 3rd-party library (for Windows).
#include <Windows.h>
vector<string> get_all_files_names_within_folder(string folder)
{
vector<string> names;
string search_path = folder + "/*.*";
WIN32_FIND_DATA fd;
HANDLE hFind = ::FindFirstFile(search_path.c_str(), &fd);
if(hFind != INVALID_HANDLE_VALUE) {
do {
// read all (real) files in current folder
// , delete '!' read other 2 default folder . and ..
if(! (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) {
names.push_back(fd.cFileName);
}
}while(::FindNextFile(hFind, &fd));
::FindClose(hFind);
}
return names;
}
PS: as mentioned by @Sebastian, you could change *.*
to *.ext
in order to get only the EXT-files (i.e. of a specific type) in that directory.
Curiously, this works:
yourcommand &> filename
But this gives a syntax error:
yourcommand &>> filename
syntax error near unexpected token `>'
You have to use:
yourcommand 1>> filename 2>&1
Try a different usb cable. My cable was bad. Charging was ok but did not attach the phone.
void intSwap (int *pa, int *pb){
int temp = *pa;
*pa = *pb;
*pb = temp;
}
You need to know the following -
int a = 5; // an integer, contains value
int *p; // an integer pointer, contains address
p = &a; // &a means address of a
a = *p; // *p means value stored in that address, here 5
void charSwap(char* a, char* b){
char temp = *a;
*a = *b;
*b = temp;
}
So, when you swap like this. Only the value will be swapped. So, for a char*
only their first char
will swap.
Now, if you understand char* (string) clearly, then you should know that, you only need to exchange the pointer. It'll be easier to understand if you think it as an array
instead of string.
void stringSwap(char** a, char** b){
char *temp = *a;
*a = *b;
*b = temp;
}
So, here you are passing double pointer because starting of an array
itself is a pointer.
The purpose of raw.github.com
is to allow users to view the contents of a file, so for text based files this means (for certain content types) you can get the wrong headers and things break in the browser.
When this question was asked (in 2012) SVGs didn't work. Since then Github has implemented various improvements. Now (at least for SVG), the correct Content-Type headers are sent.
All of the ways stated below will work.
I copied the SVG image from the question to a repo on github in order to create the examples below
Code
![Alt text](./controllers_brief.svg)
<img src="./controllers_brief.svg">
Result
See the working example on github.com.
Code
![Alt text](https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg)
<img src="https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg">
Result
?sanitize=true
Code
![Alt text](https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg?sanitize=true)
<img src="https://raw.github.com/potherca-blog/StackOverflow/master/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg?sanitize=true">
Result
Code
![Alt text](https://potherca-blog.github.io/StackOverflow/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg)
<img src="https://potherca-blog.github.io/StackOverflow/question.13808020.include-an-svg-hosted-on-github-in-markdown/controllers_brief.svg">
Result
Some comments regarding changes that happened along the way:
Github has implemented a feature which makes it possible for SVG's to be used with the Markdown image syntax. The SVG image will be sanitized and displayed with the correct HTTP header. Certain tags (like <script>
) are removed.
To view the sanitized SVG or to achieve this effect from other places (i.e. from markdown files not hosted in repos on http://github.com/) simply append ?sanitize=true
to the SVG's raw URL.
As stated by AdamKatz in the comments, using a source other than github.io can introduce potentially privacy and security risks. See the answer by CiroSantilli and the answer by DavidChambers for more details.
The issue to resolve this was opened on Github on October 13th 2015 and was resolved on August 31th 2017
Even you can do like this
display:block;
overflow:auto;
height: 100%;
This will include your each dynamic div as per the content. Suppose if you have a common div with class it will increase height of each dynamic div according to the content
This should solve your problem:
td {
/* <http://www.w3.org/wiki/CSS/Properties/text-align>
* left, right, center, justify, inherit
*/
text-align: center;
/* <http://www.w3.org/wiki/CSS/Properties/vertical-align>
* baseline, sub, super, top, text-top, middle,
* bottom, text-bottom, length, or a value in percentage
*/
vertical-align: top;
}
We can do this by setting out variable of System class in the following way
System.setOut(new PrintStream(new FileOutputStream("Path to output file"))). Also You need to close or flush 'out'(System.out.close() or System.out.flush()) variable so that you don't end up missing some output.
Source : http://xmodulo.com/how-to-save-console-output-to-file-in-eclipse.html
I see this issue come up a lot. Yes, Tomcat 7 does automatically deregister it, but it that REALLY taking control of your code and a good coding practice? Surely YOU want to know that you have all the correct code in place to close all your objects, shut down database connection pool threads, and get rid of all warnings. I certainly do.
This is how I do it.
Step 1: Register a Listener
web.xml
<listener>
<listener-class>com.mysite.MySpecialListener</listener-class>
</listener>
Step 2: Implement the Listener
com.mysite.MySpecialListener.java
public class MySpecialListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
// On Application Startup, please…
// Usually I'll make a singleton in here, set up my pool, etc.
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
// On Application Shutdown, please…
// 1. Go fetch that DataSource
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource datasource = (DataSource)envContext.lookup("jdbc/database");
// 2. Deregister Driver
try {
java.sql.Driver mySqlDriver = DriverManager.getDriver("jdbc:mysql://localhost:3306/");
DriverManager.deregisterDriver(mySqlDriver);
} catch (SQLException ex) {
logger.info("Could not deregister driver:".concat(ex.getMessage()));
}
// 3. For added safety, remove the reference to dataSource for GC to enjoy.
dataSource = null;
}
}
Please feel free to comment and/or add...
Simply install the 32-bit version of the program, instead of the 64-bit version.
This is much safer than installing packages that are not intended for the distribution at hand.
I got this suggestion from the Google Earth installation instructions for Ubuntu 14.04.
Google Earth used to employ ia32-libs
under 64-bit Ubuntu 12.04.
Quoting webupd8.org:
The ia32-libs package is no longer available in Ubuntu, starting with Ubuntu 13.10. The package was superseded by multiarch support so you don't need it any more, but some 64bit packages (which are actually 32bit applications) still depend on this package and because of this, they can't be installed in Ubuntu 14.04 or 13.10, 64bit. [...]
The "fix" or more specifically the correct way of installing these apps which depend on ia32-libs is to simply install the 32bit package on Ubuntu 64bit. Of course, that will install quite a few 32bit packages, but that's how multiarch works.
The problem with some programs (like Google Earth) is that the 32-bit package does not support multiarch. Consequently, some 32-bit dependencies need to be installed manually to make the 32-bit version of the program run on Ubuntu 64-bit.
sudo dpkg --add-architecture i386 # only needed once
sudo apt-get update
sudo apt-get install libfontconfig1:i386 libx11-6:i386 libxrender1:i386 libxext6:i386 libgl1-mesa-glx:i386 libglu1-mesa:i386 libglib2.0-0:i386 libsm6:i386
SELECT TOP 25 amount,
(SELECT SUM(amount)
FROM time_detail b
WHERE b.time_detail_id <= a.time_detail_id) AS Total FROM time_detail a
You can also use the ROW_NUMBER() function and a temp table to create an arbitrary column to use in the comparison on the inner SELECT statement.
you can't make easisly a slideup slidedown with css3 tha's why I've turned JensT script into a plugin with javascript fallback and callback.
in this way if you have a modern brwowser you can use the css3 csstransition. if your browser does not support it gracefuly use the old fashioned slideUp slideDown.
/* css */
.csstransitions .mosneslide {
-webkit-transition: height .4s ease-in-out;
-moz-transition: height .4s ease-in-out;
-ms-transition: height .4s ease-in-out;
-o-transition: height .4s ease-in-out;
transition: height .4s ease-in-out;
max-height: 9999px;
overflow: hidden;
height: 0;
}
the plugin
(function ($) {
$.fn.mosne_slide = function (
options) {
// set default option values
defaults = {
delay: 750,
before: function () {}, // before callback
after: function () {} // after callback;
}
// Extend default settings
var settings = $.extend({},
defaults, options);
return this.each(function () {
var $this = $(this);
//on after
settings.before.apply(
$this);
var height = $this.height();
var width = $this.width();
if (Modernizr.csstransitions) {
// modern browsers
if (height > 0) {
$this.css(
'height',
'0')
.addClass(
"mosne_hidden"
);
} else {
var clone =
$this.clone()
.css({
'position': 'absolute',
'visibility': 'hidden',
'height': 'auto',
'width': width
})
.addClass(
'mosne_slideClone'
)
.appendTo(
'body'
);
var newHeight =
$(
".mosne_slideClone"
)
.height();
$(
".mosne_slideClone"
)
.remove();
$this.css(
'height',
newHeight +
'px')
.removeClass(
"mosne_hidden"
);
}
} else {
//fallback
if ($this.is(
":visible"
)) {
$this.slideUp()
.addClass(
"mosne_hidden"
);
} else {
$this.hide()
.slideDown()
.removeClass(
"mosne_hidden"
);
}
}
//on after
setTimeout(function () {
settings.after
.apply(
$this
);
}, settings.delay);
});
}
})(jQuery);;
how to use it
/* jQuery */
$(".mosneslide").mosne_slide({
delay:400,
before:function(){console.log("start");},
after:function(){console.log("done");}
});
you can find a demo page here http://www.mosne.it/playground/mosne_slide_up_down/
In Python self
is the conventional name given to the first argument of instance methods of classes, which is always the instance the method was called on:
class A(object):
def f(self):
print self
a = A()
a.f()
Will give you something like
<__main__.A object at 0x02A9ACF0>
Just add in: border-bottom: none;
#index-03 {
position:absolute;
border: .1px solid #900;
border-bottom: none;
left:0px;
top:102px;
width:900px;
height:27px;
}
As of 2016, the following will suffice (you don't even need to embed):
let src = 'https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_700KB.mp3';
let audio = new Audio(src);
audio.play();
See more here.
The problem with ordering the other way is that it often does not make good use of indices. It is also not very extendable if you ever need to select a number of rows that are not at the start or the end. An alternative way is as follows.
DECLARE @NumberOfRows int;
SET @NumberOfRows = (SELECT COUNT(*) FROM TheTable);
SELECT col1, col2,...
FROM (
SELECT col1, col2,..., ROW_NUMBER() OVER (ORDER BY col1) AS intRow
FROM TheTable
) AS T
WHERE intRow > @NumberOfRows - 20;
* Hope This will work for u
System.Windows.Forms.Form f1 = System.Windows.Forms.Application.OpenForms["Order"];
if(((Order)f1)!=null)
{
//open Form
}
else
{
//not open
}
Using FETCH FIRST [n] ROWS ONLY
:
SELECT LASTNAME, FIRSTNAME, EMPNO, SALARY
FROM EMP
ORDER BY SALARY DESC
FETCH FIRST 20 ROWS ONLY;
To get ranges, you'd have to use ROW_NUMBER()
(since v5r4) and use that within the WHERE
clause: (stolen from here: http://www.justskins.com/forums/db2-select-how-to-123209.html)
SELECT code, name, address
FROM (
SELECT row_number() OVER ( ORDER BY code ) AS rid, code, name, address
FROM contacts
WHERE name LIKE '%Bob%'
) AS t
WHERE t.rid BETWEEN 20 AND 25;
This article helped explain a lot of things. It's in FAQ style.
This part explains why Thread.Sleep
runs on the same original thread - leading to my initial confusion.
Does the “async” keyword cause the invocation of a method to queue to the ThreadPool? To create a new thread? To launch a rocket ship to Mars?
No. No. And no. See the previous questions. The “async” keyword indicates to the compiler that “await” may be used inside of the method, such that the method may suspend at an await point and have its execution resumed asynchronously when the awaited instance completes. This is why the compiler issues a warning if there are no “awaits” inside of a method marked as “async”.
Return false
to prevent the keystroke from continuing.
Other answers are old, could not get a good answer.
Below example is for object literals, helps how both can complement each other, and how it cannot complement each other (therefore difference):
var obj1 = { a: 1, b: { b1: 1, b2: 'b2value', b3: 'b3value' } };
// overwrite parts of b key
var obj2 = {
b: {
...obj1.b,
b1: 2
}
};
var res2 = Object.assign({}, obj1, obj2); // b2,b3 keys still exist
document.write('res2: ', JSON.stringify (res2), '<br>');
// Output:
// res2: {"a":1,"b":{"b1":2,"b2":"b2value","b3":"b3value"}} // NOTE: b2,b3 still exists
// overwrite whole of b key
var obj3 = {
b: {
b1: 2
}
};
var res3 = Object.assign({}, obj1, obj3); // b2,b3 keys are lost
document.write('res3: ', JSON.stringify (res3), '<br>');
// Output:
// res3: {"a":1,"b":{"b1":2}} // NOTE: b2,b3 values are lost
Several more small examples here, also for array & object:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
The question was answered perfectly by Darin Dimitrov, but since ASP.NET 4.5, there is now a better way to set up these bindings to replace* Eval()
and Bind()
, taking advantage of the strongly-typed bindings.
*Note: this will only work if you're not using a SqlDataSource
or an anonymous object
. It requires a Strongly-typed object (from an EF model or any other class).
This code snippet shows how Eval
and Bind
would be used for a ListView
control (InsertItem
needs Bind
, as explained by Darin Dimitrov above, and ItemTemplate
is read-only (hence they're labels), so just needs an Eval
):
<asp:ListView ID="ListView1" runat="server" DataKeyNames="Id" InsertItemPosition="LastItem" SelectMethod="ListView1_GetData" InsertMethod="ListView1_InsertItem" DeleteMethod="ListView1_DeleteItem">
<InsertItemTemplate>
<li>
Title: <asp:TextBox ID="Title" runat="server" Text='<%# Bind("Title") %>'/><br />
Description: <asp:TextBox ID="Description" runat="server" TextMode="MultiLine" Text='<%# Bind("Description") %>' /><br />
<asp:Button ID="InsertButton" runat="server" Text="Insert" CommandName="Insert" />
</li>
</InsertItemTemplate>
<ItemTemplate>
<li>
Title: <asp:Label ID="Title" runat="server" Text='<%# Eval("Title") %>' /><br />
Description: <asp:Label ID="Description" runat="server" Text='<%# Eval("Description") %>' /><br />
<asp:Button ID="DeleteButton" runat="server" Text="Delete" CommandName="Delete" CausesValidation="false"/>
</li>
</ItemTemplate>
From ASP.NET 4.5+, data-bound controls have been extended with a new property ItemType
, which points to the type of object you're assigning to its data source.
<asp:ListView ItemType="Picture" ID="ListView1" runat="server" ...>
Picture
is the strongly type object (from EF model). We then replace:
Bind(property) -> BindItem.property
Eval(property) -> Item.property
So this:
<%# Bind("Title") %>
<%# Bind("Description") %>
<%# Eval("Title") %>
<%# Eval("Description") %>
Would become this:
<%# BindItem.Title %>
<%# BindItem.Description %>
<%# Item.Title %>
<%# Item.Description %>
Advantages over Eval & Bind:
Source: from this excellent book
I had the same problem that is really easy to make, but took me a while to see through.
I had copied the declaration to where I was using it and had left the 'self' argument there, but it took me ages to realise that.
I had
self.myFunction(self, a, b, c='123')
but it should have been
self.myFunction(a, b, c='123')
ALTER TABLE table_name ADD COLUMN ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT ; This could be useful
only css div you can center content
div{
display:table;
margin:0 auto;
}
It seems that stopUpdatingLocation is what triggers the background watchdog timer, so I replaced it in didUpdateLocation with:
[self.locationManager setDesiredAccuracy:kCLLocationAccuracyThreeKilometers];
[self.locationManager setDistanceFilter:99999];
which appears to effectively power down the GPS. The selector for the background NSTimer then becomes:
- (void) changeAccuracy {
[self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[self.locationManager setDistanceFilter:kCLDistanceFilterNone];
}
All I'm doing is periodically toggling the accuracy to get a high-accuracy coordinate every few minutes and because the locationManager hasn't been stopped, backgroundTimeRemaining stays at its maximum value. This reduced battery consumption from ~10% per hour (with constant kCLLocationAccuracyBest in the background) to ~2% per hour on my device
A reasonably good type capture function is the one used by YUI3:
var TYPES = {
'undefined' : 'undefined',
'number' : 'number',
'boolean' : 'boolean',
'string' : 'string',
'[object Function]': 'function',
'[object RegExp]' : 'regexp',
'[object Array]' : 'array',
'[object Date]' : 'date',
'[object Error]' : 'error'
},
TOSTRING = Object.prototype.toString;
function type(o) {
return TYPES[typeof o] || TYPES[TOSTRING.call(o)] || (o ? 'object' : 'null');
};
This captures many of the primitives provided by javascript, but you can always add more by modifying the TYPES
object. Note that typeof HTMLElementCollection
in Safari will report function
, but type(HTMLElementCollection) will return object
There are many possibilities to do this in R. Here are some of them:
df <- read.table(header = TRUE, text = 'Gene Value
A 12
A 10
B 3
B 5
B 6
C 1
D 3
D 4')
# aggregate
aggregate(df$Value, by = list(df$Gene), max)
aggregate(Value ~ Gene, data = df, max)
# tapply
tapply(df$Value, df$Gene, max)
# split + lapply
lapply(split(df, df$Gene), function(y) max(y$Value))
# plyr
require(plyr)
ddply(df, .(Gene), summarise, Value = max(Value))
# dplyr
require(dplyr)
df %>% group_by(Gene) %>% summarise(Value = max(Value))
# data.table
require(data.table)
dt <- data.table(df)
dt[ , max(Value), by = Gene]
# doBy
require(doBy)
summaryBy(Value~Gene, data = df, FUN = max)
# sqldf
require(sqldf)
sqldf("select Gene, max(Value) as Value from df group by Gene", drv = 'SQLite')
# ave
df[as.logical(ave(df$Value, df$Gene, FUN = function(x) x == max(x))),]
In my case symbolicating was take forever. I force restart my phone with both of on/off and home button. Now quickly finished symbolicating and I am starting run my app via xcode.
Any browser that does not support the input type date
will default to the standard type, which is text
, so all you have to do is check the type property (not the attribute), if it's not date
, the date input is not supported by the browser, and you add your own datepicker:
if ( $('[type="date"]').prop('type') != 'date' ) {
$('[type="date"]').datepicker();
}
You can of course use any datepicker you want, jQuery UI's datepicker is probably the one most commonly used, but it does add quite a bit of javascript if you're not using the UI library for anything else, but there are hundreds of alternative datepickers to choose from.
The type
attribute never changes, the browser will only fall back to the default text
type for the property, so one has to check the property.
The attribute can still be used as a selector, as in the example above.
OK, let me put this bluntly: if you're putting user data, or anything derived from user data into a cookie for this purpose, you're doing something wrong.
There. I said it. Now we can move on to the actual answer.
What's wrong with hashing user data, you ask? Well, it comes down to exposure surface and security through obscurity.
Imagine for a second that you're an attacker. You see a cryptographic cookie set for the remember-me on your session. It's 32 characters wide. Gee. That may be an MD5...
Let's also imagine for a second that they know the algorithm that you used. For example:
md5(salt+username+ip+salt)
Now, all an attacker needs to do is brute force the "salt" (which isn't really a salt, but more on that later), and he can now generate all the fake tokens he wants with any username for his IP address! But brute-forcing a salt is hard, right? Absolutely. But modern day GPUs are exceedingly good at it. And unless you use sufficient randomness in it (make it large enough), it's going to fall quickly, and with it the keys to your castle.
In short, the only thing protecting you is the salt, which isn't really protecting you as much as you think.
But Wait!
All of that was predicated that the attacker knows the algorithm! If it's secret and confusing, then you're safe, right? WRONG. That line of thinking has a name: Security Through Obscurity, which should NEVER be relied upon.
The Better Way
The better way is to never let a user's information leave the server, except for the id.
When the user logs in, generate a large (128 to 256 bit) random token. Add that to a database table which maps the token to the userid, and then send it to the client in the cookie.
What if the attacker guesses the random token of another user?
Well, let's do some math here. We're generating a 128 bit random token. That means that there are:
possibilities = 2^128
possibilities = 3.4 * 10^38
Now, to show how absurdly large that number is, let's imagine every server on the internet (let's say 50,000,000 today) trying to brute-force that number at a rate of 1,000,000,000 per second each. In reality your servers would melt under such load, but let's play this out.
guesses_per_second = servers * guesses
guesses_per_second = 50,000,000 * 1,000,000,000
guesses_per_second = 50,000,000,000,000,000
So 50 quadrillion guesses per second. That's fast! Right?
time_to_guess = possibilities / guesses_per_second
time_to_guess = 3.4e38 / 50,000,000,000,000,000
time_to_guess = 6,800,000,000,000,000,000,000
So 6.8 sextillion seconds...
Let's try to bring that down to more friendly numbers.
215,626,585,489,599 years
Or even better:
47917 times the age of the universe
Yes, that's 47917 times the age of the universe...
Basically, it's not going to be cracked.
So to sum up:
The better approach that I recommend is to store the cookie with three parts.
function onLogin($user) {
$token = GenerateRandomToken(); // generate a token, should be 128 - 256 bit
storeTokenForUser($user, $token);
$cookie = $user . ':' . $token;
$mac = hash_hmac('sha256', $cookie, SECRET_KEY);
$cookie .= ':' . $mac;
setcookie('rememberme', $cookie);
}
Then, to validate:
function rememberMe() {
$cookie = isset($_COOKIE['rememberme']) ? $_COOKIE['rememberme'] : '';
if ($cookie) {
list ($user, $token, $mac) = explode(':', $cookie);
if (!hash_equals(hash_hmac('sha256', $user . ':' . $token, SECRET_KEY), $mac)) {
return false;
}
$usertoken = fetchTokenByUserName($user);
if (hash_equals($usertoken, $token)) {
logUserIn($user);
}
}
}
Note: Do not use the token or combination of user and token to lookup a record in your database. Always be sure to fetch a record based on the user and use a timing-safe comparison function to compare the fetched token afterwards. More about timing attacks.
Now, it's very important that the SECRET_KEY
be a cryptographic secret (generated by something like /dev/urandom
and/or derived from a high-entropy input). Also, GenerateRandomToken()
needs to be a strong random source (mt_rand()
is not nearly strong enough. Use a library, such as RandomLib or random_compat, or mcrypt_create_iv()
with DEV_URANDOM
)...
The hash_equals()
is to prevent timing attacks.
If you use a PHP version below PHP 5.6 the function hash_equals()
is not supported. In this case you can replace hash_equals()
with the timingSafeCompare function:
/**
* A timing safe equals comparison
*
* To prevent leaking length information, it is important
* that user input is always used as the second parameter.
*
* @param string $safe The internal (safe) value to be checked
* @param string $user The user submitted (unsafe) value
*
* @return boolean True if the two strings are identical.
*/
function timingSafeCompare($safe, $user) {
if (function_exists('hash_equals')) {
return hash_equals($safe, $user); // PHP 5.6
}
// Prevent issues if string length is 0
$safe .= chr(0);
$user .= chr(0);
// mbstring.func_overload can make strlen() return invalid numbers
// when operating on raw binary strings; force an 8bit charset here:
if (function_exists('mb_strlen')) {
$safeLen = mb_strlen($safe, '8bit');
$userLen = mb_strlen($user, '8bit');
} else {
$safeLen = strlen($safe);
$userLen = strlen($user);
}
// Set the result to the difference between the lengths
$result = $safeLen - $userLen;
// Note that we ALWAYS iterate over the user-supplied length
// This is to prevent leaking length information
for ($i = 0; $i < $userLen; $i++) {
// Using % here is a trick to prevent notices
// It's safe, since if the lengths are different
// $result is already non-0
$result |= (ord($safe[$i % $safeLen]) ^ ord($user[$i]));
}
// They are only identical strings if $result is exactly 0...
return $result === 0;
}
Here is another example, for compiling a java file in a nested directory.
I was trying to build this from the command line. This is an example from 'gradle', which has dependency 'commons-collection.jar'. For more info, please see 'gradle: java quickstart' example. -- of course, you would use the 'gradle' tools to build it. But i thought to extend this example, for a nested java project, with a dependent jar.
Note: You need the 'gradle binary or source' distribution for this, example code is in: 'samples/java/quickstart'
% mkdir -p temp/classes
% curl --get \
http://central.maven.org/maven2/commons-collections/commons-collections/3.2.2/commons-collections-3.2.2.jar \
--output commons-collections-3.2.2.jar
% javac -g -classpath commons-collections-3.2.2.jar \
-sourcepath src/main/java -d temp/classes \
src/main/java/org/gradle/Person.java
% jar cf my_example.jar -C temp/classes org/gradle/Person.class
% jar tvf my_example.jar
0 Wed Jun 07 14:11:56 CEST 2017 META-INF/
69 Wed Jun 07 14:11:56 CEST 2017 META-INF/MANIFEST.MF
519 Wed Jun 07 13:58:06 CEST 2017 org/gradle/Person.class
//====Single Class Reference used to retrieve object for fields and initial values. Performance enhancing only====
Class<?> reference = vector.get(0).getClass();
Object obj = reference.newInstance();
Field[] objFields = obj.getClass().getFields();
Look at the Inherits tag of all your aspx pages and master pages. Chances are there are two partial classes that have the same name. Change one and recompile.
Here is some more info:
http://blogs.msdn.com/b/carloc/archive/2007/06/12/compiler-error-message-cs0433-in-asp-net-2-0.aspx
I have been working with our DBA to copy an audit table with 240M rows to another database.
Using a simple select/insert created a huge tempdb file.
Using a the Import/Export wizard worked but copied 8M rows in 10min
Creating a custom SSIS package and adjusting settings copied 30M rows in 10Min
The SSIS package turned out to be the fastest and most efficent for our purposes
Earl
I guess your code uses somewhere in the second case a singular matrix (i.e. not invertible), and the solve function needs to invert it. This has nothing to do with the size but with the fact that some of your vectors are (probably) colinear.
Send a SIGTERM or a SIGKILL to it:
http://en.wikipedia.org/wiki/SIGKILL
http://en.wikipedia.org/wiki/SIGTERM
SIGTERM is polite and lets the process clean up before it goes, whereas, SIGKILL is for when it won't listen >:)
Example from the shell (man page: http://unixhelp.ed.ac.uk/CGI/man-cgi?kill )
kill -9 pid
In C, you can do the same thing using the kill syscall:
kill(pid, SIGKILL);
See the following man page: http://linux.die.net/man/2/kill
The code below is enough for "Check if a String contains numbers in Java"
Pattern p = Pattern.compile("([0-9])");
Matcher m = p.matcher("Here is ur string");
if(m.find()){
System.out.println("Hello "+m.find());
}
Before MySQL 5.6 Full-Text Search is supported only with MyISAM Engine.
Therefore either change the engine for your table to MyISAM
CREATE TABLE gamemech_chat (
id bigint(20) unsigned NOT NULL auto_increment,
from_userid varchar(50) NOT NULL default '0',
to_userid varchar(50) NOT NULL default '0',
text text NOT NULL,
systemtext text NOT NULL,
timestamp datetime NOT NULL default '0000-00-00 00:00:00',
chatroom bigint(20) NOT NULL default '0',
PRIMARY KEY (id),
KEY from_userid (from_userid),
FULLTEXT KEY from_userid_2 (from_userid),
KEY chatroom (chatroom),
KEY timestamp (timestamp)
) ENGINE=MyISAM;
Here is SQLFiddle demo
or upgrade to 5.6 and use InnoDB Full-Text Search.
Assuming the following method to test:
public boolean doSomething(SomeClass arg);
Mockito documentation says that you should not use captor in this way:
when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);
assertThat(argumentCaptor.getValue(), equalTo(expected));
Because you can just use matcher during stubbing:
when(someObject.doSomething(eq(expected))).thenReturn(true);
But verification is a different story. If your test needs to ensure that this method was called with a specific argument, use ArgumentCaptor
and this is the case for which it is designed:
ArgumentCaptor<SomeClass> argumentCaptor = ArgumentCaptor.forClass(SomeClass.class);
verify(someObject).doSomething(argumentCaptor.capture());
assertThat(argumentCaptor.getValue(), equalTo(expected));
java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;
That method was added in Servlet 2.5.
So this problem can have at least 3 causes:
web.xml
is not declared conform Servlet 2.5 or newer.To solve it,
web.xml
complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.servlet-api.jar
or j2ee.jar
in /WEB-INF/lib
or even worse, the JRE/lib
or JRE/lib/ext
. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.You can call a JavaScript function and use window.location = 'url';
:
You'll have to attach Database X with Database Y using the ATTACH command, then run the appropriate Insert Into commands for the tables you want to transfer.
INSERT INTO X.TABLE SELECT * FROM Y.TABLE;
Or, if the columns are not matched up in order:
INSERT INTO X.TABLE(fieldname1, fieldname2) SELECT fieldname1, fieldname2 FROM Y.TABLE;
If the HTTP Connection doesn't timeout, You can implement the timeout checker in the background thread itself (AsyncTask, Service, etc), the following class is an example for Customize AsyncTask which timeout after certain period
public abstract class AsyncTaskWithTimer<Params, Progress, Result> extends
AsyncTask<Params, Progress, Result> {
private static final int HTTP_REQUEST_TIMEOUT = 30000;
@Override
protected Result doInBackground(Params... params) {
createTimeoutListener();
return doInBackgroundImpl(params);
}
private void createTimeoutListener() {
Thread timeout = new Thread() {
public void run() {
Looper.prepare();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (AsyncTaskWithTimer.this != null
&& AsyncTaskWithTimer.this.getStatus() != Status.FINISHED)
AsyncTaskWithTimer.this.cancel(true);
handler.removeCallbacks(this);
Looper.myLooper().quit();
}
}, HTTP_REQUEST_TIMEOUT);
Looper.loop();
}
};
timeout.start();
}
abstract protected Result doInBackgroundImpl(Params... params);
}
A Sample for this
public class AsyncTaskWithTimerSample extends AsyncTaskWithTimer<Void, Void, Void> {
@Override
protected void onCancelled(Void void) {
Log.d(TAG, "Async Task onCancelled With Result");
super.onCancelled(result);
}
@Override
protected void onCancelled() {
Log.d(TAG, "Async Task onCancelled");
super.onCancelled();
}
@Override
protected Void doInBackgroundImpl(Void... params) {
// Do background work
return null;
};
}
I highly recommend you use the tobytes
function of the Image
object. After some timing checks this is much more efficient.
def jpg_image_to_array(image_path):
"""
Loads JPEG image into 3D Numpy array of shape
(width, height, channels)
"""
with Image.open(image_path) as image:
im_arr = np.fromstring(image.tobytes(), dtype=np.uint8)
im_arr = im_arr.reshape((image.size[1], image.size[0], 3))
return im_arr
The timings I ran on my laptop show
In [76]: %timeit np.fromstring(im.tobytes(), dtype=np.uint8)
1000 loops, best of 3: 230 µs per loop
In [77]: %timeit np.array(im.getdata(), dtype=np.uint8)
10 loops, best of 3: 114 ms per loop
```
Have a look at this answer:
Storing Images in DB - Yea or Nay?
Essentially, the space and performance hit can be quite big, depending on the number of users. Also, keep in mind that Web servers are cheap and you can easily add more to balance the load, whereas the database is the most expensive and hardest to scale part of a web architecture usually.
There are some opposite examples (e.g., Microsoft Sharepoint), but usually, storing files in the database is not a good idea.
Unless possibly you write desktop apps and/or know roughly how many users you will ever have, but on something as random and unexpectable like a public web site, you may pay a high price for storing files in the database.
Ok. I think I found the proper solution:
v = [x[0]-x[1] for x in zip(t[1:],t[:-1])]
Your question How can I just get the file-names (with paths)
Your syntax example find . -iname "*php" -exec grep -H myString {} \;
My Command suggestion
sudo find /home -name *.php
The output from this command on my Linux OS:
compose-sample-3/html/mail/contact_me.php
As you require the filename with path, enjoy!
Use filter
, or if the number of dictionaries in exampleSet
is too high, use ifilter
of the itertools
module. It would return an iterator, instead of filling up your system's memory with the entire list at once:
from itertools import ifilter
for elem in ifilter(lambda x: x['type'] in keyValList, exampleSet):
print elem
// MY_PREFS_NAME - a static String variable like:
//public static final String MY_PREFS_NAME = "MyPrefsFile";
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.commit();
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value.
}
more info:
In the app-routing.modules.ts
file:
{
path: 'hero/:id', component: HeroComponent
}
In the component.html
file:
target="_blank" [routerLink]="['/hero', '/sachin']"
If you need style names which should appear according to the state condition, I prefer to use this construction:
<div className={'wrapper searchDiv' + (this.state.something === "a" ? " anotherClass" : "")'}>
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);
I was thinking about this problem for my own code and even though I probably will end up using something simpler/faster, here's another Linq solution that's similar to one that @Francisco added.
I just like it because it reads the most like what you actually want to do: "Take chars while the resulting substring has fewer than 2 spaces."
string input = "o1 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467 1232.5467";
var substring = input.TakeWhile((c0, index) =>
input.Substring(0, index + 1).Count(c => c == ' ') < 2);
string result = new String(substring.ToArray());
You can use Case
expression for returning a boolean
in your select query like below.
@Query("SELECT CASE WHEN count(e) > 0 THEN true ELSE false END FROM MyEntity e where e.my_column = ?1")
On connectionstrings.com you can find the connection string for every DB provider. A connection string is built up with certain attributes/properties and their values. For SQL server 2008, it looks like this (standard, which is what you'll need here):
Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
on myServerAddress
, write the name of your installed instance (by default it's .\SQLEXPRESS
for SQL Server Express edition). Initial catalog = your database name, you'll see it in SSMS on the left after connecting. The rest speaks for itself.
edit
You will need to omit username and password for windows authentication and add Integrated Security=SSPI
.
Here i am using angular js. In javascript you can use for loop to find.
if($scope.bechval>0 &&$scope.bechval!=undefined)
{
angular.forEach($scope.model.benhmarkghamlest, function (val, key) {
$scope.model.benhmarkghamlest[key].bechval = $scope.bechval;
});
}
else {
alert("Please sepecify Bechmark value");
}
Unfortunately, All the above answers are only half right.. Took a long time to figure this out..
Mongoose bson install via npm throws warning and causes the error...
npm install -g node-gyp
git clone https://github.com/mongodb/js-bson.git
cd js-bson
npm install
node-gyp rebuild
This works like magic!!
Are you referring to the server side or the client side?
For a client, you would want to adjust the sendTimeout attribute of a binding element. For a service, you would want to adjust the receiveTimeout attribute of a binding elemnent.
<system.serviceModel>
<bindings>
<netTcpBinding>
<binding name="longTimeoutBinding"
receiveTimeout="00:10:00" sendTimeout="00:10:00">
<security mode="None"/>
</binding>
</netTcpBinding>
</bindings>
<services>
<service name="longTimeoutService"
behaviorConfiguration="longTimeoutBehavior">
<endpoint address="net.tcp://localhost/longtimeout/"
binding="netTcpBinding" bindingConfiguration="longTimeoutBinding" />
</service>
....
Of course, you have to map your desired endpoint to that particular binding.
int indexOf(Object o)
This method returns the index in this list of the first occurrence of the specified element, or -1 if this list does not contain this element.
From the JavaDocs for ResourceBundle.getBundle(String baseName)
:
baseName
- the base name of the resource bundle, a fully qualified class name
What this means in plain English is that the resource bundle must be on the classpath and that baseName
should be the package containing the bundle plus the bundle name, mybundle
in your case.
Leave off the extension and any locale that forms part of the bundle name, the JVM will sort that for you according to default locale - see the docs on java.util.ResourceBundle for more info.
Perhaps the below method could be the cause if you've set it to
func webView(_ webView: WebView!,decidePolicyForNavigationAction actionInformation: [AnyHashable : Any]!, request: URLRequest!, frame: WebFrame!, decisionListener listener: WebPolicyDecisionListener!)
ends with
decisionHandler(.cancel)
for the default navigationAction.request.url
Hope it works!
If you are using postgresql
And i'm using in spring boot 1.5.6
@Column(columnDefinition = "serial")
@Generated(GenerationTime.INSERT)
private Integer orderID;
You can use the BlockingCollection and ConcurrentQueue in the System.Collections.Concurrent Namespace
public class ProducerConsumerQueue<T> : BlockingCollection<T>
{
/// <summary>
/// Initializes a new instance of the ProducerConsumerQueue, Use Add and TryAdd for Enqueue and TryEnqueue and Take and TryTake for Dequeue and TryDequeue functionality
/// </summary>
public ProducerConsumerQueue()
: base(new ConcurrentQueue<T>())
{
}
/// <summary>
/// Initializes a new instance of the ProducerConsumerQueue, Use Add and TryAdd for Enqueue and TryEnqueue and Take and TryTake for Dequeue and TryDequeue functionality
/// </summary>
/// <param name="maxSize"></param>
public ProducerConsumerQueue(int maxSize)
: base(new ConcurrentQueue<T>(), maxSize)
{
}
}
Sorting on two date fields and a numeric field example:
var generic_date = new Date(2070, 1, 1);
checkDate = function(date) {
return Date.parse(date) ? new Date(date): generic_date;
}
function sortData() {
data.sort(function(a,b){
var deltaEnd = checkDate(b.end) - checkDate(a.end);
if(deltaEnd) return deltaEnd;
var deltaRank = a.rank - b.rank;
if (deltaRank) return deltaRank;
var deltaStart = checkDate(b.start) - checkDate(a.start);
if(deltaStart) return deltaStart;
return 0;
});
}
I've made an Int type extension. tested it in playground, hope this is useful. It also accepts negative ranges:
extension Int
{
static func random(range: Range<Int> ) -> Int
{
var offset = 0
if range.startIndex < 0 // allow negative ranges
{
offset = abs(range.startIndex)
}
let mini = UInt32(range.startIndex + offset)
let maxi = UInt32(range.endIndex + offset)
return Int(mini + arc4random_uniform(maxi - mini)) - offset
}
}
use like
var aRandomInt = Int.random(-500...100) // returns a random number within the given range.
or define it as a Range extension as property like this:
extension Range
{
var randomInt: Int
{
get
{
var offset = 0
if (startIndex as Int) < 0 // allow negative ranges
{
offset = abs(startIndex as Int)
}
let mini = UInt32(startIndex as Int + offset)
let maxi = UInt32(endIndex as Int + offset)
return Int(mini + arc4random_uniform(maxi - mini)) - offset
}
}
}
// usage example: get an Int within the given Range:
let nr = (-1000 ... 1100).randomInt
The post above that mentioned strategies didn't stress enough what a nice lightweight implementation of the strategy pattern using enums gets you:
public enum Strategy {
A {
@Override
void execute() {
System.out.print("Executing strategy A");
}
},
B {
@Override
void execute() {
System.out.print("Executing strategy B");
}
};
abstract void execute();
}
You can have all your strategies in one place without needing a separate compilation unit for each. You get a nice dynamic dispatch just with:
Strategy.valueOf("A").execute();
Makes java read almost like a nice loosely typed language!
Using
<BR>
is not allways enough. MS Outlook 2007 will ignore this if you dont tell outlook that it is a selfclosing html tag by using
<BR />
TLDR; Append Script path to the System Path by adding following in the entry point of your python script.
import os.path
import sys
PACKAGE_PARENT = '..'
SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))
Thats it now you can run your project in PyCharma as well as from Terminal!!
There are many methods to convert an array to comma separated list
From MDN
The join() method joins all elements of an array (or an array-like object) into a string.
The code
var arr = ["this","is","a","comma","separated","list"];
arr = arr.join(",");
var arr = ["this", "is", "a", "comma", "separated", "list"];_x000D_
arr = arr.join(",");_x000D_
console.log(arr);
_x000D_
From MDN
The toString() method returns a string representing the specified array and its elements.
The code
var arr = ["this","is","a","comma","separated","list"];
arr = arr.toString();
var arr = ["this", "is", "a", "comma", "separated", "list"];_x000D_
arr = arr.toString();_x000D_
console.log(arr);
_x000D_
The []+ or +[] will convert it into a string
([]+[] === [].toString())
will output true
console.log([]+[] === [].toString());
_x000D_
var arr = ["this","is","a","comma","separated","list"];
arr = []+arr;
var arr = ["this", "is", "a", "comma", "separated", "list"];_x000D_
arr = []+arr;_x000D_
console.log(arr);
_x000D_
var arr = ["this","is","a","comma","separated","list"];
arr = arr+[];
var arr = ["this", "is", "a", "comma", "separated", "list"];_x000D_
arr = arr + [];_x000D_
console.log(arr);
_x000D_
Step 1:Create a XML File
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="@+id/lvItems"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
Step 2:Studnet.java
package com.scancode.acutesoft.telephonymanagerapp;
public class Student
{
String email,phone,address;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Step 3:MainActivity.java
package com.scancode.acutesoft.telephonymanagerapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends Activity {
ListView lvItems;
ArrayList<Student> studentArrayList ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvItems = (ListView) findViewById(R.id.lvItems);
studentArrayList = new ArrayList<Student>();
dataSaving();
CustomAdapter adapter = new CustomAdapter(MainActivity.this,studentArrayList);
lvItems.setAdapter(adapter);
}
private void dataSaving() {
Student student = new Student();
student.setEmail("[email protected]");
student.setPhone("1234567890");
student.setAddress("Hyderabad");
studentArrayList.add(student);
student = new Student();
student.setEmail("[email protected]");
student.setPhone("1234567890");
student.setAddress("Banglore");
studentArrayList.add(student);
student = new Student();
student.setEmail("[email protected]");
student.setPhone("1234567890");
student.setAddress("Banglore");
studentArrayList.add(student);
student = new Student();
student.setEmail("[email protected]");
student.setPhone("1234567890");
student.setAddress("Banglore");
studentArrayList.add(student);
}
}
Step 4:CustomAdapter.java
package com.scancode.acutesoft.telephonymanagerapp;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomAdapter extends BaseAdapter
{
ArrayList<Student> studentList;
Context mContext;
public CustomAdapter(Context context, ArrayList<Student> studentArrayList) {
this.mContext = context;
this.studentList = studentArrayList;
}
@Override
public int getCount() {
return studentList.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Student student = studentList.get(position);
convertView = LayoutInflater.from(mContext).inflate(R.layout.student_row,null);
TextView tvStudEmail = (TextView) convertView.findViewById(R.id.tvStudEmail);
TextView tvStudPhone = (TextView) convertView.findViewById(R.id.tvStudPhone);
TextView tvStudAddress = (TextView) convertView.findViewById(R.id.tvStudAddress);
tvStudEmail.setText(student.getEmail());
tvStudPhone.setText(student.getPhone());
tvStudAddress.setText(student.getAddress());
return convertView;
}
}
Although I am not aware if it's officially documented anywhere, you can do footer notes in Github.
Mark the place where you want to insert footer link with a number enclosed in square brackets, I.E. [1]
On the bottom of the post, make a reference of the numbered marker and followed by a colon and the link, I.E. [1]: http://www.example.com/link1
And once you preview it, it will be rendered as numbered links in the body of the post.
If you wish to have "Save as" dialog, just pass image into php script, which adds appropriate headers
Example "all-in-one" script script.php
<?php if(isset($_GET['image'])):
$image = $_GET['image'];
if(preg_match('#^data:image/(.*);base64,(.*)$#s', $image, $match)){
$base64 = $match[2];
$imageBody = base64_decode($base64);
$imageFormat = $match[1];
header('Content-type: application/octet-stream');
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false); // required for certain browsers
header("Content-Disposition: attachment; filename=\"file.".$imageFormat."\";" ); //png is default for toDataURL
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".strlen($imageBody));
echo $imageBody;
}
exit();
endif;?>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js?ver=1.7.2'></script>
<canvas id="canvas" width="300" height="150"></canvas>
<button id="btn">Save</button>
<script>
$(document).ready(function(){
var canvas = document.getElementById('canvas');
var oCtx = canvas.getContext("2d");
oCtx.beginPath();
oCtx.moveTo(0,0);
oCtx.lineTo(300,150);
oCtx.stroke();
$('#btn').on('click', function(){
// opens dialog but location doesnt change due to SaveAs Dialog
document.location.href = '/script.php?image=' + canvas.toDataURL();
});
});
</script>
In order to do this in SQL Server, you must order the query by a column, so you can specify the rows you want.
Example:
select * from table order by [some_column]
offset 10 rows
FETCH NEXT 10 rows only
Adding this in conf.d fixed this issue for me.
Options +Indexes +FollowSymLinks
The problem is that you compiled the code with java 13 (class file 57), and the java runtime is set to java 8 (class file 52).
Assuming you have the JRE 13 installed in your local system, you could change your runtime from 52 to 57. That you can do with the plugin Choose Runtime. To install it go to File/Settings/Plugins
Once installed go to Help/Find Action, type "runtime" and select the jre 13 from the dropdown menu.
data.reindex(index=data.index[::-1])
or simply:
data.iloc[::-1]
will reverse your data frame, if you want to have a for
loop which goes from down to up you may do:
for idx in reversed(data.index):
print(idx, data.loc[idx, 'Even'], data.loc[idx, 'Odd'])
or
for idx in reversed(data.index):
print(idx, data.Even[idx], data.Odd[idx])
You are getting an error because reversed
first calls data.__len__()
which returns 6. Then it tries to call data[j - 1]
for j
in range(6, 0, -1)
, and the first call would be data[5]
; but in pandas dataframe data[5]
means column 5, and there is no column 5 so it will throw an exception. ( see docs )
No need to explicitly go to the end of line before doing a
, use A
;
Append text at the end of line [count] times
<ESC>GA
You need to put the files into an array in order to sort and find the last modified file.
$files = array();
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$files[filemtime($file)] = $file;
}
}
closedir($handle);
// sort
ksort($files);
// find the last modification
$reallyLastModified = end($files);
foreach($files as $file) {
$lastModified = date('F d Y, H:i:s',filemtime($file));
if(strlen($file)-strpos($file,".swf")== 4){
if ($file == $reallyLastModified) {
// do stuff for the real last modified file
}
echo "<tr><td><input type=\"checkbox\" name=\"box[]\"></td><td><a href=\"$file\" target=\"_blank\">$file</a></td><td>$lastModified</td></tr>";
}
}
}
Not tested, but that's how to do it.
The proper answer to your question is to use statistics.mean
. But for fun, here is a version of mean that does not use the len()
function, so it (like statistics.mean
) can be used on generators, which do not support len()
:
from functools import reduce
from operator import truediv
def ave(seq):
return truediv(*reduce(lambda a, b: (a[0] + b[1], b[0]),
enumerate(seq, start=1),
(0, 0)))
Static variables in C have the lifetime of the program.
If defined in a function, they have local scope, i.e. they can be accessed only inside those functions. The value of static variables is preserved between function calls.
For example:
void function()
{
static int var = 1;
var++;
printf("%d", var);
}
int main()
{
function(); // Call 1
function(); // Call 2
}
In the above program, var
is stored in the data segment. Its lifetime is the whole C program.
After function call 1, var
becomes 2. After function call 2, var
becomes 3.
The value of var
is not destroyed between functions calls.
If var
had between non static and local variable, it would be stored in the stack segment in the C program. Since the stack frame of the function is destroyed after the function returns, the value of var
is also destroyed.
Initialized static variables are stored in the data segment of the C program whereas uninitialized ones are stored in the BSS segment.
Another information about static: If a variable is global and static, it has the life time of the C program, but it has file scope. It is visible only in that file.
To try this:
static int x;
int main()
{
printf("Accessing in same file%d", x):
}
extern int x;
func()
{
printf("accessing in different file %d",x); // Not allowed, x has the file scope of file1.c
}
run gcc -c file1.c
gcc -c file2.c
Now try to link them using:
gcc -o output file1.o file2.o
It would give a linker error as x has the file scope of file1.c and the linker would not be able to resolve the reference to variable x used in file2.c.
References:
>>> takeClosest = lambda num,collection:min(collection,key=lambda x:abs(x-num))
>>> takeClosest(5,[4,1,88,44,3])
4
A lambda is a special way of writing an "anonymous" function (a function that doesn't have a name). You can assign it any name you want because a lambda is an expression.
The "long" way of writing the the above would be:
def takeClosest(num,collection):
return min(collection,key=lambda x:abs(x-num))
You can download the 10.7 Lion JDK from http://connect.apple.com.
Sign in and click the java
section on the right.
The jdk is installed into a different location then previous. This will result in IDEs (such as Eclipse) being unable to locate source code and javadocs.
At the time of writing the JDK ended up here:
/Library/Java/JavaVirtualMachines/1.6.0_26-b03-383.jdk/Contents/Home
Open up eclipse preferences and go to Java --> Installed JREs page
Rather than use the "JVM Contents (MacOS X Default) we will need to use the JDK location
At the time of writing Search is not aware of the new JDK location; we we will need to click on the Add button
From the Add JRE wizard choose "MacOS X VM" for the JRE Type
For the JRE Definition Page we need to fill in the following:
The other fields will now auto fill, with the default JRE name being "Home". You can quickly correct this to something more meaningful:
Finish the wizard and return to the Installed JREs page
Choose "System JDK" from the list
You can now develop normally with:
Personal understanding, in TensorFlow domain, logits are the values to be used as input to softmax. I came to this understanding based on this tensorflow tutorial.
https://www.tensorflow.org/tutorials/layers
Although it is true that logit is a function in maths(especially in statistics), I don't think that's the same 'logit' you are looking at. In the book Deep Learning by Ian Goodfellow, he mentioned,
The function s-1(x) is called the logit in statistics, but this term is more rarely used in machine learning. s-1(x) stands for the inverse function of logistic sigmoid function.
In TensorFlow, it is frequently seen as the name of last layer. In Chapter 10 of the book Hands-on Machine Learning with Scikit-learn and TensorFLow by Aurélien Géron, I came across this paragraph, which stated logits
layer clearly.
note that
logits
is the output of the neural network before going through the softmax activation function: for optimization reasons, we will handle the softmax computation later.
That is to say, although we use softmax as the activation function in the last layer in our design, for ease of computation, we take out logits
separately. This is because it is more efficient to calculate softmax
and cross-entropy
loss together. Remember that cross-entropy
is a cost function, not used in forward propagation.
Try redirecting the output to Out-Null. Like so,
$key = & 'gpg' --decrypt "secret.gpg" --quiet --no-verbose | out-null
This would do it.
public static void main(String[] args) {
double d = 12.349678;
int r = (int) Math.round(d*100);
double f = r / 100.0;
System.out.println(f);
}
You can short this method, it's easy to understand that's why I have written like this.
Make sure you have below features are installed in order
Also you may need to load
Add-Type -Path "C:\Program Files\Microsoft SQL Server\110\SDK\Assemblies\Microsoft.SqlServer.Smo.dll"
Add-Type -Path "C:\Program Files\Microsoft SQL Server\110\SDK\Assemblies\Microsoft.SqlServer.SqlWmiManagement.dll"
Components are declared, Modules are imported, and Services are provided. An example I'm working with:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {FormsModule} from '@angular/forms';
import { UserComponent } from './components/user/user.component';
import { StateService } from './services/state.service';
@NgModule({
declarations: [
AppComponent,
UserComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [ StateService ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Using Future described in above answers does the job, but a bit less significantly as f.get(), blocks the thread until it gets the result, which violates concurrency.
Best solution is to use Guava's ListenableFuture. An example :
ListenableFuture<Void> future = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(1, new NamedThreadFactory).submit(new Callable<Void>()
{
@Override
public Void call() throws Exception
{
someBackgroundTask();
}
});
Futures.addCallback(future, new FutureCallback<Long>()
{
@Override
public void onSuccess(Long result)
{
doSomething();
}
@Override
public void onFailure(Throwable t)
{
}
};
Referencing Qwerty's answer, if the destRow isnot null, sheet.shiftRows() will change the destRow's reference to the next row; so we should always create a new row:
if (destRow != null) {
sheet.shiftRows(destination, sheet.getLastRowNum(), 1);
}
destRow = sheet.createRow(destination);
Your code looks correct. My suggestion is that the database already thinks it's upgraded. If you executed the project after incrementing the version number, but before adding the execSQL
call, the database on your test device/emulator may already believe it's at version 2.
A quick way to verify this would be to change the version number to 3 -- if it upgrades after that, you know it was just because your device believed it was already upgraded.
Another trick is to use 2 popup windows instead of one. The 1st popup window will simply be a dummy view with translucent background which provides the dim effect. The 2nd popup window is your intended popup window.
Sequence while creating pop up windows: Show the dummy pop up window 1st and then the intended popup window.
Sequence while destroying: Dismiss the intended pop up window and then the dummy pop up window.
The best way to link these two is to add an OnDismissListener and override the onDismiss()
method of the intended to dimiss the dummy popup window from their.
Code for the dummy popup window:
fadepopup.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/fadePopup"
android:background="#AA000000">
</LinearLayout>
Show fade popup to dim the background
private PopupWindow dimBackground() {
LayoutInflater inflater = (LayoutInflater) EPGGRIDActivity.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View layout = inflater.inflate(R.layout.fadepopup,
(ViewGroup) findViewById(R.id.fadePopup));
PopupWindow fadePopup = new PopupWindow(layout, windowWidth, windowHeight, false);
fadePopup.showAtLocation(layout, Gravity.NO_GRAVITY, 0, 0);
return fadePopup;
}
I encountered a problem like this and it turns out that I accidentally changed the permission of the var/cache folder. Just delete the cache folder so magento could automatically create the folder with the right permissions.
rm -rf root/var/cache
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
http://www.tutorialspoint.com/mysql/mysql-date-time-functions.htm
use Date function directly. Hope it works
$.event.special.rightclick = {
bindType: "contextmenu",
delegateType: "contextmenu"
};
$(document).on("rightclick", "div", function() {
console.log("hello");
return false;
});
Based on Bluefeet's accepted response with an added nuance using OVER()
:
SELECT distributor_id,
COUNT(*) total,
SUM(case when level = 'exec' then 1 else 0 end) OVER() ExecCount,
SUM(case when level = 'personal' then 1 else 0 end) OVER () PersonalCount
FROM yourtable
GROUP BY distributor_id
Using OVER()
with nothing in the () will give you the total count for the whole dataset.
You need to use:
await client.PostAsync(uri, content);
Something like that:
var comment = "hello world";
var questionId = 1;
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("comment", comment),
new KeyValuePair<string, string>("questionId", questionId)
});
var myHttpClient = new HttpClient();
var response = await myHttpClient.PostAsync(uri.ToString(), formContent);
And if you need to get the response after post, you should use:
var stringContent = await response.Content.ReadAsStringAsync();
Hope it helps ;)
Just for the future reference, you just need to add System.Configuration
to your references library:
If using cocoapods, try reinstalling the pods by running the following command.
pod install
In case you want to increase the font of the labels of the histogram when setting labels=TRUE
bp=hist(values, labels = FALSE,
main='Histogram',
xlab='xlab',ylab='ylab', cex.main=2, cex.lab=2,cex.axis=2)
text(x=bp$mids, y=bp$counts, labels=bp$counts ,cex=2,pos=3)
Use: LOGGER.log(Level.INFO, "Got an exception.", e);
or LOGGER.info("Got an exception. " + e.getMessage())
;
SELECT *
FROM people
WHERE names ='SMITH'
ORDER BY names asc
limit 10
If you need add group by clause. If you search Smith you would have to sort on something else.
You can do the same with .ix
, like this:
In [1]: df = pd.DataFrame(np.random.randn(5,4), columns=list('abcd'))
In [2]: df
Out[2]:
a b c d
0 -0.323772 0.839542 0.173414 -1.341793
1 -1.001287 0.676910 0.465536 0.229544
2 0.963484 -0.905302 -0.435821 1.934512
3 0.266113 -0.034305 -0.110272 -0.720599
4 -0.522134 -0.913792 1.862832 0.314315
In [3]: df.ix[df.a>0, ['b','c']] = 0
In [4]: df
Out[4]:
a b c d
0 -0.323772 0.839542 0.173414 -1.341793
1 -1.001287 0.676910 0.465536 0.229544
2 0.963484 0.000000 0.000000 1.934512
3 0.266113 0.000000 0.000000 -0.720599
4 -0.522134 -0.913792 1.862832 0.314315
EDIT
After the extra information, the following will return all columns - where some condition is met - with halved values:
>> condition = df.a > 0
>> df[condition][[i for i in df.columns.values if i not in ['a']]].apply(lambda x: x/2)
I hope this helps!
Call the Below Action Method from your JS file (To get the ipv4 ip address).
[HttpGet]
public string GetIP()
{
IPAddress[] ipv4Addresses = Array.FindAll(
Dns.GetHostEntry(string.Empty).AddressList,
a => a.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);
return ipv4Addresses.ToString();
}
Check after keeping Breakpoint, and use as per your requirement. Its working fine for me.
Implement your own extension of DataGridViewTextBoxCell and override Paint method like this:
class MyDataGridViewTextBoxCell : DataGridViewTextBoxCell
{
protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex,
DataGridViewElementStates cellState, object value, object formattedValue, string errorText,
DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
{
if (value != null)
{
if ((bool) value)
{
cellStyle.BackColor = Color.LightGreen;
}
else
{
cellStyle.BackColor = Color.OrangeRed;
}
}
base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value,
formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);
}
}
Then in the code set CellTemplate property of your column to instance of your class
columns.Add(new DataGridViewTextBoxColumn() {CellTemplate = new MyDataGridViewTextBoxCell()});
They are technically the same thing, it's actually a different notation of using the provider
function of the $provide
service.
The only difference between the service
and the factory
notation is that the service is new-ed and the factory is not. But for everything else they both look, smell and behave the same. Again, it's just a shorthand for the $provide.provider function.
// Factory
angular.module('myApp').factory('myFactory', function() {
var _myPrivateValue = 123;
return {
privateValue: function() { return _myPrivateValue; }
};
});
// Service
function MyService() {
this._myPrivateValue = 123;
}
MyService.prototype.privateValue = function() {
return this._myPrivateValue;
};
angular.module('myApp').service('MyService', MyService);
The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc
A set of simple examples:
Using Gson:
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class Gson {
public static void main(String[] args) {
}
public HttpResponse http(String url, String body) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPost request = new HttpPost(url);
StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
com.google.gson.Gson gson = new com.google.gson.Gson();
Response respuesta = gson.fromJson(json, Response.class);
System.out.println(respuesta.getExample());
System.out.println(respuesta.getFr());
} catch (IOException ex) {
}
return null;
}
public class Response{
private String example;
private String fr;
public String getExample() {
return example;
}
public void setExample(String example) {
this.example = example;
}
public String getFr() {
return fr;
}
public void setFr(String fr) {
this.fr = fr;
}
}
}
Using json-simple:
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JsonSimple {
public static void main(String[] args) {
}
public HttpResponse http(String url, String body) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPost request = new HttpPost(url);
StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
try {
JSONParser parser = new JSONParser();
Object resultObject = parser.parse(json);
if (resultObject instanceof JSONArray) {
JSONArray array=(JSONArray)resultObject;
for (Object object : array) {
JSONObject obj =(JSONObject)object;
System.out.println(obj.get("example"));
System.out.println(obj.get("fr"));
}
}else if (resultObject instanceof JSONObject) {
JSONObject obj =(JSONObject)resultObject;
System.out.println(obj.get("example"));
System.out.println(obj.get("fr"));
}
} catch (Exception e) {
// TODO: handle exception
}
} catch (IOException ex) {
}
return null;
}
}
etc...