It's worth pointing out that if you have multiple Gmail accounts, you may want to use the URL approach because you can customize which account to compose from.
e.g.
https://mail.google.com/mail/u/0/#inbox?compose=new
https://mail.google.com/mail/u/1/#inbox?compose=new
Or if you know the email address you are sending from, replace the numeric index with the email address:
https://mail.google.com/mail/u/[email protected]/#inbox?compose=new
String input = EditTextinput.getText().toString();
input = input.replace(" ", "");
Sometimes you would want to remove only the spaces at the beginning or end of the String (not the ones in the middle). If that's the case you can use trim
:
input = input.trim();
Charles Bailey's answer is correct. The exact wording from the C++ standard is (§4.7/4): "If the source type is bool, the value false is converted to zero and the value true is converted to one."
Edit: I see he's added the reference as well -- I'll delete this shortly, if I don't get distracted and forget...
Edit2: Then again, it is probably worth noting that while the Boolean values themselves always convert to zero or one, a number of functions (especially from the C standard library) return values that are "basically Boolean", but represented as int
s that are normally only required to be zero to indicate false or non-zero to indicate true. For example, the is* functions in <ctype.h>
only require zero or non-zero, not necessarily zero or one.
If you cast that to bool
, zero will convert to false, and non-zero to true (as you'd expect).
Kenny is right, just want to clear some things out.
border.xml
and put it in the folder res/drawable/
add the code
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="4dp" android:color="#FF00FF00" />
<solid android:color="#ffffff" />
<padding android:left="7dp" android:top="7dp"
android:right="7dp" android:bottom="0dp" />
<corners android:radius="4dp" />
</shape>
set back ground like android:background="@drawable/border"
wherever you want the border
Mine first didn't work cause i put the border.xml
in the wrong folder!
It's not easy to find a full solution of the problem of a convertion of an arbitrary HTML to PDF with non-english letters in Android. I test it for russian unicode letters.
We use three libraries:
(1) Jsoup (jsoup-1.7.3.jar) for a convertion from HTML to XHTML,
(2) iTextPDF (itextpdf-5.5.0.jar),
(3) XMLWorker (xmlworker-5.5.1.jar).
public boolean createPDF(String rawHTML, String fileName, ContextWrapper context){
final String APPLICATION_PACKAGE_NAME = context.getBaseContext().getPackageName();
File path = new File( Environment.getExternalStorageDirectory(), APPLICATION_PACKAGE_NAME );
if ( !path.exists() ){ path.mkdir(); }
File file = new File(path, fileName);
try{
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
document.open();
// ?????????????? HTML
String htmlText = Jsoup.clean( rawHTML, Whitelist.relaxed() );
InputStream inputStream = new ByteArrayInputStream( htmlText.getBytes() );
// ???????? ???????? PDF
XMLWorkerHelper.getInstance().parseXHtml(writer, document,
inputStream, null, Charset.defaultCharset(), new MyFont());
document.close();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (DocumentException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
The difficult problem is to display russian letters in PDF by using iTextPDF XMLWorker library. For this we should create our own implementation of FontProvider interface:
public class MyFont implements FontProvider{
private static final String FONT_PATH = "/system/fonts/DroidSans.ttf";
private static final String FONT_ALIAS = "my_font";
public MyFont(){ FontFactory.register(FONT_PATH, FONT_ALIAS); }
@Override
public Font getFont(String fontname, String encoding, boolean embedded,
float size, int style, BaseColor color){
return FontFactory.getFont(FONT_ALIAS, BaseFont.IDENTITY_H,
BaseFont.EMBEDDED, size, style, color);
}
@Override
public boolean isRegistered(String name) { return name.equals( FONT_ALIAS ); }
}
Here we use the standard Android font Droid Sans, which is located in the system folder:
private static final String FONT_PATH = "/system/fonts/DroidSans.ttf";
Use first the method OpenTextFile
, and then...
either read the file at once with the method ReadAll
:
Set file = fso.OpenTextFile("C:\test.txt", 1)
content = file.ReadAll
or line by line with the method ReadLine
:
Set dict = CreateObject("Scripting.Dictionary")
Set file = fso.OpenTextFile ("c:\test.txt", 1)
row = 0
Do Until file.AtEndOfStream
line = file.Readline
dict.Add row, line
row = row + 1
Loop
file.Close
'Loop over it
For Each line in dict.Items
WScript.Echo line
Next
Click on No servers are available. Click this link to create a new server.
Click Finish.
Right click->Start
Now you can run your web applications on server.
/* while loop
5 bucks
1 chocolate = 1 bucks
while my money is greater than 1 bucks
select chocolate
pay 1 bucks to the shopkeeper
money = money - 1
end
come to home and cant go to while shop because my money = 0 bucks */
#include<stdio.h>
int main(){
int money = 5;
while( money >= 1){
printf("inside the shopk and selecting chocolate\n");
printf("after selecting chocolate paying 1 bucks\n");
money = money - 1 ;
printf("my remaining moeny = %d\n", money);
printf("\n\n");
}
printf("dont have money cant go inside the shop, money = %d", money);
return 0;
}
infinite money
while( codition ){ // condition will always true ....infinite loop
statement(s)
}
please visit this video for better understanding https://www.youtube.com/watch?v=eqDv2wxDMJ8&t=25s
/* for loop
5 bucks
for my money is greater than equal to 1 bucks 0 money >= 1
select chocolate
pay 1 bucks to the shopkeeper
money = money - 1 1-1 => 0
end
*/
#include<stdio.h>
int main(){
int money = 5;
for( ; money >= 1; ){ 0>=1 false
printf("select chocolate \n");
printf("paying 1 bucks to the shopkeeper\n");
money = money - 1; 1-1 = 0
printf(" remaining money =%d\n", money);
printf("\n\n");
}
return 0;
}
For better understanding please visit https://www.youtube.com/watch?v=_vdvyzzp-R4&t=25s
Yes. Class can have private constructor. Even abstract class can have private constructor.
By making constructor private, we prevent the class from being instantiated as well as subclassing of that class.
Here are some of the uses of private constructor :
A cleaner alternative would be to use a Dictionary
to handle parameters. They are key-value pairs after all.
private static readonly HttpClient httpclient;
static MyClassName()
{
// HttpClient is intended to be instantiated once and re-used throughout the life of an application.
// Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads.
// This will result in SocketException errors.
// https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.7.1
httpclient = new HttpClient();
}
var url = "http://myserver/method";
var parameters = new Dictionary<string, string> { { "param1", "1" }, { "param2", "2" } };
var encodedContent = new FormUrlEncodedContent (parameters);
var response = await httpclient.PostAsync (url, encodedContent).ConfigureAwait (false);
if (response.StatusCode == HttpStatusCode.OK) {
// Do something with response. Example get content:
// var responseContent = await response.Content.ReadAsStringAsync ().ConfigureAwait (false);
}
Also dont forget to Dispose()
httpclient, if you dont use the keyword using
As stated in the Remarks section of the HttpClient class in the Microsoft docs, HttpClient should be instantiated once and re-used.
Edit:
You may want to look into response.EnsureSuccessStatusCode();
instead of if (response.StatusCode == HttpStatusCode.OK)
.
You may want to keep your httpclient and dont Dispose()
it. See: Do HttpClient and HttpClientHandler have to be disposed?
Edit:
Do not worry about using .ConfigureAwait(false) in .NET Core. For more details look at https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html
For anyone coming to this question wondering how to do this in Eclipse, You can remove the displayed text from the logCat using the button provided (often has a red X on the icon)
The exec
family of functions make your process execute a different program, replacing the old program it was running. I.e., if you call
execl("/bin/ls", "ls", NULL);
then the ls
program is executed with the process id, current working dir and user/group (access rights) of the process that called execl
. Afterwards, the original program is not running anymore.
To start a new process, the fork
system call is used. To execute a program without replacing the original, you need to fork
, then exec
.
Just pass mute=1
.
For example:
<iframe id="myVideo" src="https://www.youtube.com/embed/k0DN-BZrM4o?rel=0&autoplay=1;mute=1" width="100%" height="600" frameborder="0" allowfullscreen></iframe>
Fundamentally you hadn't declare location which is what nginx uses to bind URL with resources.
server {
listen 80;
server_name localhost;
access_log logs/localhost.access.log main;
location / {
root /var/www/board/public;
index index.html index.htm index.php;
}
}
This same issue happened to me when I had more than one API function in the module and tried to wrap each function with 2 decorators:
I got this same exception because I tried to wrap more than one function with those two decorators:
@app.route("/path1")
@exception_handler
def func1():
pass
@app.route("/path2")
@exception_handler
def func2():
pass
Specifically, it is caused by trying to register a few functions with the name wrapper:
def exception_handler(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
error_code = getattr(e, "code", 500)
logger.exception("Service exception: %s", e)
r = dict_to_json({"message": e.message, "matches": e.message, "error_code": error_code})
return Response(r, status=error_code, mimetype='application/json')
return wrapper
Changing the name of the function solved it for me (wrapper.__name__ = func.__name__):
def exception_handler(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
error_code = getattr(e, "code", 500)
logger.exception("Service exception: %s", e)
r = dict_to_json({"message": e.message, "matches": e.message, "error_code": error_code})
return Response(r, status=error_code, mimetype='application/json')
# Renaming the function name:
wrapper.__name__ = func.__name__
return wrapper
Then, decorating more than one endpoint worked.
see this http://www.codeproject.com/Articles/3389/Read-write-and-delete-from-registry-with-C
Updated:
You can use RegistryKey
class under Microsoft.Win32
namespace.
Some important functions of RegistryKey
are as follows:
GetValue //to get value of a key
SetValue //to set value to a key
DeleteValue //to delete value of a key
OpenSubKey //to read value of a subkey (read-only)
CreateSubKey //to create new or edit value to a subkey
DeleteSubKey //to delete a subkey
GetValueKind //to retrieve the datatype of registry key
It will be very helpful to get current date and time.
var date=new Date();
var today=new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toISOString().replace(/T/, ' ').replace(/\..+/, '');
In C/C++ you have header files (*.H). There you declare your functions/classes. So for example you will have to #include "second.h"
to your main.cpp
file.
In second.h
you just declare like this void yourFunction();
In second.cpp
you implement it like
void yourFunction() {
doSomethng();
}
Don't forget to #include "second.h"
also in the beginning of second.cpp
Hope this helps:)
Have a look at monit (http://mmonit.com/monit/). It handles start, stop and restart of your script and can do health checks plus restarts if necessary.
Or do a simple script:
while true
do
/your/script
sleep 1
done
Please also note that on certain environments and conditions (such as running on windows on dispatch level >= DISPATCH LEVEL), you cannot use mutex but rather spinlock. On unix - same thing.
Here is equivalent question on competitor stackexchange unix site: https://unix.stackexchange.com/questions/5107/why-are-spin-locks-good-choices-in-linux-kernel-design-instead-of-something-more
Info on dispatching on windows systems: http://download.microsoft.com/download/e/b/a/eba1050f-a31d-436b-9281-92cdfeae4b45/IRQL_thread.doc
You could alter the figsize
by passing a tuple
showing the width, height
parameters you would like to keep.
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(10,10)) # Sample figsize in inches
sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5, ax=ax)
EDIT
I remember answering a similar question of yours where you had to set the index as TIMESTAMP
. So, you could then do something like below:
df = df.set_index('TIMESTAMP')
df.resample('30min').mean()
fig, ax = plt.subplots()
ax = sns.heatmap(df.iloc[:, 1:6:], annot=True, linewidths=.5)
ax.set_yticklabels([i.strftime("%Y-%m-%d %H:%M:%S") for i in df.index], rotation=0)
For the head
of the dataframe you posted, the plot would look like:
Annoyingly, the withTimeAtStartOfDay answer is wrong, but only occasionally. You want:
Days.daysBetween(start.toLocalDate(), end.toLocalDate()).getDays()
It turns out that "midnight/start of day" sometimes means 1am (daylight savings happen this way in some places), which Days.daysBetween doesn't handle properly.
// 5am on the 20th to 1pm on the 21st, October 2013, Brazil
DateTimeZone BRAZIL = DateTimeZone.forID("America/Sao_Paulo");
DateTime start = new DateTime(2013, 10, 20, 5, 0, 0, BRAZIL);
DateTime end = new DateTime(2013, 10, 21, 13, 0, 0, BRAZIL);
System.out.println(daysBetween(start.withTimeAtStartOfDay(),
end.withTimeAtStartOfDay()).getDays());
// prints 0
System.out.println(daysBetween(start.toLocalDate(),
end.toLocalDate()).getDays());
// prints 1
Going via a LocalDate
sidesteps the whole issue.
My turn:
https://play.golang.org/p/RifHKsX7Puh
package main
import (
"fmt"
"time"
)
func main() {
var n int = 77
v := time.Duration( 1.15 * float64(n) ) * time.Second
fmt.Printf("%v %T", v, v)
}
It helps to remember the simple fact, that underlyingly the time.Duration is a mere int64, which holds nanoseconds value.
This way, conversion to/from time.Duration becomes a formality. Just remember:
I'm very surprised nobody has suggested collection initializers. This way can only add objects when the list is created hence the name however it seems like the nicest way of doing it. No need to create an array then convert it to a list.
var list = new List<dynamic>()
{
new { Id = 1, Name = "Foo" },
new { Id = 2, Name = "Bar" }
};
You can always use object
instead of dynamic
but trying to keep it in a true generic way then dynamic
makes more sense.
var result;_x000D_
result = "1,2,3".split(","); _x000D_
console.log(result);
_x000D_
More info on W3Schools describing the String Split function.
Use a BinaryReader object to return a byte array from the stream like:
byte[] fileData = null;
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}
In principle, you can style it using option[selected] as selector, but that doesn't work in many browsers. Also, that only allows you to style the selected option, not the option that has hover focus.
Tested to work in Chrome 9 and Firefox 3.6, doesn't work in Internet Explorer 8.
if you think you followed everything good but still unlucky, just make sure you/capistrano run touch tmp/restart.txt or equivalent at the end. I was in the unlucky list but now :)
Here's what I did:
That's it. I have tested it with my Nokia and it's working for me.
According to documentation:
random.sample(population, k)
Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.
Basically, it picks k unique random elements, a sample, from a sequence:
>>> import random
>>> c = list(range(0, 15))
>>> c
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> random.sample(c, 5)
[9, 2, 3, 14, 11]
random.sample
works also directly from a range:
>>> c = range(0, 15)
>>> c
range(0, 15)
>>> random.sample(c, 5)
[12, 3, 6, 14, 10]
In addition to sequences, random.sample
works with sets too:
>>> c = {1, 2, 4}
>>> random.sample(c, 2)
[4, 1]
However, random.sample
doesn't work with arbitrary iterators:
>>> c = [1, 3]
>>> random.sample(iter(c), 5)
TypeError: Population must be a sequence or set. For dicts, use list(d).
Approach 1
File > Settings... > Build, Execution, Deployment > Build Tools > Maven > Importing > check Import Maven projects automatically
Approach 2
Approach 1
Approach 2
You won't be able to make an ajax call to http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml
from a file deployed at http://run.jsbin.com
due to the same-origin policy.
As the source (aka origin) page and the target URL are at different domains (run.jsbin.com
and www.ecb.europa.eu
), your code is actually attempting to make a Cross-domain (CORS) request, not an ordinary GET
.
In a few words, the same-origin policy says that browsers should only allow ajax calls to services at the same domain of the HTML page.
A page at http://www.example.com/myPage.html
can only directly request services that are at http://www.example.com
, like http://www.example.com/api/myService
. If the service is hosted at another domain (say http://www.ok.com/api/myService
), the browser won't make the call directly (as you'd expect). Instead, it will try to make a CORS request.
To put it shortly, to perform a (CORS) request* across different domains, your browser:
Origin
header in the original request (with the page's domain as value) and perform it as usual; and thenAccess-Control-Allow-Origin
is one of them) allowing the CORS request, the browse will complete the call (almost** exactly the way it would if the HTML page was at the same domain).
* The above depicts the steps in a simple request, such as a regular GET
with no fancy headers. If the request is not simple (like a POST
with application/json
as content type), the browser will hold it a moment, and, before fulfilling it, will first send an OPTIONS
request to the target URL. Like above, it only will continue if the response to this OPTIONS
request contains the CORS headers. This OPTIONS
call is known as preflight request.
** I'm saying almost because there are other differences between regular calls and CORS calls. An important one is that some headers, even if present in the response, will not be picked up by the browser if they aren't included in the Access-Control-Expose-Headers
header.
Was it just a typo? Sometimes the JavaScript code has just a typo in the target domain. Have you checked? If the page is at www.example.com
it will only make regular calls to www.example.com
! Other URLs, such as api.example.com
or even example.com
or www.example.com:8080
are considered different domains by the browser! Yes, if the port is different, then it is a different domain!
Add the headers. The simplest way to enable CORS is by adding the necessary headers (as Access-Control-Allow-Origin
) to the server's responses. (Each server/language has a way to do that - check some solutions here.)
Last resort: If you don't have server-side access to the service, you can also mirror it (through tools such as reverse proxies), and include all the necessary headers there.
It is simple. The first thing that you have to understand the design of the Python interpreter. It doesn't allocate memory for all the variables basically if any two or more variable has the same value it just map to that value.
let's go to the code example,
In [6]: a = 10
In [7]: id(a)
Out[7]: 10914656
In [8]: b = 10
In [9]: id(b)
Out[9]: 10914656
In [10]: c = 11
In [11]: id(c)
Out[11]: 10914688
In [12]: d = 21
In [13]: id(d)
Out[13]: 10915008
In [14]: e = 11
In [15]: id(e)
Out[15]: 10914688
In [16]: e = 21
In [17]: id(e)
Out[17]: 10915008
In [18]: e is d
Out[18]: True
In [19]: e = 30
In [20]: id(e)
Out[20]: 10915296
From the above output, variables a and b shares the same memory, c and d has different memory when I create a new variable e and store a value (11) which is already present in the variable c so it mapped to that memory location and doesn't create a new memory when I change the value present in the variable e to 21 which is already present in the variable d so now variables d and e share the same memory location. At last, I change the value in the variable e to 30 which is not stored in any other variable so it creates a new memory for e.
so any variable which is having same value shares the memory.
Not for list and dictionary objects
let's come to your question.
when multiple keys have same value then all shares same memory so the thing that you expect is already there in python.
you can simply use it like this
In [49]: dictionary = {
...: 'k1':1,
...: 'k2':1,
...: 'k3':2,
...: 'k4':2}
...:
...:
In [50]: id(dictionary['k1'])
Out[50]: 10914368
In [51]: id(dictionary['k2'])
Out[51]: 10914368
In [52]: id(dictionary['k3'])
Out[52]: 10914400
In [53]: id(dictionary['k4'])
Out[53]: 10914400
From the above output, the key k1 and k2 mapped to the same address which means value one stored only once in the memory which is multiple key single value dictionary this is the thing you want. :P
The accepted answer is not complete without the remainder of instructions (paraphrased below) from the forum thread linked to:
cd /etc/php5/conf.d
cat > sqlite3.ini
# configuration for php SQLite3 module
extension=sqlite3.so
^D
sudo /etc/init.d/apache2 restart
Prior to running python, type cd
in the commmand line, and it will tell you the directory you are currently in. When python runs, it can only access files in this directory. hello.py
needs to be in this directory, so you can move hello.py
from its existing location to this folder as you would move any other file in Windows or you can change directories and run python in the directory hello.py
is.
Edit: Python cannot access the files in the subdirectory unless a path to it provided. You can access files in any directory by providing the path. python C:\Python27\Projects\hello.p
First and foremost, I highly suggest using a profiler or atleast use timeit.
However if you wanted to write your own timing method strictly to learn, here is somewhere to get started using a decorator.
Python 2:
def timing(f):
def wrap(*args):
time1 = time.time()
ret = f(*args)
time2 = time.time()
print '%s function took %0.3f ms' % (f.func_name, (time2-time1)*1000.0)
return ret
return wrap
And the usage is very simple, just use the @timing decorator:
@timing
def do_work():
#code
Python 3:
def timing(f):
def wrap(*args, **kwargs):
time1 = time.time()
ret = f(*args, **kwargs)
time2 = time.time()
print('{:s} function took {:.3f} ms'.format(f.__name__, (time2-time1)*1000.0))
return ret
return wrap
Note I'm calling f.func_name
to get the function name as a string(in Python 2), or f.__name__
in Python 3.
The insert or replace query would insert a new record if id=1 does not already exist.
The update query would only oudate id=1 if it aready exist, it would not create a new record if it didn't exist.
Maybe this will be helpful for answering the question: Count of days in given year,
new DateTime(anyDate.Year, 12, 31).DayOfYear //will include leap years too
Regarding DateTime.DayOfYear Property.
I am using Tortoise Git and simply going to Git in Settings and applying the same settings to Global. Apply and Ok. Worked for me.
Just set
webView.mediaPlaybackRequiresUserAction = NO;
The autoplay works for me on iOS.
I'm working on an app and face issue of killing my service by on app kill. I researched on google and found that I have to make it foreground. following is the code:
public class UpdateLocationAndPrayerTimes extends Service {
Context context;
@Override
public void onCreate() {
super.onCreate();
context = this;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
StartForground();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void StartForground() {
LocationChangeDetector locationChangeDetector = new LocationChangeDetector(context);
locationChangeDetector.getLatAndLong();
Notification notification = new NotificationCompat.Builder(this)
.setOngoing(false)
.setSmallIcon(android.R.color.transparent)
//.setSmallIcon(R.drawable.picture)
.build();
startForeground(101, notification);
}
}
hops that it may helps!!!!
Didn't see an example of both in one query. So this example might help.
/**
INTERNATIONAL_ORDERS - table of orders by company by location by day
companyId, country, city, total, date
**/
SELECT country, city, sum(total) totalCityOrders
FROM INTERNATIONAL_ORDERS with (nolock)
WHERE companyId = 884501253109
GROUP BY country, city
HAVING country = 'MX'
ORDER BY sum(total) DESC
This filters the table first by the companyId, then groups it (by country and city) and additionally filters it down to just city aggregations of Mexico. The companyId was not needed in the aggregation but we were able to use WHERE to filter out just the rows we wanted before using GROUP BY.
You can use the existing split function
One easy and choppy exemple:
var str = '<p> example ive got a string</P>';
var substr = str.split('<p> ');
// substr[0] contains ""
// substr[1] contains "example ive got a string</P>"
var substr2 = substr [1].split('</p>');
// substr2[0] contains "example ive got a string"
// substr2[1] contains ""
The example is just to show you how the split works.
Go to Settings (or Preferences in Mac) > Editor > General > Change font size (Zoom) with Ctrl+Mouse Wheel OR Press "Cmd+Shift+A" for mac.
This will allow you to quickly modify the font size whenever you want. However, the font will get reset to the default size the next time you start Android Studio. (The Control+Mouse Wheel functionality will not get reset, though. You only need to do this once.)
Go to Settings > Editor > Colors & Fonts > Font. Click "Save As..." and choose a new scheme name. Then change the font size and say OK. This will be the default size every time you open Android Studio now.
It seems the problem is that /
is not floor operation.
int mod(int m, float n)
{
return m - floor(m/n)*n;
}
Here's a minimalist way to do it.
System.out.print("Please enter an integer: ");
while(!scan.hasNextInt()) scan.next();
int demoInt = scan.nextInt();
You need a BroadcastReceiver for ACTION_PHONE_STATE_CHANGED
This will call your received whenever the phone-state changes from idle, ringing, offhook so from the previous value and the new value you can detect if this is an incoming/outgoing call.
Required permission would be:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
But if you also want to receive the EXTRA_INCOMING_NUMBER in that broadcast, you'll need another permission: "android.permission.READ_CALL_LOG"
And the code something like this:
val receiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Log.d(TAG, "onReceive")
}
}
override fun onResume() {
val filter = IntentFilter()
filter.addAction("android.intent.action.PHONE_STATE")
registerReceiver(receiver, filter)
super.onResume()
}
override fun onPause() {
unregisterReceiver(receiver)
super.onPause()
}
and in receiver class, we can get current state by reading intent like this:
intent.extras["state"]
the result of extras could be:
RINGING -> If your phone is ringing
OFFHOOK -> If you are talking with someone (Incoming or Outcoming call)
IDLE -> if call ended (Incoming or Outcoming call)
With PHONE_STATE broadcast we don't need to use PROCESS_OUTGOING_CALLS permission or deprecated NEW_OUTGOING_CALL action.
I'm late to this party but I'd like to add one bit to user756519's thorough, excellent answer. I don't believe the "RetainSameConnection on the Connection Manager" property is relevant in this instance based on my recent experience. In my case, the relevant point was their advice to set "ValidateExternalMetadata" to False.
I'm using a temp table to facilitate copying data from one database (and server) to another, hence the reason "RetainSameConnection" was not relevant in my particular case. And I don't believe it is important to accomplish what is happening in this example either, as thorough as it is.
git format-patch
also has the -B
flag.
The description in the man page leaves much to be desired, but in simple language it's the threshold format-patch will abide to before doing a total re-write of the file (by a single deletion of everything old, followed by a single insertion of everything new).
This proved very useful for me when manual editing was too cumbersome, and the source was more authoritative than my destination.
An example:
git format-patch -B10% --stdout my_tag_name > big_patch.patch
git am -3 -i < big_patch.patch
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import java.util.concurrent.TimeUnit;
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1)
@Fork(value = 1)
@Measurement(iterations = 5, time = 1)
public class StringFirstCharBenchmark {
private String source;
@Setup
public void init() {
source = "MALE";
}
@Benchmark
public String substring() {
return source.substring(0, 1);
}
@Benchmark
public String indexOf() {
return String.valueOf(source.indexOf(0));
}
}
Results:
+----------------------------------------------------------------------+
| Benchmark Mode Cnt Score Error Units |
+----------------------------------------------------------------------+
| StringFirstCharBenchmark.indexOf avgt 5 23.777 ? 5.788 ns/op |
| StringFirstCharBenchmark.substring avgt 5 11.305 ? 1.411 ns/op |
+----------------------------------------------------------------------+
Edit /etc/paths
. Then close the terminal and reopen it.
$ sudo vi /etc/paths
Note: each entry is seperated by line breaks.
/usr/local/bin
/usr/bin
/bin
/usr/sbin
/sbin
How about,
select
col1,
col2,
null col3,
null col4
from Table1
union all
select
null col1,
null col2,
col4 col3,
col5 col4
from Table2;
How about this :
@client = TinyTds::Client.new(
:adapter => 'mysql2',
:host => 'host',
:database => 'siteconfig_development',
:username => 'username',
:password => 'password'
sql = "SELECT * FROM users"
result = @client.execute(sql)
results.each do |row|
puts row[0]
end
You need to have TinyTds gem installed, since you didn't specify it in your question I didn't use Active Record
In Class1:
Class2 inst = new Class2();
inst.UpdateEmployee();
I had this error too, my problem was in some part of code I didn't close file descriptor and in other part, I tried to open that file!!
use close(fd)
system call after you finished working on a file.
import requests
r = requests.get("https://stackoverflow.com")
data = r.content # Content of response
print r.status_code # Status code of response
print data
Pyspark does include a dropDuplicates()
method, which was introduced in 1.4. https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.DataFrame.dropDuplicates
>>> from pyspark.sql import Row
>>> df = sc.parallelize([ \
... Row(name='Alice', age=5, height=80), \
... Row(name='Alice', age=5, height=80), \
... Row(name='Alice', age=10, height=80)]).toDF()
>>> df.dropDuplicates().show()
+---+------+-----+
|age|height| name|
+---+------+-----+
| 5| 80|Alice|
| 10| 80|Alice|
+---+------+-----+
>>> df.dropDuplicates(['name', 'height']).show()
+---+------+-----+
|age|height| name|
+---+------+-----+
| 5| 80|Alice|
+---+------+-----+
Make sure you have mod_rewrite enabled.
restart apache
and clear cookies of your browser for read again at .htaccess
Open the console and then enter:
keys(window)
to see variablesdir(window)
to see objects This is a simple timer class in swift that enables you to:
SimpleTimer(interval: 3,repeats: true){print("tick")}.start()//Ticks every 3 secs
class SimpleTimer {/*<--was named Timer, but since swift 3, NSTimer is now Timer*/
typealias Tick = ()->Void
var timer:Timer?
var interval:TimeInterval /*in seconds*/
var repeats:Bool
var tick:Tick
init( interval:TimeInterval, repeats:Bool = false, onTick:@escaping Tick){
self.interval = interval
self.repeats = repeats
self.tick = onTick
}
func start(){
timer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(update), userInfo: nil, repeats: true)//swift 3 upgrade
}
func stop(){
if(timer != nil){timer!.invalidate()}
}
/**
* This method must be in the public or scope
*/
@objc func update() {
tick()
}
}
ul {
list-style-type: none;
}
ul li:before {
content:'*'; /* Change this to unicode as needed*/
width: 1em !important;
margin-left: -1em;
display: inline-block;
}
For infinite Fade In and Out
AlphaAnimation fadeIn=new AlphaAnimation(0,1);
AlphaAnimation fadeOut=new AlphaAnimation(1,0);
final AnimationSet set = new AnimationSet(false);
set.addAnimation(fadeIn);
set.addAnimation(fadeOut);
fadeOut.setStartOffset(2000);
set.setDuration(2000);
imageView.startAnimation(set);
set.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) { }
@Override
public void onAnimationRepeat(Animation animation) { }
@Override
public void onAnimationEnd(Animation animation) {
imageView.startAnimation(set);
}
});
USE
Validators.min(5)
It can be used while creating a formGroup variable along with other validators, as in
dueAmount:
['', [Validators.required, Validators.pattern(/^[+]?([0-9]+(?:[\.][0-9]*)?|\.[0-9]+)$/), Validators.min(5)]]
Not sure if it is in Angular 2, but is available in Angular 5
A struct (without a typedef) often needs to (or should) be with the keyword struct when used.
struct A; // forward declaration
void function( struct A *a ); // using the 'incomplete' type only as pointer
If you typedef your struct you can leave out the struct keyword.
typedef struct A A; // forward declaration *and* typedef
void function( A *a );
Note that it is legal to reuse the struct name
Try changing the forward declaration to this in your code:
typedef struct context context;
It might be more readable to do add a suffix to indicate struct name and type name:
typedef struct context_s context_t;
The download from java.com
which installs in /Library/Internet Plug-Ins
is only the JRE, for development you probably want to download the JDK from http://www.oracle.com/technetwork/java/javase/downloads/index.html and install that instead. This will install the JDK at /Library/Java/JavaVirtualMachines/jdk1.7.0_<something>.jdk/Contents/Home
which you can then add to Eclipse via Preferences -> Java -> Installed JREs.
You don't need jQuery for this, as simple javascript will suffice:
alert(document.domain);
See it in action:
console.log("Output;"); _x000D_
console.log(location.hostname);_x000D_
console.log(document.domain);_x000D_
alert(window.location.hostname)_x000D_
_x000D_
console.log("document.URL : "+document.URL);_x000D_
console.log("document.location.href : "+document.location.href);_x000D_
console.log("document.location.origin : "+document.location.origin);_x000D_
console.log("document.location.hostname : "+document.location.hostname);_x000D_
console.log("document.location.host : "+document.location.host);_x000D_
console.log("document.location.pathname : "+document.location.pathname);
_x000D_
For further domain-related values, check out the properties of window.location
online. You may find that location.host
is a better option, as its content could differ from document.domain
. For instance, the url http://192.168.1.80:8080
will have only the ipaddress in document.domain
, but both the ipaddress and port number in location.host
.
The above mentioned answers are correct but I am simplifying it for noobs like me.Go to your project's pom file. Add a new property exec.mainClass
and give its value as the class which contains your main method. For me it was DriverClass
in mainpkg
. Change it as per your project.
Having done this navigate to the folder that contains your project's pom.xml
and run this on the command prompt mvn exec:java
. This should call the main method.
<input name="submitBnt" type="submit" value="like"/>
name is useful when using $_POST
in php and also in javascript as document.getElementByName('submitBnt')
.
Also you can use name as a CS selector like input[name="submitBnt"]
;
Hope this helps
Call JObject's ToString(Formatting.None)
method.
Alternatively if you pass the object to the JsonConvert.SerializeObject method it will return the JSON without formatting.
Documentation: Write JSON text with JToken.ToString
http://msdn.microsoft.com/en-us/library/wkze6zky.aspx
menu: Project-->Add Reference
click: assemblies, framework
Put a checkmark on Microsoft.VisualBasic.
Hit OK.
That link is for Visual Studio 2013, you can use the "Other versions" dropdown for different versions of visual studio.
In all cases you need to add a reference to the .NET assembly "Microsoft.VisualBasic".
At the top of your c# file you neeed:
using Microsoft.VisualBasic;
Then you can look at writing the code.
The code would be something like:
private void btnOK_Click(object sender, EventArgs e)
{
if ( Information.IsNumeric(startingbudget) )
{
MessageBox.Show("This is a number.");
}
}
This will validate with HTML5.
<form action="#">
You may use:
To create array of objects:
var source = ['left', 'top'];
const result = source.map(arrValue => ({[arrValue]: 0}));
Demo:
var source = ['left', 'top'];_x000D_
_x000D_
const result = source.map(value => ({[value]: 0}));_x000D_
_x000D_
console.log(result);
_x000D_
Or if you wants to create a single object from values of arrays:
var source = ['left', 'top'];
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});
Demo:
var source = ['left', 'top'];_x000D_
_x000D_
const result = source.reduce((obj, arrValue) => (obj[arrValue] = 0, obj), {});_x000D_
_x000D_
console.log(result);
_x000D_
In Swift, this code inside the UIPageViewController is getting a reference to the page indicator and setting its properties
override func viewDidLoad() {
super.viewDidLoad()
//Creating the proxy
let pageControl = UIPageControl.appearance()
//Customizing
pageControl.pageIndicatorTintColor = UIColor.lightGrayColor()
pageControl.currentPageIndicatorTintColor = UIColor.darkGrayColor()
//Setting the background of the view controller so the dots wont be on a black background
self.view.backgroundColor = UIColor.whiteColor()
}
It took me a while to implement the other responses, as I'm using Angular 8 (tested up to 10). I ended up with the following code (heavily inspired by Hasan).
Note that for the name to be set, the header Access-Control-Expose-Headers
MUST include Content-Disposition
. To set this in django RF:
http_response = HttpResponse(package, content_type='application/javascript')
http_response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
http_response['Access-Control-Expose-Headers'] = "Content-Disposition"
In angular:
// component.ts
// getFileName not necessary, you can just set this as a string if you wish
getFileName(response: HttpResponse<Blob>) {
let filename: string;
try {
const contentDisposition: string = response.headers.get('content-disposition');
const r = /(?:filename=")(.+)(?:")/
filename = r.exec(contentDisposition)[1];
}
catch (e) {
filename = 'myfile.txt'
}
return filename
}
downloadFile() {
this._fileService.downloadFile(this.file.uuid)
.subscribe(
(response: HttpResponse<Blob>) => {
let filename: string = this.getFileName(response)
let binaryData = [];
binaryData.push(response.body);
let downloadLink = document.createElement('a');
downloadLink.href = window.URL.createObjectURL(new Blob(binaryData, { type: 'blob' }));
downloadLink.setAttribute('download', filename);
document.body.appendChild(downloadLink);
downloadLink.click();
}
)
}
// service.ts
downloadFile(uuid: string) {
return this._http.get<Blob>(`${environment.apiUrl}/api/v1/file/${uuid}/package/`, { observe: 'response', responseType: 'blob' as 'json' })
}
In my case value was not an integer but a String. getNameByCode method can be added to the enum to get name of a String value-
enum CODE {
SUCCESS("SCS"), DELETE("DEL");
private String status;
/**
* @return the status
*/
public String getStatus() {
return status;
}
/**
* @param status
* the status to set
*/
public void setStatus(String status) {
this.status = status;
}
private CODE(String status) {
this.status = status;
}
public static String getNameByCode(String code) {
for (int i = 0; i < CODE.values().length; i++) {
if (code.equals(CODE.values()[i].status))
return CODE.values()[i].name();
}
return null;
}
You can also close the application:
Application.Exit();
It will end the processes.
It's recommended to put the image to the resources, than you can use it like this:
imageView = new ImageView("/gui.img/img.jpg");
The other answers didn't work for me. I found the answer in their documentation:
http://api.highcharts.com/highcharts#Series
Using this method (see JSFiddle example):
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container'
},
series: [{
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
}]
});
// the button action
$('#button').click(function() {
chart.series[0].setData([129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4, 29.9, 71.5, 106.4] );
});
$(document).ready(function(){ contsize();});
$(window).bind("resize",function(){contsize();});
function contsize()
{
var h = window.innerHeight;
var calculatecontsize = h - 70;/*if header and footer heights= 35 then total 70px*/
$('#content').css({"height":calculatecontsize + "px"} );
}
Installing Ruby gems on a Mac is a common source of confusion and frustration. Unfortunately, most solutions are incomplete, outdated, and provide bad advice. I'm glad the accepted answer here says to NOT use sudo
, which you should never need to do, especially if you don't understand what it does. While I used RVM years ago, I would recommend chruby
in 2020.
Some of the other answers here provide alternative options for installing gems, but they don't mention the limitations of those solutions. What's missing is an explanation and comparison of the various options and why you might choose one over the other. I've attempted to cover most common scenarios in my definitive guide to installing Ruby gems on a Mac.
This stuff comes from ES file explorer
Just go into this app > settings
Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good
Maybe below sample project helps you;
https://github.com/reinaldoarrosi/MaskedEditText
That project contains a view class call MaskedEditText
. As first, you should add it in your project.
Then you add below xml part in res/values/attrs.xml file of project;
<resources>
<declare-styleable name="MaskedEditText">
<attr name="mask" format="string" />
<attr name="placeholder" format="string" />
</declare-styleable>
</resources>
Then you will be ready to use MaskedEditText
view.
As last, you should add MaskedEditText in your xml file what you want like below;
<packagename.currentfolder.MaskedEditText
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/maskedEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:text="5"
app:mask="(999) 999-9999"
app:placeholder="_" >
Of course that, you can use it programmatically.
After those steps, adding MaskedEditText
will appear like below;
As programmatically, if you want to take it's text value as unmasked, you may use below row;
maskedEditText.getText(true);
To take masked value, you may send false
value instead of true
value in the getText
method.
You can kill Jenkins safely. It will catch SIGTERM and SIGINT and perform an orderly shutdown. However, if Jenkins was in the middle of building something, it will abort the builds and they will show up gray in the status display.
If you want to avoid this, you must put Jenkins into shutdown mode to prevent it from starting new builds and wait until currently running builds are done before killing Jenkins.
You can also use the Jenkins command line interface and tell Jenkins to safe-shutdown, which does the same. You can find more info on Jenkins cli at http://YOURJENKINS/cli
I use .map for foreach. For example
success: function(data) {
let dataItems = JSON.parse(data)
dataItems = dataItems.map((item) => {
return $(`<article>
<h2>${item.post_title}</h2>
<p>${item.post_excerpt}</p>
</article>`)
})
},
The reason to prefer Promises over callback functions is to have multiple callbacks and to avoid the problems like Callback Hell.
Callback hell (for more details, refer http://callbackhell.com/): Asynchronous javascript, or javascript that uses callbacks, is hard to get right intuitively. A lot of code ends up looking like this:
asyncCall(function(err, data1){
if(err) return callback(err);
anotherAsyncCall(function(err2, data2){
if(err2) return calllback(err2);
oneMoreAsyncCall(function(err3, data3){
if(err3) return callback(err3);
// are we done yet?
});
});
});
With Promises above code can be rewritten as below:
asyncCall()
.then(function(data1){
// do something...
return anotherAsyncCall();
})
.then(function(data2){
// do something...
return oneMoreAsyncCall();
})
.then(function(data3){
// the third and final async response
})
.fail(function(err) {
// handle any error resulting from any of the above calls
})
.done();
Django 2.0 removes the django.core.urlresolvers
module, which was moved to django.urls
in version 1.10. You should change any import to use django.urls instead, like this:
from django.urls import reverse
Note that Django 2.0 removes some features that previously were in django.core.urlresolvers
, so you might have to make some more changes before your code works. See the features deprecated in 1.9 for details on those additional changes.
Make sure that your classpath is set correctly and pointing to the correct version of the JDK that you have installed. Also, are you using Open JDK? I have had this issue before after I tried to move from open JDK to Suns JDK. This is an example of how that issue could be fixed.
I'm guessing you're using SQL 2005 or greater. The 2nd line selects the top 2 rows and by using ORDER BY ROW_COUNT DESC
, the 2nd row is arranged as being first, then it is selected using TOP 1
SELECT TOP 1 COLUMN1, COLUMN2
from (
SELECT TOP 2 COLUMN1, COLUMN2
FROM Table
) ORDER BY ROW_NUMBER DESC
for simple Scroll, use following style
height: 200px; overflow: scroll;
and use this style class which div or section you want to show scroll
Don't even call them DTOs. They're called Models....Period. Models never have behavior. I don't know who came up with this dumb term DTO but it must be a .NET thing is all I can figure. Think of view models in MVC, same dam** thing, models are used to transfer state between layers server side or over the wire period, they are all models. Properties with data. These are models you pass ove the wire. Models, Models Models. That's it.
I wish the stupid term DTO would go away from our vocabulary.
Assuming the class variable is z, you can use:
with(df, plot(x, y, col = z))
however, it's important that z is a factor variable, as R internally stores factors as integers.
This way, 1 is 'black', 2 is 'red', 3 is 'green, ....
You can have Read only or Read and Write only on the volume
docker -v /on/my/host/1:/on/the/container/1:ro \
docker -v /on/my/host/2:/on/the/container/2:rw \
Just Remove The Browser Default
Margin
andPadding
Apply Top Of Your Css.
<style>
* {
margin: 0;
padding: 0;
}
</style>
NOTE:
html elements
before writing your css.OR [ Use This In Your Case
]
<style>
*{
margin: 0px;
padding: 0px;
}
h1 {
margin-top: 0px;
}
</style>
DEMO:
<style>_x000D_
_x000D_
*{_x000D_
margin: 0px;_x000D_
padding: 0px;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
margin-top: 0px;_x000D_
}_x000D_
_x000D_
</style>
_x000D_
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
<h1>logo</h1>_x000D_
</body>_x000D_
</html>
_x000D_
Thank you pomber but for
var result = client.PostAsync(url, content).Result;
I used
var result = await client.PostAsync(url, content);
because Result makes app lock for high request
If you press admin on a private repo and scroll down to the part about pages, it writes that it'll be public. I'll check later if .htaccess control or similar is possible, but I don't have much hope for it.
If you want to set typeface to all the TextViews in the entire Activity you can use something like this:
public static void setTypefaceToAll(Activity activity)
{
View view = activity.findViewById(android.R.id.content).getRootView();
setTypefaceToAll(view);
}
public static void setTypefaceToAll(View view)
{
if (view instanceof ViewGroup)
{
ViewGroup g = (ViewGroup) view;
int count = g.getChildCount();
for (int i = 0; i < count; i++)
setTypefaceToAll(g.getChildAt(i));
}
else if (view instanceof TextView)
{
TextView tv = (TextView) view;
setTypeface(tv);
}
}
public static void setTypeface(TextView tv)
{
TypefaceCache.setFont(tv, TypefaceCache.FONT_KOODAK);
}
And the TypefaceCache:
import java.util.TreeMap;
import android.graphics.Typeface;
import android.widget.TextView;
public class TypefaceCache {
//Font names from asset:
public static final String FONT_ROBOTO_REGULAR = "fonts/Roboto-Regular.ttf";
public static final String FONT_KOODAK = "fonts/Koodak.ttf";
private static TreeMap<String, Typeface> fontCache = new TreeMap<String, Typeface>();
public static Typeface getFont(String fontName) {
Typeface tf = fontCache.get(fontName);
if(tf == null) {
try {
tf = Typeface.createFromAsset(MyApplication.getAppContext().getAssets(), fontName);
}
catch (Exception e) {
return null;
}
fontCache.put(fontName, tf);
}
return tf;
}
public static void setFont(TextView tv, String fontName)
{
tv.setTypeface(getFont(fontName));
}
}
You could use the hue-rotate
function in the filter
property. It's quite an obscure measurement though, you'd need to know how many degrees round the colour wheel you need to move in order to arrive at your desired hue, for example:
header {
filter: hue-rotate(90deg);
}
Once you'd found the correct hue, you could combine the brightness
and either grayscale
or saturate
functions to find the correct shade, for example:
header {
filter: hue-rotate(90deg) brightness(10%) grayscale(10%);
}
The filter
property has a vendor prefix in Webkit, so the final code would be:
header {
-webkit-filter: hue-rotate(90deg) brightness(10%) grayscale(10%);
filter: hue-rotate(90deg) brightness(10%) grayscale(10%);
}
without using Lib just pure code:
#Calculate the Days between Two Date
daysOfMonths = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def isLeapYear(year):
# Pseudo code for this algorithm is found at
# http://en.wikipedia.org/wiki/Leap_year#Algorithm
## if (year is not divisible by 4) then (it is a common Year)
#else if (year is not divisable by 100) then (ut us a leap year)
#else if (year is not disible by 400) then (it is a common year)
#else(it is aleap year)
return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0
def Count_Days(year1, month1, day1):
if month1 ==2:
if isLeapYear(year1):
if day1 < daysOfMonths[month1-1]+1:
return year1, month1, day1+1
else:
if month1 ==12:
return year1+1,1,1
else:
return year1, month1 +1 , 1
else:
if day1 < daysOfMonths[month1-1]:
return year1, month1, day1+1
else:
if month1 ==12:
return year1+1,1,1
else:
return year1, month1 +1 , 1
else:
if day1 < daysOfMonths[month1-1]:
return year1, month1, day1+1
else:
if month1 ==12:
return year1+1,1,1
else:
return year1, month1 +1 , 1
def daysBetweenDates(y1, m1, d1, y2, m2, d2,end_day):
if y1 > y2:
m1,m2 = m2,m1
y1,y2 = y2,y1
d1,d2 = d2,d1
days=0
while(not(m1==m2 and y1==y2 and d1==d2)):
y1,m1,d1 = Count_Days(y1,m1,d1)
days+=1
if end_day:
days+=1
return days
# Test Case
def test():
test_cases = [((2012,1,1,2012,2,28,False), 58),
((2012,1,1,2012,3,1,False), 60),
((2011,6,30,2012,6,30,False), 366),
((2011,1,1,2012,8,8,False), 585 ),
((1994,5,15,2019,8,31,False), 9239),
((1999,3,24,2018,2,4,False), 6892),
((1999,6,24,2018,8,4,False),6981),
((1995,5,24,2018,12,15,False),8606),
((1994,8,24,2019,12,15,True),9245),
((2019,12,15,1994,8,24,True),9245),
((2019,5,15,1994,10,24,True),8970),
((1994,11,24,2019,8,15,True),9031)]
for (args, answer) in test_cases:
result = daysBetweenDates(*args)
if result != answer:
print "Test with data:", args, "failed"
else:
print "Test case passed!"
test()
Use the requests library, pretty print the results so you can better locate the keys/values you want to extract, and then use nested for loops to parse the data. In the example I extract step by step driving directions.
import json, requests, pprint
url = 'http://maps.googleapis.com/maps/api/directions/json?'
params = dict(
origin='Chicago,IL',
destination='Los+Angeles,CA',
waypoints='Joplin,MO|Oklahoma+City,OK',
sensor='false'
)
data = requests.get(url=url, params=params)
binary = data.content
output = json.loads(binary)
# test to see if the request was valid
#print output['status']
# output all of the results
#pprint.pprint(output)
# step-by-step directions
for route in output['routes']:
for leg in route['legs']:
for step in leg['steps']:
print step['html_instructions']
Both support the same functions. jquery.min.js
is a compressed version of jquery.js
(whitespaces and comments stripped out, shorter variable names, ...) in order to preserve bandwidth. In terms of functionality they are absolutely the same. It is recommended to use this compressed version in production environment.
In Angular (currently on Angular-6) .subscribe()
is a method on the Observable type. The Observable type is a utility that asynchronously or synchronously streams data to a variety of components or services that have subscribed to the observable.
The observable is an implementation/abstraction over the promise chain and will be a part of ES7 as a proposed and very supported feature. In Angular it is used internally due to rxjs being a development dependency.
An observable itself can be thought of as a stream of data coming from a source, in Angular this source is an API-endpoint, a service, a database or another observable. But the power it has is that it's not expecting a single response. It can have one or many values that are returned.
Link to rxjs for observable/subscribe docs here: https://rxjs-dev.firebaseapp.com/api/index/class/Observable#subscribe-
Subscribe takes 3 methods as parameters each are functions:
Within each of these, there is the potentional to pipe (or chain) other utilities called operators onto the results to change the form or perform some layered logic.
In the simple example above:
.subscribe(hero => this.hero = hero);
basically says on this observable take the hero being emitted and set it to this.hero
.
Adding this answer to give more context to Observables based off the documentation and my understanding.
There are padding built into various classes.
For example:
A asp.net web forms app:
<asp:CheckBox ID="chkShowDeletedServers" runat="server" AutoPostBack="True" Text="Show Deleted" />
this code above would place the Text of "Show Deleted" too close to the checkbox to what I see at nice to look at.
However with bootstrap
<div class="checkbox-inline">
<asp:CheckBox ID="chkShowDeletedServers" runat="server" AutoPostBack="True" Text="Show Deleted" />
</div>
This created the space, if you don't want the text bold, that class=checkbox
Bootstrap is very flexible, so in this case I don't need a hack, but sometimes you need to.
Edit: Mar. 2015
As noted below, pandas now uses SQLAlchemy to both read from (read_sql) and insert into (to_sql) a database. The following should work
import pandas as pd
df = pd.read_sql(sql, cnxn)
Previous answer: Via mikebmassey from a similar question
import pyodbc
import pandas.io.sql as psql
cnxn = pyodbc.connect(connection_info)
cursor = cnxn.cursor()
sql = "SELECT * FROM TABLE"
df = psql.frame_query(sql, cnxn)
cnxn.close()
You should always use "throw;" to rethrow the exceptions in .NET,
Refer this, http://weblogs.asp.net/bhouse/archive/2004/11/30/272297.aspx
Basically MSIL (CIL) has two instructions - "throw" and "rethrow":
Basically I can see the reason why "throw ex" overrides the stack trace.
Basically http.antMatcher()
tells Spring to only configure HttpSecurity
if the path matches this pattern.
Make sure you format the string like this or it wont work
$content = "BEGIN:VCALENDAR\n".
"VERSION:2.0\n".
"PRODID:-//hacksw/handcal//NONSGML v1.0//EN\n".
"BEGIN:VEVENT\n".
"UID:".uniqid()."\n".
"DTSTAMP:".$time."\n".
"DTSTART:".$time."\n".
"DTEND:".$time."\n".
"SUMMARY:".$summary."\n".
"END:VEVENT\n".
"END:VCALENDAR";
Here it is. Add this code to your web.config file:
<system.webServer>
<rewrite>
<rules>
<rule name="Root Hit Redirect" stopProcessing="true">
<match url="^$" />
<action type="Redirect" url="/menu_1/MainScreen.aspx" />
</rule>
</rules>
</rewrite>
</system.webServer>
It will do 301 Permanent Redirect (URL will be changed in browser). If you want to have such "redirect" to be invisible (rewrite, internal redirect), then use this rule (the only difference is that "Redirect" has been replaced by "Rewrite"):
<system.webServer>
<rewrite>
<rules>
<rule name="Root Hit Redirect" stopProcessing="true">
<match url="^$" />
<action type="Rewrite" url="/menu_1/MainScreen.aspx" />
</rule>
</rules>
</rewrite>
</system.webServer>
If you can comment out code and your program still works, then yes, that code was optional.
.strip()
with no arguments (or None
as the first argument) removes all whitespace at the start and end, including spaces, tabs, newlines and carriage returns. Leaving it in doesn't do any harm, and allows your program to deal with unexpected extra whitespace inserted into the file.
For example, by using .strip()
, the following two lines in a file would lead to the same end result:
foo\tbar \n
foo\tbar\n
I'd say leave it in.
If you want to get a constraint by the column or table names, or you want to get all the constraints in the database, look to other answers. However, if you're just looking for exactly what the question asks, namely, to "test if a given default constraint exists ... by the name of the constraint", then there's a much easier way.
Here's a future-proof answer that doesn't use the sysobjects
or other sys
tables at all:
IF object_id('DF_CONSTRAINT_NAME', 'D') IS NOT NULL BEGIN
-- constraint exists, work with it.
END
I just did this out of interest. I agree it's not the right thing to do, but I think it should be the op's decision... Also the code could easily be extended to add functionality, rather than take it away (like a more advanced clipboard, or Ctrl+s triggering a server-side save).
$(document).ready(function() {_x000D_
var ctrlDown = false,_x000D_
ctrlKey = 17,_x000D_
cmdKey = 91,_x000D_
vKey = 86,_x000D_
cKey = 67;_x000D_
_x000D_
$(document).keydown(function(e) {_x000D_
if (e.keyCode == ctrlKey || e.keyCode == cmdKey) ctrlDown = true;_x000D_
}).keyup(function(e) {_x000D_
if (e.keyCode == ctrlKey || e.keyCode == cmdKey) ctrlDown = false;_x000D_
});_x000D_
_x000D_
$(".no-copy-paste").keydown(function(e) {_x000D_
if (ctrlDown && (e.keyCode == vKey || e.keyCode == cKey)) return false;_x000D_
});_x000D_
_x000D_
// Document Ctrl + C/V _x000D_
$(document).keydown(function(e) {_x000D_
if (ctrlDown && (e.keyCode == cKey)) console.log("Document catch Ctrl+C");_x000D_
if (ctrlDown && (e.keyCode == vKey)) console.log("Document catch Ctrl+V");_x000D_
});_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<h3>Ctrl+c Ctrl+v disabled</h3>_x000D_
<textarea class="no-copy-paste"></textarea>_x000D_
<br><br>_x000D_
<h3>Ctrl+c Ctrl+v allowed</h3>_x000D_
<textarea></textarea>
_x000D_
Also just to clarify, this script requires the jQuery library.
EDIT: removed 3 redundant lines (involving e.which) thanks to Tim Down's suggestion (see comments)
EDIT: added support for Macs (cmd key instead of ctrl)
in file .xml, set
android:textStyle="bold"
will set text type is bold.
What Tyler Rinker says is correct:
AQ2 <- airquality
AQ2[is.na(AQ2)] <- 0
will do just this.
What you are originally doing is that you are taking from airquality
all those rows (cases) that are complete. So, all the cases that do not have any NA's in them, and keep only those.
Add this to you PageLoad and it will solve your problem:
ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
scriptManager.RegisterPostBackControl(this.lblbtndoc1);
Most simple way (assumed you want to remove the element)
<span id='close' onclick='this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode); return false;'>x</span>
Add this inside your div
, an example here.
You may also use something like this
window.onload = function(){
document.getElementById('close').onclick = function(){
this.parentNode.parentNode.parentNode
.removeChild(this.parentNode.parentNode);
return false;
};
};
Css for close button
#close {
float:right;
display:inline-block;
padding:2px 5px;
background:#ccc;
}
You may add a hover effect like
#close:hover {
float:right;
display:inline-block;
padding:2px 5px;
background:#ccc;
color:#fff;
}
Something like this one.
It could happen when you use TFS from two different machines with the same account, if so you should compare to see changed files and check out them then get latest then undo pending changes to remove checkout
Goto:
project>Properties>Android> select: google APIs Android 4.0.3
Click Icon:
Android Virtual Device Manager>Edit> Slect box in Tabget>Google APIs APIsLevel15
and select Built-in: is WQVGA400 > Edit AVD > Start
The following resolved the issue:
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String str = "4*5";
System.out.println(engine.eval(str));
How about using a grid? it's 2019 and support is reasonable
body {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
.content {_x000D_
display: grid;_x000D_
background-color: bisque;_x000D_
height: 100vh;_x000D_
place-items: center;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
<div class="content">_x000D_
<form action="#" method="POST">_x000D_
<fieldset>_x000D_
<legend>Information:</legend>_x000D_
<label for="name">Name:</label>_x000D_
<input type="text" id="name" name="user_name">_x000D_
</fieldset>_x000D_
<button type="button" formmethod="POST" formaction="#">Submit</button>_x000D_
</form>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
Yeah mate i was trying to do the same in windows, and what helped me was a bit of lambdas with the root.state()
method.
root = Tk()
root.bind('<Escape>', lambda event: root.state('normal'))
root.bind('<F11>', lambda event: root.state('zoomed'))
“tools:context” is one of the Design Attributes that can facilitate layout creation in XML in the development framework. This attribute is used to show the development framework what activity class is picked for implementing the layout. Using “tools:context”, Android Studio chooses the necessary theme for the preview automatically.
If you’d like to know more about some other attributes and useful tools for Android app development, take a look at this review: http://cases.azoft.com/4-must-know-tools-for-effective-android-development/
I'm surprised that nobody gave CSS table layout as a solution:
.Row {_x000D_
display: table;_x000D_
width: 100%; /*Optional*/_x000D_
table-layout: fixed; /*Optional*/_x000D_
border-spacing: 10px; /*Optional*/_x000D_
}_x000D_
.Column {_x000D_
display: table-cell;_x000D_
background-color: red; /*Optional*/_x000D_
}
_x000D_
<div class="Row">_x000D_
<div class="Column">C1</div>_x000D_
<div class="Column">C2</div>_x000D_
<div class="Column">C3</div>_x000D_
</div>
_x000D_
Works in IE8+
Check out a JSFiddle Demo
When you populate your fields, you can check for the value:
<input type="radio" name="sex" value="Male" <?php echo ($sex=='Male')?'checked':'' ?>size="17">Male
<input type="radio" name="sex" value="Female" <?php echo ($sex=='Female')?'checked':'' ?> size="17">Female
Assuming that the value you return from your database is in the variable $sex
The checked property will preselect the value that match
//funcion para seleccionar por el text del select
var text = '';
var canal = ($("#name_canal").val()).split(' ');
$('#id_empresa option').each(function(i, option) {
text = $('#id_empresa option:eq('+i+')').text();
if(text.toLowerCase() == canal[0].toLowerCase()){
$('#id_empresa option:eq('+i+')').attr('selected', true);
}
});
I believe what you are looking for is assign_attributes
.
It's basically the same as update_attributes but it doesn't save the record:
class User < ActiveRecord::Base
attr_accessible :name
attr_accessible :name, :is_admin, :as => :admin
end
user = User.new
user.assign_attributes({ :name => 'Josh', :is_admin => true }) # Raises an ActiveModel::MassAssignmentSecurity::Error
user.assign_attributes({ :name => 'Bob'})
user.name # => "Bob"
user.is_admin? # => false
user.new_record? # => true
x or "default"
works best — i can even use a function call inline, without executing it twice or using extra variable:
self.lineEdit_path.setText( self.getDir(basepath) or basepath )
I use it when opening Qt's dialog.getExistingDirectory()
and canceling, which returns empty string.
Using this.props.children
is the idiomatic way to pass instantiated components to a react component
const Label = props => <span>{props.children}</span>
const Tab = props => <div>{props.children}</div>
const Page = () => <Tab><Label>Foo</Label></Tab>
When you pass a component as a parameter directly, you pass it uninstantiated and instantiate it by retrieving it from the props. This is an idiomatic way of passing down component classes which will then be instantiated by the components down the tree (e.g. if a component uses custom styles on a tag, but it wants to let the consumer choose whether that tag is a div
or span
):
const Label = props => <span>{props.children}</span>
const Button = props => {
const Inner = props.inner; // Note: variable name _must_ start with a capital letter
return <button><Inner>Foo</Inner></button>
}
const Page = () => <Button inner={Label}/>
If what you want to do is to pass a children-like parameter as a prop, you can do that:
const Label = props => <span>{props.content}</span>
const Tab = props => <div>{props.content}</div>
const Page = () => <Tab content={<Label content='Foo' />} />
After all, properties in React are just regular JavaScript object properties and can hold any value - be it a string, function or a complex object.
Use the following algorithm to traverse in breadth first search-
Code is written below-
Queue<TreeNode> queue= new LinkedList<>();
private void breadthWiseTraversal(TreeNode root) {
if(root==null){
return;
}
TreeNode temp = root;
queue.clear();
((LinkedList<TreeNode>) queue).add(temp);
while(!queue.isEmpty()){
TreeNode ref= queue.remove();
System.out.print(ref.data+" ");
if(ref.left!=null) {
((LinkedList<TreeNode>) queue).add(ref.left);
}
if(ref.right!=null) {
((LinkedList<TreeNode>) queue).add(ref.right);
}
}
}
scroll.fullScroll(View.FOCUS_DOWN)
will lead to the change of focus. That will bring some strange behavior when there are more than one focusable views, e.g two EditText. There is another way for this question.
View lastChild = scrollLayout.getChildAt(scrollLayout.getChildCount() - 1);
int bottom = lastChild.getBottom() + scrollLayout.getPaddingBottom();
int sy = scrollLayout.getScrollY();
int sh = scrollLayout.getHeight();
int delta = bottom - (sy + sh);
scrollLayout.smoothScrollBy(0, delta);
This works well.
Kotlin Extension
fun ScrollView.scrollToBottom() {
val lastChild = getChildAt(childCount - 1)
val bottom = lastChild.bottom + paddingBottom
val delta = bottom - (scrollY+ height)
smoothScrollBy(0, delta)
}
Using param to name the parameters allows you to ignore the order of the parameters:
ParamEx.ps1
# Show how to handle command line parameters in Windows PowerShell
param(
[string]$FileName,
[string]$Bogus
)
write-output 'This is param FileName:'+$FileName
write-output 'This is param Bogus:'+$Bogus
ParaEx.bat
rem Notice that named params mean the order of params can be ignored
powershell -File .\ParamEx.ps1 -Bogus FooBar -FileName "c:\windows\notepad.exe"
You can change the number format of the column to this custom format:
0;-0;;@
which will hide all 0 values.
To do this, select the column, right-click > Format Cells > Custom.
The NativeHeap can be increasded by -XX:MaxDirectMemorySize=256M (default is 128)
I've never used it. Maybe you'll find it useful.
data = File.read("/path/to/file")
You need to configure the war plugin:
<project>
...
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<warName>bird.war</warName>
</configuration>
</plugin>
</plugins>
</build>
...
</project>
More info here
In python, you wouldn't normally do what you are trying to do. But, the below code will do it:
strs = ["" for x in range(size)]
Go for the simplist possible scenario in which deadlock can occur when introducting the concept to your students. This would involve a minimum of two threads and a minimum of two resources (I think). The goal being to engineer a scenario in which the first thread has a lock on resource one, and is waiting for the lock on resource two to be released, whilst at the same time thread two holds a lock on resource two, and is waiting for the lock on resource one to be released.
It doesn't really matter what the underlying resources are; for simplicities sake, you could just make them a pair of files that both threads are able to write to.
EDIT: This assumes no inter-process communication other than the locks held.
If searching for an element is important, I'd recommend std::set
instead of std::vector
. Using this:
std::find(vec.begin(), vec.end(), x)
runs in O(n) time, but std::set
has its own find()
member (ie. myset.find(x)
) which runs in O(log n) time - that's much more efficient with large numbers of elements
std::set
also guarantees all the added elements are unique, which saves you from having to do anything like if not contained then push_back()...
.
The reason people often suggest writing
VAR=value
export VAR
instead of the shorter
export VAR=value
is that the longer form works in more different shells than the short form. If you know you're dealing with bash
, either works fine, of course.
I wrote this extension method based off @Lee's response to the OP. Note, a default parameter was used (requiring C# 4.0). However, an overloaded method call in C# 3.0 would suffice.
/// <summary>
/// Method that returns all the duplicates (distinct) in the collection.
/// </summary>
/// <typeparam name="T">The type of the collection.</typeparam>
/// <param name="source">The source collection to detect for duplicates</param>
/// <param name="distinct">Specify <b>true</b> to only return distinct elements.</param>
/// <returns>A distinct list of duplicates found in the source collection.</returns>
/// <remarks>This is an extension method to IEnumerable<T></remarks>
public static IEnumerable<T> Duplicates<T>
(this IEnumerable<T> source, bool distinct = true)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
// select the elements that are repeated
IEnumerable<T> result = source.GroupBy(a => a).SelectMany(a => a.Skip(1));
// distinct?
if (distinct == true)
{
// deferred execution helps us here
result = result.Distinct();
}
return result;
}
well this method is not a good one, but easy and not suggested. Maybe i should say this is the least effective method and the worse coding practice but, fun to use,
float val=10.0;
String str=val+"";
the empty quotes, add a null string to the variable str, upcasting 'val' to the string type.
you can get the current project path use System.getProperty("user.dir")
in that method you write Key name to get your different-different paths, and if you don't know key, you can find all property use of System.getProperties()
this method is return all property with key. and you can find key name manually from it.
and write System.getProperty("KEY NAME")
and get your require path.
Make sure you image is a relative path such as:
@Url.Content("~/Content/images/myimage.png")
MVC4
<img src="~/Content/images/myimage.png" />
You could convert the byte[]
into a Base64
string
on the fly.
string base64String = Convert.ToBase64String(imageBytes);
<img src="@String.Format("data:image/png;base64,{0}", base64string)" />
mail -s "Your Subject" [email protected] < /file/with/mail/content
(/file/with/mail/content
should be a plaintext file, not a file attachment or an image, etc)
Point 1:
If you want to write something into a file. means: it will remove anything already saved in the file and write the new content. use fs.promises.writeFile()
Point 2:
If you want to append something into a file. means: it will not remove anything already saved in the file but append the new item in the file content.then first read the file, and then add the content into the readable value, then write it to the file. so use fs.promises.readFile and fs.promises.writeFile()
example 1: I want to write a JSON object in my JSON file .
const fs = require('fs');
writeFile (filename ,writedata) async function writeFile (filename ,writedata) { try { await fs.promises.writeFile(filename, JSON.stringify(writedata,null, 4), 'utf8'); return true } catch(err) { return false } }
I've made small modifications to @paul-H code, such that you can set the font size for the x/y axes and legend independently. Hope it helps:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
x = np.random.normal(size=37)
y = np.random.lognormal(size=37)
# defaults
sns.set()
fig, ax = plt.subplots()
ax.plot(x, y, marker='s', linestyle='none', label='small')
ax.legend(loc='upper left', fontsize=20,bbox_to_anchor=(0, 1.1))
ax.set_xlabel('X_axi',fontsize=20);
ax.set_ylabel('Y_axis',fontsize=20);
plt.show()
This is the output:
I always use the tag. It is a simple compile-time flag to catch little mistakes that I might make.
It will catch things like tostring()
instead of toString()
The little things help in large projects.
In the XML: use literal line-breaks, nothing else needed there.
The newlines will be preserved for Javascript to read them [1]. Note that any indentation-spaces and preceding or trailing line-breaks are preserved too (the reason you weren't seeing them is that HTML/CSS collapses whitespace into single space-characters by default).
Then the easiest way is: In the HTML: do nothing, just use CSS to preserve the line-breaks
.msg_body {
white-space: pre-line;
}
But this also preserves your extra lines from the XML document, and doesn't work in IE 6 or 7 [2].
So clean up the whitespace yourself; this is one way to do it (linebreaks for clarity - Javascript is happy with or without them [3]) [4]
[get lyric...].nodeValue
.replace(/^[\r\n\t ]+|[\r\n\t ]+$/g, '')
.replace(/[ \t]+/g, ' ')
.replace(/ ?([\r\n]) ?/g, '$1')
and then preserve those line-breaks with
.msg_body {
white-space: pre; // for IE 6 and 7
white-space: pre-wrap; // or pre-line
}
or, instead of that CSS, add a .replace(/\r?\n/g, '<br />')
after the other JavaScript .replace
s.
(Side note: Using document.write() like that is also not ideal and sometimes vulnerable to cross-site scripting attacks, but that's another subject. In relation to this answer, if you wanted to use the variation that replaces with <br>
, you'd have to escape <
,&
(,>
,"
,'
) before generating the <br>
s.)
--
[1] reference: sections "Element White Space Handling" and "XML Schema White Space Control" http://www.usingxml.com/Basics/XmlSpace#ElementWhiteSpaceHandling
[2] http://www.quirksmode.org/css/whitespace.html
[3] except for a few places in Javascript's syntax where its semicolon insertion is particularly annoying.
[4] I wrote it and tested these regexps in Linux Node.js (which uses the same Javascript engine as Chrome, "V8"). There's a small risk some browser executes regexps differently. (My test string (in javascript syntax) "\n\nfoo bar baz\n\n\tmore lyrics \nare good\n\n"
)
PS > $c = Compare-Object -ReferenceObject (1..5) -DifferenceObject (1..6) -PassThru
PS > $c
6
It is a good practice to set where the access log should be in nginx configuring file . Using acces_log /path/ Like this.
keyval $remote_addr:$http_user_agent $seen zone=clients;
server { listen 443 ssl;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers HIGH:!aNULL:!MD5;
if ($seen = "") {
set $seen 1;
set $logme 1;
}
access_log /tmp/sslparams.log sslparams if=$logme;
error_log /pathtolog/error.log;
# ...
}
You can do this:
private String cellToString(HSSFCell cell) {
CellType type;
Object result;
type = cell.getCellType();
switch (type) {
case NUMERIC : //numeric value in excel
result = cell.getNumericCellValue();
break;
case STRING : //String Value in Excel
result = cell.getStringCellValue();
break;
default :
throw new RuntimeException("There is no support for this type of value in Apche POI");
}
return result.toString();
}
You may want to update you .bashrc and .bash_profile files with aliases to recognize the command you are entering.
.bashrc and .bash_profile files are hidden files probably located on your C: drive where you save your program files.
I suggest using Vladimir Keleshev's pep257 Python program to check your docstrings against PEP-257 and the Numpy Docstring Standard for describing parameters, returns, etc.
pep257 will report divergence you make from the standard and is called like pylint and pep8.
If you need to compare an array of objects, this works in all cases:
let arr = [{ id: 1, title: "title1" },{ id: 2, title: "title2" }]
let brr = [{ id: 2, title: "title2" },{ id: 3, title: "title3" }]
const res = arr.filter(f => brr.some(item => item.id === f.id));
console.log(res);
This rule
main: producer.o consumer.o AddRemove.o
$(COMPILER) -pthread $(CCFLAGS) -o producer.o consumer.o AddRemove.o
is wrong. It says to create a file named producer.o (with -o producer.o
), but you want to create a file named main
. Please excuse the shouting, but ALWAYS USE $@ TO REFERENCE THE TARGET:
main: producer.o consumer.o AddRemove.o
$(COMPILER) -pthread $(CCFLAGS) -o $@ producer.o consumer.o AddRemove.o
As Shahbaz rightly points out, the gmake professionals would also use $^
which expands to all the prerequisites in the rule. In general, if you find yourself repeating a string or name, you're doing it wrong and should use a variable, whether one of the built-ins or one you create.
main: producer.o consumer.o AddRemove.o
$(COMPILER) -pthread $(CCFLAGS) -o $@ $^
The first problem encountered with your code is the message
Local variable OrdersPerHour might not be initialized before accessing.
It happens because in the case where your database query would throw an exception, the value might not be set to something (you have an empty catch clause).
To fix this, set the value to what you'd want to have if the query fails, which is probably 0
:
int? OrdersPerHour = 0;
Once this is fixed, now there's the error you're posting about. This happens because your method signature declares you are returning an int
, but you are in fact returning a nullable int, int?
, variable.
So to get the int
part of your int?
, you can use the .Value
property:
return OrdersPerHour.Value;
However, if you declared your OrdersPerHour to be null
at start instead of 0
, the value can be null so a proper validation before returning is probably needed (Throw a more specific exception, for example).
To do so, you can use the HasValue
property to be sure you're having a value before returning it:
if (OrdersPerHour.HasValue){
return OrdersPerHour.Value;
}
else{
// Handle the case here
}
As a side note, since you're coding in C# it would be better if you followed C#'s conventions. Your parameter and variables should be in camelCase, not PascalCase. So User
and OrdersPerHour
would be user
and ordersPerHour
.
Best Solution
<span class="anchor" id="section1"></span>
<div class="section"></div>
<span class="anchor" id="section2"></span>
<div class="section"></div>
<span class="anchor" id="section3"></span>
<div class="section"></div>
<style>
.anchor{
display: block;
height: 115px; /*same height as header*/
margin-top: -115px; /*same height as header*/
visibility: hidden;
}
</style>
Here is an example to get string/value
public enum Suit
{
Spades = 0x10,
Hearts = 0x11,
Clubs = 0x12,
Diamonds = 0x13
}
private void print_suit()
{
foreach (var _suit in Enum.GetValues(typeof(Suit)))
{
int suitValue = (byte)(Suit)Enum.Parse(typeof(Suit), _suit.ToString());
MessageBox.Show(_suit.ToString() + " value is 0x" + suitValue.ToString("X2"));
}
}
Result of Message Boxes
Spade value is 0x10
Hearts value is 0x11
Clubs value is 0x12
Diamonds value is 0x13
see this http://stleary.github.io/JSON-java/org/json/JSONObject.html#JSONObject-java.lang.String-
JSONObject
public JSONObject(java.lang.String source)
throws JSONException
Construct a JSONObject from a source JSON text string. This is the most commonly used` JSONObject constructor.
Parameters:
source - `A string beginning with { (left brace) and ending with } (right brace).`
Throws:
JSONException - If there is a syntax error in the source string or a duplicated key.
you try to use some thing like:
new JSONObject("{your string}")
Things have changed a little in the way Charles provides HTTPS proxying.
First the certificates installation options have been moved to the help menu.
Help -> SSL Proxying -> Install Charles Root Certificate
Help -> SSL Proxying -> Install Charles Root Certificate in iOS Simulators
Second, starting in iOS 9 you must provide a NSAppTransportSecurity
option in your Info.plist
and if you want Charles to work properly as a man in the middle, you must add:
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
as part of the your domains see full example:
<key>NSExceptionDomains</key>
<dict>
<key>yourdomain.com</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.1</string>
</dict>
The reason being (I guess) that Charles at some point communicates in clear http after acting as the man in the middle https server.
Last step is to activate SSL Proxying for this domain in Charles (right click on domain and select Enable SSL Proxying)
I do recomend doing it in 2 filles (.h .cpp)
But if u lazy just add inline
before the function
So it will look something like this
inline void functionX()
{ }
more about inline functions:
The inline functions are a C++ enhancement feature to increase the execution time of a program. Functions can be instructed to compiler to make them inline so that compiler can replace those function definition wherever those are being called. Compiler replaces the definition of inline functions at compile time instead of referring function definition at runtime. NOTE- This is just a suggestion to compiler to make the function inline, if function is big (in term of executable instruction etc) then, compiler can ignore the “inline” request and treat the function as normal function.
more info here
I think this is the easiest way for multy selection/update/insert/delete. You can run as many update/insert/delete as u want after select (you have to make a select first(a dummy if needed)) with executeUpdate(str) (just use new int(count1,count2,...)) and if u need a new selection close 'statement' and 'connection' and make new for next select. Like example:
String str1 = "select * from users";
String str9 = "INSERT INTO `port`(device_id, potition, port_type, di_p_pt) VALUE ('"+value1+"', '"+value2+"', '"+value3+"', '"+value4+"')";
String str2 = "Select port_id from port where device_id = '"+value1+"' and potition = '"+value2+"' and port_type = '"+value3+"' ";
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
theConnection=(Connection) DriverManager.getConnection(dbURL,dbuser,dbpassword);
theStatement = theConnection.prepareStatement(str1);
ResultSet theResult = theStatement.executeQuery();
int count8 = theStatement.executeUpdate(str9);
theStatement.close();
theConnection.close();
theConnection=DriverManager.getConnection(dbURL,dbuser,dbpassword);
theStatement = theConnection.prepareStatement(str2);
theResult = theStatement.executeQuery();
ArrayList<Port> portList = new ArrayList<Port>();
while (theResult.next()) {
Port port = new Port();
port.setPort_id(theResult.getInt("port_id"));
portList.add(port);
}
I hope it helps
The path you give to LOAD DATA INFILE
is for the filesystem on the machine where the server is running, not the machine you connect from. LOAD DATA LOCAL INFILE
is for the client's machine, but it requires that the server was started with the right settings, otherwise it's not allowed. You can read all about it here: http://dev.mysql.com/doc/refman/5.0/en/load-data-local.html
As for SELECT INTO OUTFILE
I'm not sure why there is not a local version, besides it probably being tricky to do over the connection. You can get the same functionality through the mysqldump
tool, but not through sending SQL to the server.
You can also set the TMPDIR
environment variable.
In some situations (Docker in my case) it's more convenient to set an environment variable than to update a config file.
Using Bundling and Minification also helps you improve the performance. It basically reduces the page loading time.
Key differences between Serializable
and Externalizable
Serializable
is marker interface without any methods. Externalizable
interface contains two methods: writeExternal()
and readExternal()
.Serializable
interface. Programmer defined Serialization process will be kicked-in for classes implementing Externalizable
interface.Externalizable
interface. You can support different versions of your object. If you implement Externalizable
, it's your responsibility to serialize super
classSerializable
uses reflection to construct object and does not require no arg constructor. But Externalizable
demands public no-arg constructor.Refer to blog by Hitesh Garg
for more details.
If you want to preserve the details come with ls like file size etc in your output then this should work.
sed "s|<OLDPATH>|<NEWPATH>|g" input_file > output_file
In my case, I was careless while merging the application.yml file, and I've unnecessary indented my properties to the right.
I've indented it like this:
spring:
application:
name: applicationName
............................
myProperties:
property1: property1value
While the code expected it to be like this:
spring:
application:
name: applicationName
.............................
myProperties:
property1: property1value
As a workaround, There is a Kotlin stdlib function that can be used in a nice way and fully compatible with Java's String format (it's only a wrapper around Java's String.format()
)
See Kotlin's documentation
Your code would be:
val pi = 3.14159265358979323
val s = "pi = %.2f".format(pi)
The best practise is to not force a garbage collection.
According to MSDN:
"It is possible to force garbage collection by calling Collect, but most of the time, this should be avoided because it may create performance issues. "
However, if you can reliably test your code to confirm that calling Collect() won't have a negative impact then go ahead...
Just try to make sure objects are cleaned up when you no longer need them. If you have custom objects, look at using the "using statement" and the IDisposable interface.
This link has some good practical advice with regards to freeing up memory / garbage collection etc:
You could call this function for each of the edit texts:
public boolean isEmpty(EditText editText) {
boolean isEmptyResult = false;
if (editText.getText().length() == 0) {
isEmptyResult = true;
}
return isEmptyResult;
}
I solved my own problem when using google distance matrix API by setting my request header with Jquery ajax. take a look below.
var settings = {
'cache': false,
'dataType': "jsonp",
"async": true,
"crossDomain": true,
"url": "https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=place_id:"+me.originPlaceId+"&destinations=place_id:"+me.destinationPlaceId+"®ion=ng&units=metric&key=mykey",
"method": "GET",
"headers": {
"accept": "application/json",
"Access-Control-Allow-Origin":"*"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
Note what i added at the settings
**
"headers": {
"accept": "application/json",
"Access-Control-Allow-Origin":"*"
}
**
I hope this helps.
here's a gentle introduction to the js debugger in chrome that i wrote. Maybe it will help others looking for info on this: http://meeech.amihod.com/getting-started-with-javascript-debugging-in-chrome/
If you're using jQuery-UI, you must include the jQuery UI CSS package, otherwise the UI components don't know how to be styled.
If you don't like the jQuery UI styles, then you'll have to recreate all the styles it would have otherwise applied.
Here's an example and some possible fixes.
Here's a demo in Stack Snippets without jquery-ui.css (doesn't work)
$(function() {_x000D_
var availableTags = [_x000D_
"ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++",_x000D_
"Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran",_x000D_
"Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl",_x000D_
"PHP", "Python", "Ruby", "Scala", "Scheme"_x000D_
];_x000D_
_x000D_
$(".autocomplete").autocomplete({_x000D_
source: availableTags_x000D_
});_x000D_
});
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
_x000D_
<div class="form-group">_x000D_
<label>Languages</label>_x000D_
<input class="form-control autocomplete" placeholder="Enter A" />_x000D_
</div>_x000D_
_x000D_
<div class="form-group">_x000D_
<label >Another Field</label>_x000D_
<input class="form-control">_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
Just include jquery-ui.css and everything should work just fine with the latest supported versions of jquery.
$(function() {_x000D_
var availableTags = [_x000D_
"ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++",_x000D_
"Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran",_x000D_
"Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl",_x000D_
"PHP", "Python", "Ruby", "Scala", "Scheme"_x000D_
];_x000D_
_x000D_
$(".autocomplete").autocomplete({_x000D_
source: availableTags_x000D_
});_x000D_
});
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.css" rel="stylesheet"/>_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
<div class="form-group">_x000D_
<label>Languages</label>_x000D_
<input class="form-control autocomplete" placeholder="Enter A" />_x000D_
</div>_x000D_
_x000D_
<div class="form-group">_x000D_
<label >Another Field</label>_x000D_
<input class="form-control">_x000D_
</div>_x000D_
</div>
_x000D_
There is a project that created a Bootstrap-esque theme for jQuery-UI components called jquery-ui-bootstrap. Just grab the stylesheet from there and you should be all set.
$(function() {_x000D_
var availableTags = [_x000D_
"ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++",_x000D_
"Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran",_x000D_
"Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl",_x000D_
"PHP", "Python", "Ruby", "Scala", "Scheme"_x000D_
];_x000D_
_x000D_
$(".autocomplete").autocomplete({_x000D_
source: availableTags_x000D_
});_x000D_
});
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-ui-bootstrap/0.5pre/css/custom-theme/jquery-ui-1.10.0.custom.css" rel="stylesheet"/>_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
<div class="form-group">_x000D_
<label>Languages</label>_x000D_
<input class="form-control autocomplete" placeholder="Enter A" />_x000D_
</div>_x000D_
_x000D_
<div class="form-group">_x000D_
<label >Another Field</label>_x000D_
<input class="form-control">_x000D_
</div>_x000D_
</div>
_x000D_
If you only need the AutoComplete widget from jQuery-UI's library, you should start by doing a custom build so you don't pull in resources you're not using.
After that, you'll need to style it yourself. Just look at some of the other styles that are applied to jquery's autocomplete.css and theme.css to figure out what styles you'll need to manually replace.
You can use bootstrap's dropdowns.less for inspiration.
Here's a sample CSS that fits pretty well with Bootstrap's default theme:
.ui-autocomplete {
position: absolute;
z-index: 1000;
cursor: default;
padding: 0;
margin-top: 2px;
list-style: none;
background-color: #ffffff;
border: 1px solid #ccc;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
-moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
}
.ui-autocomplete > li {
padding: 3px 20px;
}
.ui-autocomplete > li.ui-state-focus {
background-color: #DDD;
}
.ui-helper-hidden-accessible {
display: none;
}
$(function() {_x000D_
var availableTags = [_x000D_
"ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++",_x000D_
"Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran",_x000D_
"Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl",_x000D_
"PHP", "Python", "Ruby", "Scala", "Scheme"_x000D_
];_x000D_
_x000D_
$(".autocomplete").autocomplete({_x000D_
source: availableTags_x000D_
});_x000D_
});
_x000D_
.ui-autocomplete {_x000D_
position: absolute;_x000D_
z-index: 1000;_x000D_
cursor: default;_x000D_
padding: 0;_x000D_
margin-top: 2px;_x000D_
list-style: none;_x000D_
background-color: #ffffff;_x000D_
border: 1px solid #ccc_x000D_
-webkit-border-radius: 5px;_x000D_
-moz-border-radius: 5px;_x000D_
border-radius: 5px;_x000D_
-webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);_x000D_
-moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);_x000D_
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);_x000D_
}_x000D_
.ui-autocomplete > li {_x000D_
padding: 3px 20px;_x000D_
}_x000D_
.ui-autocomplete > li.ui-state-focus {_x000D_
background-color: #DDD;_x000D_
}_x000D_
.ui-helper-hidden-accessible {_x000D_
display: none;_x000D_
}
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
<div class="form-group ui-widget">_x000D_
<label>Languages</label>_x000D_
<input class="form-control autocomplete" placeholder="Enter A" />_x000D_
</div>_x000D_
_x000D_
<div class="form-group ui-widget">_x000D_
<label >Another Field</label>_x000D_
<input class="form-control" />_x000D_
</div>_x000D_
</div>
_x000D_
Tip: Since the dropdown menu hides every time you go to inspect the element (i.e. whenever the input loses focus), for easier debugging of the style, find the control with
.ui-autocomplete
and removedisplay: none;
.
// Procedural
$fineStamp = date('Y-m-d\TH:i:s') . substr(microtime(), 1, 9);
echo $fineStamp . PHP_EOL;
// Object-oriented (if you must). Still relies on $fineStamp though :-\
$d = new DateTime($fineStamp);
echo $d->format('Y-m-d\TH:i:s.u') . PHP_EOL;
[<-
with mapply
is a bit faster than sapply
.
> dat[mapply(is.infinite, dat)] <- NA
With mnel's data, the timing is
> system.time(dat[mapply(is.infinite, dat)] <- NA)
# user system elapsed
# 15.281 0.000 13.750
There are multiple suggestions here, but as far as I can see the jQuery UI guys have broken the dialogue control at present.
I say this because I include a dialogue on my page, and its semi transparent and the modal blanking div is behind some other elements. That can't be right!
In the end based on some other posts I developed this global solution, as an extension to the dialogue widget. It works for me but I'm not sure what it would do if I opened a dialogue from within a dialogue.
Basically it looks for the zIndex of everything else on the page and moves the .ui-widget-overlay to be one higher, and the dialogue itself to be one higher than that.
$.widget("ui.dialog", $.ui.dialog,
{
open: function ()
{
var $dialog = $(this.element[0]);
var maxZ = 0;
$('*').each(function ()
{
var thisZ = $(this).css('zIndex');
thisZ = (thisZ === 'auto' ? (Number(maxZ) + 1) : thisZ);
if (thisZ > maxZ) maxZ = thisZ;
});
$(".ui-widget-overlay").css("zIndex", (maxZ + 1));
$dialog.parent().css("zIndex", (maxZ + 2));
return this._super();
}
});
Thanks to the following, as this is where I got the info from of how to do this: https://stackoverflow.com/a/20942857
http://learn.jquery.com/jquery-ui/widget-factory/extending-widgets/
With reacts Hooks:
import ReactDOM from 'react-dom';
import React, {useRef} from 'react';
const divRef = useRef<HTMLDivElement>(null);
<div ref={divRef}/>
const scrollToDivRef = () => {
let node = ReactDOM.findDOMNode(divRef.current) as Element;
node.scrollIntoView({block: 'start', behavior: 'smooth'});
}
I was seeing this error along with: "Error:compileSdkVersion android-21 requires compiling with JDK 7"
For me, the solution was found here, where I had to update the JDK location in the project structure.
perhaps I am late
you can use git remote remove origin
it will do the job.
Just do:
cd /home/user/.ssh/
-> here user
will be your username, i.e. /home/jon/
for example.
Then
gedit known_hosts &
and delete the contents inside it.
Now ssh
again, it should work.
There are no post/pre increment/decrement operators in python like in languages like C.
We can see ++
or --
as multiple signs getting multiplied, like we do in maths (-1) * (-1) = (+1).
E.g.
---count
Parses as
-(-(-count)))
Which translates to
-(+count)
Because, multiplication of -
sign with -
sign is +
And finally,
-count
In Python 3, you can¹ use the Ellipsis literal ...
as a “nop” placeholder for code that hasn't been written yet:
def will_do_something():
...
This is not magic; any expression can be used instead of ...
, e.g.:
def will_do_something():
1
(Can't use the word “sanctioned”, but I can say that this use was not outrightly rejected by Guido.)
¹ 'can' not in {'must', 'should'}
setTimeout()
buys you some time until the DOM elements are loaded, even if is set to 0.
Check this out: setTimeout
DateTime d1 = ...;
DateTime d2 = ...;
Period period = new Period(d1, d2, PeriodType.minutes());
int differenceMinutes = period.getMinutes();
In practice I think this will always give the same result as the answer based on Duration
. For a different time unit than minutes, though, it might be more correct. For example there are 365 days from 2016/2/2 to 2017/2/1, but actually it's less than 1 year and should truncate to 0 years if you use PeriodType.years()
.
In theory the same could happen for minutes because of leap seconds, but Joda doesn't support leap seconds.
Wikipedia points out that the syntax of an IPv6 address includes colons and has a short form preventing fixed-length parsing, and therefore you have to delimit the address portion with []. This completely avoids the odd parsing errors.
(Taken from an edit Peter Wone made to the original question.)
The os.exec*()
functions replace the current programm with the new one. When this programm ends so does your process. You probably want os.system()
.
If you are trying to find the difference between timestamps that are in pandas columns, the the answer is fairly simple. If you need it in days or seconds then
# For difference in days:
df['diff_in_days']=(df['timestamp2'] - df['timestamp1']).dt.days
# For difference in seconds
df['diff_in_seconds']=(df['timestamp2'] - df['timestamp1']).dt.seconds
Now minute is tricky as dt.minute works only on datetime64[ns] dtype. whereas the column generated from subtracting two datetimes has format
AttributeError: 'TimedeltaProperties' object has no attribute 'm8'
So like mentioned by many above to get the actual value of the difference in minute you have to do:
df['diff_in_min']=df['diff_in_seconds']/60
But if just want the difference between the minute parts of the two timestamps then do the following
#convert the timedelta to datetime and then extract minute
df['diff_in_min']=(pd.to_datetime(df['timestamp2']-df['timestamp1'])).dt.minute
You can also read the article https://docs.python.org/3.4/library/datetime.html and see section 8.1.2 you'll see the read only attributes are only seconds,days and milliseconds. And this settles why the minute function doesn't work directly.
Change the default block from "Code" to "Markdown" before running this code:
![<caption>](image_filename.png)
If image file is in another folder, you can do the following:
![<caption>](folder/image_filename.png)
Try this one:
function show_sub(cat) {
var parent = cat,
sub = parent.getElementsByClassName('sub');
if (sub[0].style.display == 'inline'){
sub[0].style.display = 'none';
}
else {
sub[0].style.display = 'inline';
}
}
document.getElementById('cat').onclick = function(){
show_sub(this);
};?
and use this for IE6 & 7
if (typeof document.getElementsByClassName!='function') {
document.getElementsByClassName = function() {
var elms = document.getElementsByTagName('*');
var ei = new Array();
for (i=0;i<elms.length;i++) {
if (elms[i].getAttribute('class')) {
ecl = elms[i].getAttribute('class').split(' ');
for (j=0;j<ecl.length;j++) {
if (ecl[j].toLowerCase() == arguments[0].toLowerCase()) {
ei.push(elms[i]);
}
}
} else if (elms[i].className) {
ecl = elms[i].className.split(' ');
for (j=0;j<ecl.length;j++) {
if (ecl[j].toLowerCase() == arguments[0].toLowerCase()) {
ei.push(elms[i]);
}
}
}
}
return ei;
}
}
I found that JimTheDev's answer only worked when the state definition had cache:false
set. With the view cached, you can do $ionicHistory.clearCache()
and then $state.go('app.fooDestinationView')
if you're navigating from one state to the one that is cached but needs refreshing.
See my answer here as it requires a simple change to Ionic and I created a pull request: https://stackoverflow.com/a/30224972/756177
LogisticRegression
is not for regression but classification !
The Y
variable must be the classification class,
(for example 0
or 1
)
And not a continuous
variable,
that would be a regression problem.
You can use the filter_var()
function, which gives you a lot of handy validation and sanitization options.
filter_var($email, FILTER_VALIDATE_EMAIL)
Available in PHP >= 5.2.0
If you don't want to change your code that relied on your function, just do:
function isValidEmail($email){
return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}
Note: For other uses (where you need Regex), the deprecated ereg
function family (POSIX Regex Functions) should be replaced by the preg
family (PCRE Regex Functions). There are a small amount of differences, reading the Manual should suffice.
Update 1: As pointed out by @binaryLV:
PHP 5.3.3 and 5.2.14 had a bug related to FILTER_VALIDATE_EMAIL, which resulted in segfault when validating large values. Simple and safe workaround for this is using
strlen()
beforefilter_var()
. I'm not sure about 5.3.4 final, but it is written that some 5.3.4-snapshot versions also were affected.
This bug has already been fixed.
Update 2: This method will of course validate bazmega@kapa
as a valid email address, because in fact it is a valid email address. But most of the time on the Internet, you also want the email address to have a TLD: [email protected]
. As suggested in this blog post (link posted by @Istiaque Ahmed), you can augment filter_var()
with a regex that will check for the existence of a dot in the domain part (will not check for a valid TLD though):
function isValidEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL)
&& preg_match('/@.+\./', $email);
}
As @Eliseo Ocampos pointed out, this problem only exists before PHP 5.3, in that version they changed the regex and now it does this check, so you do not have to.
Calculating AUC with Metrics package is very easy and straightforward:
library(Metrics)
actual <- c(0, 0, 1, 1)
predicted <- c(.1, .3, .3, .9)
auc(actual, predicted)
0.875
You have misspelt the second pixels
as pixel
. The following works:
pixels = [1,2,3]
pixels[0] = 5
It appears that due to the typo you were trying to accidentally modify some tuple called pixel
, and in Python tuples are immutable. Hence the confusing error message.
this solution work only .if your want to ignore this Warning
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:ignore="GoogleAppIndexingWarning"
package="com.example.saloononlinesolution">
As far as I know a Panel can have a transparent color only, you can not control the opacity of the panel. So, you can have some parts of a panel completely transparent but not a 50% to say something.
To use transparency you must define the transparent color property.
How about
session.query(MyUserClass).filter(MyUserClass.id.in_((123,456))).all()
edit: Without the ORM, it would be
session.execute(
select(
[MyUserTable.c.id, MyUserTable.c.name],
MyUserTable.c.id.in_((123, 456))
)
).fetchall()
select()
takes two parameters, the first one is a list of fields to retrieve, the second one is the where
condition. You can access all fields on a table object via the c
(or columns
) property.
I use this custom binding (based on this fiddle by RP Niemeyer, see his answer to this question), which makes sure the numeric value is properly converted from string to number (as suggested by the solution of Michael Best):
Javascript:
ko.bindingHandlers.valueAsNumber = {
init: function (element, valueAccessor, allBindingsAccessor) {
var observable = valueAccessor(),
interceptor = ko.computed({
read: function () {
var val = ko.utils.unwrapObservable(observable);
return (observable() ? observable().toString() : observable());
},
write: function (newValue) {
observable(newValue ? parseInt(newValue, 10) : newValue);
},
owner: this
});
ko.applyBindingsToNode(element, { value: interceptor });
}
};
Example HTML:
<select data-bind="valueAsNumber: level, event:{ change: $parent.permissionChanged }">
<option value="0"></option>
<option value="1">R</option>
<option value="2">RW</option>
</select>