Consider using django-bulk-update
found here on GitHub.
Install: pip install django-bulk-update
Implement: (code taken directly from projects ReadMe file)
from bulk_update.helper import bulk_update
random_names = ['Walter', 'The Dude', 'Donny', 'Jesus']
people = Person.objects.all()
for person in people:
r = random.randrange(4)
person.name = random_names[r]
bulk_update(people) # updates all columns using the default db
Update: As Marc points out in the comments this is not suitable for updating thousands of rows at once. Though it is suitable for smaller batches 10's to 100's. The size of the batch that is right for you depends on your CPU and query complexity. This tool is more like a wheel barrow than a dump truck.
Just don't set the height of the input box, only set the font-size, that will be ok
Just in case anyone else runs into this. I troubleshooted all of these steps and it turns out because I unzipped some files from a MAC, Microsoft automatically without any notification Encrypted the files. After hours of trying to set folder permissions I went in and saw the file names were green which means the files were encrypted and IIS will throw the same error even if folder permissions are correct.
Swift 3.0
Try this, you don't need to check for any condition I have done everything just use this function. Send anything string, number, float, double ,etc,. you get a number as a value or 0 if it is unable to convert your value
Function:
func getNumber(number: Any?) -> NSNumber {
guard let statusNumber:NSNumber = number as? NSNumber else
{
guard let statString:String = number as? String else
{
return 0
}
if let myInteger = Int(statString)
{
return NSNumber(value:myInteger)
}
else{
return 0
}
}
return statusNumber
}
Usage:
Add the above function in code and to convert use
let myNumber = getNumber(number: myString)
if the myString
has a number or string it returns the number else it returns 0
Example 1:
let number:String = "9834"
print("printing number \(getNumber(number: number))")
Output: printing number 9834
Example 2:
let number:Double = 9834
print("printing number \(getNumber(number: number))")
Output: printing number 9834
Example 3:
let number = 9834
print("printing number \(getNumber(number: number))")
Output: printing number 9834
You could use a List<T>
and when T
is a value type it will be allocated in contiguous memory which would not be the case if T
is a reference type.
Example:
List<int> integers = new List<int>();
integers.Add(1);
integers.Add(4);
integers.Add(7);
int someElement = integers[1];
Swap should take place on the Instance Storage (ephemeral) disk and not an EBS device. Swapping will cause a lot of IO and will increase cost on EBS. EBS is also slower than the Instance Store and the Instance Store comes free with certain types of EC2 Instances.
It will usually be mounted to /mnt but if not run
sudo mount /dev/xvda2 /mnt
To then create a swap file on this device do the following for a 4GB swapfile
sudo dd if=/dev/zero of=/mnt/swapfile bs=1M count=4096
Make sure no other user can view the swap file
sudo chown root:root /mnt/swapfile
sudo chmod 600 /mnt/swapfile
Make and Flag as swap
sudo mkswap /mnt/swapfile
sudo swapon /mnt/swapfile
Add/Make sure the following are in your /etc/fstab
/dev/xvda2 /mnt auto defaults,nobootwait,comment=cloudconfig 0 2
/mnt/swapfile swap swap defaults 0 0
lastly enable swap
sudo swapon -a
Have a look at: Greybox
It's an awesome version of lightbox that supports forms, external web pages as well as the traditional images and slideshows. It works perfectly from a link on a webpage.
You will find many information on how to use Greybox and also some great examples. Cheers Kara
Neither of them worked for me for some reason.
I figured it out that for some reason python doesn't read %s. So use (?) instead of %S in you SQL Code.
And finally this worked for me.
cursor.execute ("update tablename set columnName = (?) where ID = (?) ",("test4","4"))
connect.commit()
There are a lot of ways to do that :
t = s.split(" ")
if len(t) > 1:
print "several tokens"
To be sure it matches every kind of space, you can use re module :
import re
if re.search(r"\s", your_string):
print "several words"
All previous answers are correct, here is one more and easy way to do it. For example, create a Dict data structure to serialize and deserialize an object
(Notice None is Null in python and I'm intentionally using this to demonstrate how you can store null and convert it to json null)
import json
print('serialization')
myDictObj = { "name":"John", "age":30, "car":None }
##convert object to json
serialized= json.dumps(myDictObj, sort_keys=True, indent=3)
print(serialized)
## now we are gonna convert json to object
deserialization=json.loads(serialized)
print(deserialization)
As others have mentioned you have to consume stderr and stdout.
Compared to the other answers, since Java 1.7 it is even more easy. You do not have to create threads yourself anymore to read stderr and stdout.
Just use the ProcessBuilder
and use the methods redirectOutput
in combination with either redirectError
or redirectErrorStream
.
String directory = "/working/dir";
File out = new File(...); // File to write stdout to
File err = new File(...); // File to write stderr to
ProcessBuilder builder = new ProcessBuilder();
builder.directory(new File(directory));
builder.command(command);
builder.redirectOutput(out); // Redirect stdout to file
if(out == err) {
builder.redirectErrorStream(true); // Combine stderr into stdout
} else {
builder.redirectError(err); // Redirect stderr to file
}
Process process = builder.start();
Adding to @Hendrik Eichler Answer, the n vh
uses n%
of the viewport's initial containing block.
.element{
height: 50vh; /* Would mean 50% of Viewport height */
width: 75vw; /* Would mean 75% of Viewport width*/
}
Also, the viewport height is for devices of any resolution, the view port height, width is one of the best ways (similar to css design using % values but basing it on the device's view port height and width)
vh
Equal to 1% of the height of the viewport's initial containing block.
vw
Equal to 1% of the width of the viewport's initial containing block.
vi
Equal to 1% of the size of the initial containing block, in the direction of the root element’s inline axis.
vb
Equal to 1% of the size of the initial containing block, in the direction of the root element’s block axis.
vmin
Equal to the smaller of vw and vh.
vmax
Equal to the larger of vw and vh.
Ref: https://developer.mozilla.org/en-US/docs/Web/CSS/length#Viewport-percentage_lengths
It is happening because .header-shadow
is empty.
Add height
to it:
.header-shadow{
background-image: url('../images/header-shade.jpg');
background-color: red;
height: 50px;
}
Apparently, the system I was using had the docker-ce not Docker. Thus, running below command did the trick.
sudo apt-get purge docker-ce
sudo rm -rf /var/lib/docker
hope it helps
For C
/C++
programs there's very good package gpp-compiler.
Shortcuts:
F5
F6
This worked for me. Thank you Rody!
y="HELLO"
val=$(echo $y | tr '[:upper:]' '[:lower:]')
string="$val world"
one small modification, if you are using underscore next to the variable You need to encapsulate the variable name in {}.
string="${val}_world"
Addition to the Usage from the ORM layer in the accepted answer: count(*) can be done for ORM using the query.with_entities(func.count())
, like this:
session.query(MyModel).with_entities(func.count()).scalar()
It can also be used in more complex cases, when we have joins and filters - the important thing here is to place with_entities
after joins, otherwise SQLAlchemy could raise the Don't know how to join
error.
For example:
User
model (id
, name
) and Song
model (id
, title
, genre
)UserSong
model (user_id
, song_id
, is_liked
) where user_id
+ song_id
is a primary key)We want to get a number of user's liked rock songs:
SELECT count(*)
FROM user_song
JOIN song ON user_song.song_id = song.id
WHERE user_song.user_id = %(user_id)
AND user_song.is_liked IS 1
AND song.genre = 'rock'
This query can be generated in a following way:
user_id = 1
query = session.query(UserSong)
query = query.join(Song, Song.id == UserSong.song_id)
query = query.filter(
and_(
UserSong.user_id == user_id,
UserSong.is_liked.is_(True),
Song.genre == 'rock'
)
)
# Note: important to place `with_entities` after the join
query = query.with_entities(func.count())
liked_count = query.scalar()
Complete example is here.
i tried using the same ng-click for two elements with same name showDetail2('abc')
it is working for me . can you check rest of the code which may be breaking you to move further.
# here database details
mysql_connect('hostname', 'username', 'password');
mysql_select_db('database-name');
$sql = "SELECT username FROM userregistraton";
$result = mysql_query($sql);
echo "<select name='username'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['username'] ."'>" . $row['username'] ."</option>";
}
echo "</select>";
# here username is the column of my table(userregistration)
# it works perfectly
This my solution:
Working in real project.
$(function () {
$("#accordion").accordion({collapsible:true, active:false});
$('.open').click(function () {
$('.ui-accordion-header').removeClass('ui-corner-all').addClass('ui-accordion-header-active ui-state-active ui-corner-top').attr({'aria-selected':'true','tabindex':'0'});
$('.ui-accordion-header .ui-icon').removeClass('ui-icon-triangle-1-e').addClass('ui-icon-triangle-1-s');
$('.ui-accordion-content').addClass('ui-accordion-content-active').attr({'aria-expanded':'true','aria-hidden':'false'}).show();
$(this).hide();
$('.close').show();
});
$('.close').click(function () {
$('.ui-accordion-header').removeClass('ui-accordion-header-active ui-state-active ui-corner-top').addClass('ui-corner-all').attr({'aria-selected':'false','tabindex':'-1'});
$('.ui-accordion-header .ui-icon').removeClass('ui-icon-triangle-1-s').addClass('ui-icon-triangle-1-e');
$('.ui-accordion-content').removeClass('ui-accordion-content-active').attr({'aria-expanded':'false','aria-hidden':'true'}).hide();
$(this).hide();
$('.open').show();
});
$('.ui-accordion-header').click(function () {
$('.open').show();
$('.close').show();
});
});
Try this,
<?php
$arr1=array('result1'=>'abcd','result2'=>'efg');
$arr2=array('result1'=>'hijk','result2'=>'lmn');
$arr3=array($arr1,$arr2);
print (json_encode($arr3));
?>
Since there is so much confusion about functionality of standard service accounts, I'll try to give a quick run down.
First the actual accounts:
LocalService account (preferred)
A limited service account that is very similar to Network Service and meant to run standard least-privileged services. However, unlike Network Service it accesses the network as an Anonymous user.
NT AUTHORITY\LocalService
HKEY_USERS\S-1-5-19
)
Limited service account that is meant to run standard privileged services. This account is far more limited than Local System (or even Administrator) but still has the right to access the network as the machine (see caveat above).
NT AUTHORITY\NetworkService
MANGO$
) to remote serversHKEY_USERS\S-1-5-20
)NETWORK SERVICE
into the Select User or Group dialog
LocalSystem account (dangerous, don't use!)
Completely trusted account, more so than the administrator account. There is nothing on a single box that this account cannot do, and it has the right to access the network as the machine (this requires Active Directory and granting the machine account permissions to something)
.\LocalSystem
(can also use LocalSystem
or ComputerName\LocalSystem
)HKCU
represents the default user)MANGO$
) to remote servers
Above when talking about accessing the network, this refers solely to SPNEGO (Negotiate), NTLM and Kerberos and not to any other authentication mechanism. For example, processing running as LocalService
can still access the internet.
The general issue with running as a standard out of the box account is that if you modify any of the default permissions you're expanding the set of things everything running as that account can do. So if you grant DBO to a database, not only can your service running as Local Service or Network Service access that database but everything else running as those accounts can too. If every developer does this the computer will have a service account that has permissions to do practically anything (more specifically the superset of all of the different additional privileges granted to that account).
It is always preferable from a security perspective to run as your own service account that has precisely the permissions you need to do what your service does and nothing else. However, the cost of this approach is setting up your service account, and managing the password. It's a balancing act that each application needs to manage.
In your specific case, the issue that you are probably seeing is that the the DCOM or COM+ activation is limited to a given set of accounts. In Windows XP SP2, Windows Server 2003, and above the Activation permission was restricted significantly. You should use the Component Services MMC snapin to examine your specific COM object and see the activation permissions. If you're not accessing anything on the network as the machine account you should seriously consider using Local Service (not Local System which is basically the operating system).
In Windows Server 2003 you cannot run a scheduled task as
NT_AUTHORITY\LocalService
(aka the Local Service account), or NT AUTHORITY\NetworkService
(aka the Network Service account). That capability only was added with Task Scheduler 2.0, which only exists in Windows Vista/Windows Server 2008 and newer.
A service running as NetworkService
presents the machine credentials on the network. This means that if your computer was called mango
, it would present as the machine account MANGO$
:
"C:\Program Files\PuTTY\pscp.exe" -scp file.py server.com:
file.py
will be uploaded into your HOME
dir on remote server.
or when the remote server has a different user, use "C:\Program Files\PuTTY\pscp.exe" -l username -scp file.py server.com:
After connecting to the server pscp will ask for a password.
For readability, I prefer this:
if (inputString.length() > maxLength) {
inputString = inputString.substring(0, maxLength);
}
over the accepted answer.
int maxLength = (inputString.length() < MAX_CHAR)?inputString.length():MAX_CHAR;
inputString = inputString.substring(0, maxLength);
The problem is, you are creating a transport
object and using it's connect method to authenticate yourself.
But then you use a static
method to send the message which ignores authentication done by the object.
So, you should either use the sendMessage(message, message.getAllRecipients())
method on the object or use an authenticator as suggested by others to get authorize
through the session.
Here's the Java Mail FAQ, you need to read.
AJAX is simply Asyncronous JSON or XML (in most newer situations JSON). Because we are doing an ASYNC task we will likely be providing our users with a more enjoyable UI experience. In this specific case we are doing a FORM submission using AJAX.
Really quickly there are 4 general web actions GET
, POST
, PUT
, and DELETE
; these directly correspond with SELECT/Retreiving DATA
, INSERTING DATA
, UPDATING/UPSERTING DATA
, and DELETING DATA
. A default HTML/ASP.Net webform/PHP/Python or any other form
action is to "submit" which is a POST action. Because of this the below will all describe doing a POST. Sometimes however with http you might want a different action and would likely want to utilitize .ajax
.
/* attach a submit handler to the form */
$("#formoid").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get the action attribute from the <form action=""> element */
var $form = $(this),
url = $form.attr('action');
/* Send the data using post with element id name and name2*/
var posting = $.post(url, {
name: $('#name').val(),
name2: $('#name2').val()
});
/* Alerts the results */
posting.done(function(data) {
$('#result').text('success');
});
posting.fail(function() {
$('#result').text('failed');
});
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="formoid" action="studentFormInsert.php" title="" method="post">
<div>
<label class="title">First Name</label>
<input type="text" id="name" name="name">
</div>
<div>
<label class="title">Last Name</label>
<input type="text" id="name2" name="name2">
</div>
<div>
<input type="submit" id="submitButton" name="submitButton" value="Submit">
</div>
</form>
<div id="result"></div>
_x000D_
From jQuery website $.post
documentation.
Example: Send form data using ajax requests
$.post("test.php", $("#testform").serialize());
Example: Post a form using ajax and put results in a div
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<form action="/" id="searchForm">
<input type="text" name="s" placeholder="Search..." />
<input type="submit" value="Search" />
</form>
<!-- the result of the search will be rendered inside this div -->
<div id="result"></div>
<script>
/* attach a submit handler to the form */
$("#searchForm").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $(this),
term = $form.find('input[name="s"]').val(),
url = $form.attr('action');
/* Send the data using post */
var posting = $.post(url, {
s: term
});
/* Put the results in a div */
posting.done(function(data) {
var content = $(data).find('#content');
$("#result").empty().append(content);
});
});
</script>
</body>
</html>
Without using OAuth or at minimum HTTPS (TLS/SSL) please don't use this method for secure data (credit card numbers, SSN, anything that is PCI, HIPAA, or login related)
Another real-life example:
$result = & "$env:cust_tls_store\Tools\WDK\x64\devcon.exe" enable $strHwid 2>&1 | Out-String
Notice that this example includes a path (which begins with an environment variable). Notice that the quotes must surround the path and the EXE file, but not the parameters!
Note: Don't forget the &
character in front of the command, but outside of the quotes.
The error output is also collected.
It took me a while to get this combination working, so I thought that I would share it.
Yes, NSDictionary
supports fast enumeration. With Objective-C 2.0, you can do this:
// To print out all key-value pairs in the NSDictionary myDict
for(id key in myDict)
NSLog(@"key=%@ value=%@", key, [myDict objectForKey:key]);
The alternate method (which you have to use if you're targeting Mac OS X pre-10.5, but you can still use on 10.5 and iPhone) is to use an NSEnumerator
:
NSEnumerator *enumerator = [myDict keyEnumerator];
id key;
// extra parens to suppress warning about using = instead of ==
while((key = [enumerator nextObject]))
NSLog(@"key=%@ value=%@", key, [myDict objectForKey:key]);
A stored procedure is a group of SQL statements that has been created and stored in the database. A stored procedure will accept input parameters so that a single procedure can be used over the network by several clients using different input data. A stored procedures will reduce network traffic and increase the performance. If we modify a stored procedure all the clients will get the updated stored procedure.
Sample of creating a stored procedure
CREATE PROCEDURE test_display
AS
SELECT FirstName, LastName
FROM tb_test;
EXEC test_display;
Advantages of using stored procedures
A stored procedure allows modular programming.
You can create the procedure once, store it in the database, and call it any number of times in your program.
A stored procedure allows faster execution.
If the operation requires a large amount of SQL code that is performed repetitively, stored procedures can be faster. They are parsed and optimized when they are first executed, and a compiled version of the stored procedure remains in a memory cache for later use. This means the stored procedure does not need to be reparsed and reoptimized with each use, resulting in much faster execution times.
A stored procedure can reduce network traffic.
An operation requiring hundreds of lines of Transact-SQL code can be performed through a single statement that executes the code in a procedure, rather than by sending hundreds of lines of code over the network.
Stored procedures provide better security to your data
Users can be granted permission to execute a stored procedure even if they do not have permission to execute the procedure's statements directly.
In SQL Server we have different types of stored procedures:
System-stored procedures are stored in the master database and these start with a sp_
prefix. These procedures can be used to perform a variety of tasks to support SQL Server functions for external application calls in the system tables
Example: sp_helptext [StoredProcedure_Name]
User-defined stored procedures are usually stored in a user database and are typically designed to complete the tasks in the user database. While coding these procedures don’t use the sp_
prefix because if we use the sp_
prefix first, it will check the master database, and then it comes to user defined database.
Extended stored procedures are the procedures that call functions from DLL files. Nowadays, extended stored procedures are deprecated for the reason it would be better to avoid using extended stored procedures.
Apparently with Laravel 5.2, the closure in DB::listen
only receives a single parameter.
So, if you want to use DB::listen
in Laravel 5.2, you should do something like:
DB::listen(
function ($sql) {
// $sql is an object with the properties:
// sql: The query
// bindings: the sql query variables
// time: The execution time for the query
// connectionName: The name of the connection
// To save the executed queries to file:
// Process the sql and the bindings:
foreach ($sql->bindings as $i => $binding) {
if ($binding instanceof \DateTime) {
$sql->bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
} else {
if (is_string($binding)) {
$sql->bindings[$i] = "'$binding'";
}
}
}
// Insert bindings into query
$query = str_replace(array('%', '?'), array('%%', '%s'), $sql->sql);
$query = vsprintf($query, $sql->bindings);
// Save the query to file
$logFile = fopen(
storage_path('logs' . DIRECTORY_SEPARATOR . date('Y-m-d') . '_query.log'),
'a+'
);
fwrite($logFile, date('Y-m-d H:i:s') . ': ' . $query . PHP_EOL);
fclose($logFile);
}
);
In case this is useful to anyone I had this same issue. I was bringing in a footer into a web page via jQuery. Inside that footer were some Google scripts for ads and retargeting. I had to move those scripts from the footer and place them directly in the page and that eliminated the notice.
I found that the Import Paths
in the Build Settings
was wrong for a custom (MySQL) module. After pointing that to the right direction the message was gone.
Try this Javascript (jquery) code. Its an ajax request to an external URL. Use the callback function to fire any code:
<script type="text/javascript">
$(function() {
$('form').submit(function(){
$.post('http://example.com/upload', function() {
window.location = 'http://google.com';
});
return false;
});
});
</script>
An alternative is to use OFFSET:
Assuming the column value is stored in B1, you can use the following
C1 = OFFSET(A1, 0, B1 - 1)
This works by:
a) taking a base cell (A1)
b) adding 0 to the row (keeping it as A)
c) adding (A5 - 1) to the column
You can also use another value instead of 0 if you want to change the row value too.
There is no portable way to read raw characters from a Java console.
Some platform-dependent workarounds have been presented above. But to be really portable, you'd have to abandon console mode and use a windowing mode, e.g. AWT or Swing.
I think this is it:
sudo update-alternatives --install /usr/bin/node node /usr/bin/nodejs 10
Using Debian alternatives.
Unfortunately RecyclerView
is missing a couple of features that ListView
had built-in.
For example the ability to add an OnItemClickListener
that triggers when an item is clicked.
RecyclerView
allows you to set an OnClickListener
in your adapter, but passing on that click
listener from your calling code, to the adapter and to the ViewHolder
, is complicated
for catching a simple item click.
public class ItemClickSupport {
private final RecyclerView mRecyclerView;
private OnItemClickListener mOnItemClickListener;
private OnItemLongClickListener mOnItemLongClickListener;
private View.OnClickListener mOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mOnItemClickListener != null) {
RecyclerView.ViewHolder holder = mRecyclerView.getChildViewHolder(v);
mOnItemClickListener.onItemClicked(mRecyclerView, holder.getAdapterPosition(), v);
}
}
};
private View.OnLongClickListener mOnLongClickListener = new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
if (mOnItemLongClickListener != null) {
RecyclerView.ViewHolder holder = mRecyclerView.getChildViewHolder(v);
return mOnItemLongClickListener.onItemLongClicked(mRecyclerView, holder.getAdapterPosition(), v);
}
return false;
}
};
private RecyclerView.OnChildAttachStateChangeListener mAttachListener
= new RecyclerView.OnChildAttachStateChangeListener() {
@Override
public void onChildViewAttachedToWindow(View view) {
if (mOnItemClickListener != null) {
view.setOnClickListener(mOnClickListener);
}
if (mOnItemLongClickListener != null) {
view.setOnLongClickListener(mOnLongClickListener);
}
}
@Override
public void onChildViewDetachedFromWindow(View view) {
}
};
private ItemClickSupport(RecyclerView recyclerView) {
mRecyclerView = recyclerView;
mRecyclerView.setTag(R.id.item_click_support, this);
mRecyclerView.addOnChildAttachStateChangeListener(mAttachListener);
}
public static ItemClickSupport addTo(RecyclerView view) {
ItemClickSupport support = (ItemClickSupport) view.getTag(R.id.item_click_support);
if (support == null) {
support = new ItemClickSupport(view);
}
return support;
}
public static ItemClickSupport removeFrom(RecyclerView view) {
ItemClickSupport support = (ItemClickSupport) view.getTag(R.id.item_click_support);
if (support != null) {
support.detach(view);
}
return support;
}
public ItemClickSupport setOnItemClickListener(OnItemClickListener listener) {
mOnItemClickListener = listener;
return this;
}
public ItemClickSupport setOnItemLongClickListener(OnItemLongClickListener listener) {
mOnItemLongClickListener = listener;
return this;
}
private void detach(RecyclerView view) {
view.removeOnChildAttachStateChangeListener(mAttachListener);
view.setTag(R.id.item_click_support, null);
}
public interface OnItemClickListener {
void onItemClicked(RecyclerView recyclerView, int position, View v);
}
public interface OnItemLongClickListener {
boolean onItemLongClicked(RecyclerView recyclerView, int position, View v);
}
}
You also need to define R.id.item_click_support
using ids.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="item_click_support" type="id" />
</resources>
The resulting code click listener now looks like this:
ItemClickSupport.addTo(mRecyclerView).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
@Override
public void onItemClicked(RecyclerView recyclerView, int position, View v) {
// do it
}
});
For Brief Explanation about recyclerview clicks please have a look at this littlerobots_blog
// ???????_x000D_
function getFileExtension(file) {_x000D_
var regexp = /\.([0-9a-z]+)(?:[\?#]|$)/i;_x000D_
var extension = file.match(regexp);_x000D_
return extension && extension[1];_x000D_
}_x000D_
_x000D_
console.log(getFileExtension("https://www.example.com:8080/path/name/foo"));_x000D_
console.log(getFileExtension("https://www.example.com:8080/path/name/foo.BAR"));_x000D_
console.log(getFileExtension("https://www.example.com:8080/path/name/.quz/foo.bar?key=value#fragment"));_x000D_
console.log(getFileExtension("https://www.example.com:8080/path/name/.quz.bar?key=value#fragment"));
_x000D_
How you are running your script? If you did with
$ sh myscript
you should try:
$ bash myscript
or, if the script is executable:
$ ./myscript
sh and bash are two different shells. While in the first case you are passing your script as an argument to the sh interpreter, in the second case you decide on the very first line which interpreter will be used.
Does this work?
Workbooks.Open Filename:=filepath, ReadOnly:=True
Or, as pointed out in a comment, to keep a reference to the opened workbook:
Dim book As Workbook
Set book = Workbooks.Open(Filename:=filepath, ReadOnly:=True)
Use the network byte order (big endian), which is the same as Java uses anyway. See man htons for the different translators in C.
You need to add some arguments. Also, instancing and opening can be put in one line:
fstream file("test.txt", fstream::in | fstream::out | fstream::trunc);
In case you want to handle intent on opened activity, you can use PendintIntent (Complete steps below):
public class SMSReciver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
try {
if (senderNum.contains("MOB_NUMBER")) {
Toast.makeText(context,"",Toast.LENGTH_SHORT).show();
Intent intentCall = new Intent(context, MainActivity.class);
intentCall.putExtra("message", currentMessage.getMessageBody());
PendingIntent pendingIntent= PendingIntent.getActivity(context, 0, intentCall, PendingIntent.FLAG_UPDATE_CURRENT);
pendingIntent.send();
}
} catch (Exception e) {
}
}
}
} catch (Exception e) {
}
}
}
manifest:
<activity android:name=".MainActivity"
android:launchMode="singleTask"/>
<receiver android:name=".SMSReciver">
<intent-filter android:priority="1000">
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
onNewIntent:
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Toast.makeText(this, "onNewIntent", Toast.LENGTH_SHORT).show();
onSMSReceived(intent.getStringExtra("message"));
}
permissions:
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
if(JSON.stringify(Object.keys(pcOrGroup).sort()) === JSON.stringify(Object.keys(orGroup)).sort())
{
return true;
}
public static void main(String[] args) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set("Accept", MediaType.APPLICATION_JSON_VALUE);
final String url = "https://host:port/contract/{code}";
Map<String, String> params = new HashMap<String, String>();
params.put("code", "123456");
HttpEntity<?> httpEntity = new HttpEntity<>(httpHeaders);
RestTemplate restTemplate = new RestTemplate();
restTemplate.exchange(url, HttpMethod.GET, httpEntity,String.class, params);
}
If the below statment is present in your class then your log4j.properties should be in java source(src) folder , if it is jar executable it should be packed in jar not a seperate file.
static Logger log = Logger.getLogger(MyClass.class);
Thanks,
If you use my code (below), the time will appear in seconds, then, after a decimal, milliseconds. I think that there is a difference between Windows and Unix - please comment if there is.
from time import time
x = time()
print(x)
my result (on Windows) was:
1576095264.2682993
EDIT: There is no difference:) Thanks tc0nn
You can't do it with the HTML5 input type. There are many libs available to do it, you can use momentjs or some other jQuery UI components for the best outcome.
Expanding on @baba's answer, which I like, but creates a more complex three level deep multi-dimensional (array(array(array))):
$group = array();
foreach ( $array as $value ) {
$group[$value['id']][] = $value;
}
// output only data from id 96
foreach ($group as $key=>$value) { //outer loop
foreach ($value as $k=>$v){ //inner loop
if($key==96){ //if outer loop is equal to 96 (could be variable)
for ($i=0;$i<count($k);$i++){ //iterate over the inner loop
printf($key.' has a part no. of '.$v['part_no'].' and shipping no. of '.$v['shipping_no'].'<br>');
}
}
}
}
Will output:
96 has a part no. of reterty and shipping number of 212755-1
96 has a part no. of dftgtryh and shipping number of 212755-1
well,
I used System.setProperty("java.net.preferIPv4Stack" , "true");
and it works from JAVA, but it doesn't work on JBOSS AS7.
Here is my work around solution,
Add the below line to the end of the file ${JBOSS_HOME}/bin/standalone.conf.bat (just after :JAVA_OPTS_SET
)
set "JAVA_OPTS=%JAVA_OPTS% -Djava.net.preferIPv4Stack=true"
Note: restart JBoss server
I didn't want to introduce an asset catalog.
Per the answer from seahorseseaeo here, adding the following to info.plist worked for me. (I edited it as a "source code".) I then named the images [email protected] and [email protected]
<key>UILaunchImages</key>
<array>
<dict>
<key>UILaunchImageMinimumOSVersion</key>
<string>8.0</string>
<key>UILaunchImageName</key>
<string>Default-667h</string>
<key>UILaunchImageOrientation</key>
<string>Portrait</string>
<key>UILaunchImageSize</key>
<string>{375, 667}</string>
</dict>
<dict>
<key>UILaunchImageMinimumOSVersion</key>
<string>8.0</string>
<key>UILaunchImageName</key>
<string>Default-736h</string>
<key>UILaunchImageOrientation</key>
<string>Portrait</string>
<key>UILaunchImageSize</key>
<string>{414, 736}</string>
</dict>
</array>
It should run properly at cron also. Please check below things.
1- You are editing proper file to set cron.
2- You have given proper permission(execute permission) to script mean your script is executable.
For Windows if you dont want to edit pb_gba.conf ie leave the method to MD5(default), create a new user, by running this query in Query tool in PGadmin
CREATE USER admin WITH PASSWORD 'secret'
then in cmd
psql "dbname=Main_db host=127.0.0.1 user=admin password=secret port=5432
where dbname is your db in postgresql
In my case I have a kubernetes cluster with nginx ingress controller and nginx+php-fpm to handle drupal instance.
I notice this issue on one of my page, where my pictures was not loaded in chrome. After investigation I discovered that modsecurity module enabled in my nginx ingress somehow produce this issue. Not fully know why, but after disabling it, all pages are loaded fine.
Best Regards.
People mentioned string.find()
, string.index()
, and string.indexOf()
in the comments, and I summarize them here (according to the Python Documentation):
First of all there is not a string.indexOf()
method. The link posted by Deviljho shows this is a JavaScript function.
Second the string.find()
and string.index()
actually return the index of a substring. The only difference is how they handle the substring not found situation: string.find()
returns -1
while string.index()
raises an ValueError
.
You can use INTERVAL type or just add calculated number value - "1" is equal "1 day".
first way:
select date_column + INTERVAL '0 01:00:00' DAY TO SECOND from dual;
second way:
select date_column + 1/24 from dual;
First way is more convenient when you need to add a complicated value - for example, "1 day 3 hours 25 minutes 49 seconds". See also: http://www.oracle-base.com/articles/misc/oracle-dates-timestamps-and-intervals.php
Also you have to remember that oracle have two interval types - DAY TO SECOND and YEAR TO MONTH. As for me, one interval type would be better, but I hope people in oracle knows, what they do ;)
App::cpanminus
from CPAN (use: cpan App::cpanminus
for this).cpanm --uninstall Module::Name
(note the "m
") to uninstall the module with cpanminus.This should work.
str_replace('"', "", $string);
str_replace("'", "", $string);
I assume you mean quotation marks?
Otherwise, go for some regex, this will work for html quotes for example:
preg_replace("/<!--.*?-->/", "", $string);
C-style quotes:
preg_replace("/\/\/.*?\n/", "\n", $string);
CSS-style quotes:
preg_replace("/\/*.*?\*\//", "", $string);
bash-style quotes:
preg-replace("/#.*?\n/", "\n", $string);
Etc etc...
// Just simply add border around the image view or view
<ImageView
android:id="@+id/imageView2"
android:layout_width="90dp"
android:layout_height="70dp"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:layout_toLeftOf="@+id/imageView1"
android:background="@android:color/white"
android:padding="5dip" />
// After that dynamically put color into your view or image view object
objView.setBackgroundColor(Color.GREEN);
//VinodJ/Abhishek
You can delete multiple branches on windows using Git GUI:
Python Extension. From the Python Docs:
The solution chosen by the Perl developers was to use (?...) as the extension syntax. ? immediately after a parenthesis was a syntax error because the ? would have nothing to repeat, so this didn’t introduce any compatibility problems. The characters immediately after the ? indicate what extension is being used, so (?=foo) is one thing (a positive lookahead assertion) and (?:foo) is something else (a non-capturing group containing the subexpression foo).
Python supports several of Perl’s extensions and adds an extension syntax to Perl’s extension syntax.If the first character after the question mark is a P, you know that it’s an extension that’s specific to Python
You are giving the span a 100% width resulting in it expanding to the size of the parent. This means you can’t center-align it, as there is no room to move it.
You could give the span a set width, then add the margin:0 auto
again. This would center-align it.
.left
{
background-color: #999999;
height: 50px;
width: 24.5%;
}
span.panelTitleTxt
{
display:block;
width:100px;
height: 100%;
margin: 0 auto;
}
You can use enum and refer that enum in annotation field
package name with 0 may cause problem for sharedPreference.
(OK) con = createPackageContext("com.example.android.sf1", 0);
(Problem but no error)
con = createPackageContext("com.example.android.sf01", 0);
Proper way to do it is to change the width on the online customizer here:
http://getbootstrap.com/customize/
download the recompiled source, overwrite the existing bootstrap dist dir, and reload (mind the browser cache!!!)
All your changes will be retained in the .json configuration file
To apply again the all the changes just upload the json file and you are ready to go
Constructor of public
class clients
is public
but it has a parameter of type ACTInterface
that is private
(it is nested in a class?). You can't do that. You need to make ACTInterface
at least as accessible as clients
.
Here is the code to mock this functionality using PowerMockito API.
Second mockedSecond = PowerMockito.mock(Second.class);
PowerMockito.whenNew(Second.class).withNoArguments().thenReturn(mockedSecond);
You need to use Powermockito runner and need to add required test classes (comma separated ) which are required to be mocked by powermock API .
@RunWith(PowerMockRunner.class)
@PrepareForTest({First.class,Second.class})
class TestClassName{
// your testing code
}
$("div").click(function() {
var txtClass = $(this).attr("class");
console.log("Class Name : "+txtClass);
});
Remove numbers, underscore, white-spaces and special characters from the string sentence.
str.replace(/[0-9`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi,'');
Though not exactly what the Q was asking for, I've built one that is similar but uses named placeholders instead of numbered. I personally prefer having named arguments and just send in an object as an argument to it (more verbose, but easier to maintain).
String.prototype.format = function (args) {
var newStr = this;
for (var key in args) {
newStr = newStr.replace('{' + key + '}', args[key]);
}
return newStr;
}
Here's an example usage...
alert("Hello {name}".format({ name: 'World' }));
A slightly updated answer (since I ran into this problem in different circumstances.)
When you connect to a server using SSL, the first thing the server does is present a certificate which says "I am api.dropbox.com." The certificate has a "subject" and the subject has a "CN" (short for "common name".) The certificate may also have one or more "subjectAltNames". When node.js connects to a server, node.js fetches this certificate, and then verifies that the domain name it thinks it's connecting to (api.dropbox.com) matches either the subject's CN or one of the altnames. Note that, in node 0.10.x, if you connect using an IP, the IP address has to be in the altnames - node.js will not try to verify the IP against the CN.
Setting the rejectUnauthorized
flag to false will get around this check, but first of all if the server is giving you different credentials than you are expecting, something fishy is going on, and second this will also bypass other checks - it's not a good idea if you're connecting over the Internet.
If you are using node >= 0.11.x, you can also specify a checkServerIdentity: function(host, cert)
function to the tls module, which should return undefined
if you want to allow the connection and throw an exception otherwise (although I don't know if request
will proxy this flag through to tls for you.) It can be handy to declare such a function and console.log(host, cert);
to figure out what the heck is going on.
I use this function in my code:
$.fn.extend({_x000D_
insertAtCaret: function(myValue) {_x000D_
this.each(function() {_x000D_
if (document.selection) {_x000D_
this.focus();_x000D_
var sel = document.selection.createRange();_x000D_
sel.text = myValue;_x000D_
this.focus();_x000D_
} else if (this.selectionStart || this.selectionStart == '0') {_x000D_
var startPos = this.selectionStart;_x000D_
var endPos = this.selectionEnd;_x000D_
var scrollTop = this.scrollTop;_x000D_
this.value = this.value.substring(0, startPos) +_x000D_
myValue + this.value.substring(endPos,this.value.length);_x000D_
this.focus();_x000D_
this.selectionStart = startPos + myValue.length;_x000D_
this.selectionEnd = startPos + myValue.length;_x000D_
this.scrollTop = scrollTop;_x000D_
} else {_x000D_
this.value += myValue;_x000D_
this.focus();_x000D_
}_x000D_
});_x000D_
return this;_x000D_
}_x000D_
});
_x000D_
input{width:100px}_x000D_
label{display:block;margin:10px 0}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<label>Copy text from: <input id="in2copy" type="text" value="x"></label>_x000D_
<label>Insert text in: <input id="in2ins" type="text" value="1,2,3" autofocus></label>_x000D_
<button onclick="$('#in2ins').insertAtCaret($('#in2copy').val())">Insert</button>
_x000D_
It's not 100% mine, I googled it somewhere and then tuned for mine app.
Usage: $('#element').insertAtCaret('text');
The SQL used in a PreparedStatement is precompiled on the driver. From that point on, the parameters are sent to the driver as literal values and not executable portions of SQL; thus no SQL can be injected using a parameter. Another beneficial side effect of PreparedStatements (precompilation + sending only parameters) is improved performance when running the statement multiple times even with different values for the parameters (assuming that the driver supports PreparedStatements) as the driver does not have to perform SQL parsing and compilation each time the parameters change.
What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.
I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)
http://en.cppreference.com/w/cpp/memory/weak_ptr std::weak_ptr is a smart pointer that holds a non-owning ("weak") reference to an object that is managed by std::shared_ptr. It must be converted to std::shared_ptr in order to access the referenced object.
std::weak_ptr models temporary ownership: when an object needs to be accessed only if it exists, and it may be deleted at any time by someone else, std::weak_ptr is used to track the object, and it is converted to std::shared_ptr to assume temporary ownership. If the original std::shared_ptr is destroyed at this time, the object's lifetime is extended until the temporary std::shared_ptr is destroyed as well.
In addition, std::weak_ptr is used to break circular references of std::shared_ptr.
In addition to uncommenting the ;extension=php_openssl.dll
line in php.ini
that everyone else has mentioned, you also have to ensure the ;extension_dir = "ext"
line is also uncommented. To uncomment, remove the prefixed semicolon and save.
That line might already be uncommented in packages like WAMP and XAMPP, but it's not in a plain PHP download for Windows, so it's worth verifying. Also, you have to create the php.ini
file by copying one of the examples, like php.ini-development
to a new file and then name it php.ini
. Then make these changes there.
Also, in the future, to install tools such as PHP and Composer, I recommend using the Chocolatey package manager. Then it's as simple as choco install composer
. Of course, you'd still need to edit php.ini before installing Composer with the choco method. In future versions of Windows, package management tools like Chocolatey will be baked into Windows, the same way apt-get
is in Ubuntu. Exciting times ahead for developers!
With either method, after installing Composer, don't forget to restart your terminal. Whether you're using Command Prompt, Bash (installs with Git), or Powershell, you'll need to restart it before the updated environmental variables work.
In browsers other than Internet Explorer, you can pass parameters to the function together after the delay:
var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);
So, you can do this:
var timeoutID = window.setTimeout(function (self) {
console.log(self);
}, 500, this);
This is better in terms of performance than a scope lookup (caching this
into a variable outside of the timeout / interval expression), and then creating a closure (by using $.proxy
or Function.prototype.bind
).
The code to make it work in IEs from Webreflection:
/*@cc_on
(function (modifierFn) {
// you have to invoke it as `window`'s property so, `window.setTimeout`
window.setTimeout = modifierFn(window.setTimeout);
window.setInterval = modifierFn(window.setInterval);
})(function (originalTimerFn) {
return function (callback, timeout){
var args = [].slice.call(arguments, 2);
return originalTimerFn(function () {
callback.apply(this, args)
}, timeout);
}
});
@*/
Referencing XCopy Force File
For forcing files, we could use pipeline "echo F |":
C:\Trash>xcopy 23.txt 24.txt
Does 24.txt specify a file name
or directory name on the target
(F = file, D = directory)?
C:\Trash>echo F | xcopy 23.txt 24.txt
Does 24.txt specify a file name
or directory name on the target
(F = file, D = directory)? F
C:23.txt
1 File(s) copied
For forcing a folder, we could use /i parameter for xcopy or using a backslash() at the end of the destination folder.
Bind variable can be used in Oracle SQL query with "in" clause.
Works in 10g; I don't know about other versions.
Bind variable is varchar up to 4000 characters.
Example: Bind variable containing comma-separated list of values, e.g.
:bindvar = 1,2,3,4,5
select * from mytable
where myfield in
(
SELECT regexp_substr(:bindvar,'[^,]+', 1, level) items
FROM dual
CONNECT BY regexp_substr(:bindvar, '[^,]+', 1, level) is not null
);
(Same info as I posted here: How do you specify IN clause in a dynamic query using a variable? )
I usually combine PointToScreen
and PointToClient
:
Point locationOnForm = control.FindForm().PointToClient(
control.Parent.PointToScreen(control.Location));
function makeBreadCrumbs($separator = '/'){
//extract uri path parts into an array
$breadcrumbs = array_filter(explode('/',parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));
//determine the base url or domain
$base = (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/';
$last = end($breadcrumbs); //obtain the last piece of the path parts
$crumbs['Home'] = $base; //Our first crumb is the base url
$current = $crumbs['Home']; //set the current breadcrumb to base url
//create valid urls from the breadcrumbs and store them in an array
foreach ($breadcrumbs as $key => $piece) {
//ignore file names and create urls from directory path
if( strstr($last,'.php') == false){
$current = $current.$separator.$piece;
$crumbs[$piece] =$current;
}else{
if($piece !== $last){
$current = $current.$separator.$piece;
$crumbs[$piece] =$current;
}
}
}
$links = '';
$count = 0;
//create html tags for displaying the breadcrumbs
foreach ($crumbs as $key => $value) :
$x = array_filter(explode('/',parse_url($value, PHP_URL_PATH)));
$last = end($x);
//this will add a class to the last link to control its appearance
$clas = ($count === count($crumbs) -1 ? ' current-crumb' : '' );
//determine where to print separators
$sep = ( $count > -1 && $count < count($crumbs) -1 ? '»' :'');
$links .= "<a class=\"$clas\" href=\"$value\">$key</a> $sep";
$count++;
endforeach;
return $links;
}
I'm not sure why there are no answers to what the question is asking for. i.e. All tags (non-annotated included) and without the suffix:
git describe --tags --abbrev=0
Subtract from another date object
var d = new Date();
d.setHours(d.getHours() - 2);
In Oracle database we can achieve like this.
CREATE TABLE Student(
StudentID Number(38, 0) not null,
DepartmentID Number(38, 0) not null,
PRIMARY KEY (StudentID, DepartmentID)
);
In new jQuery 1.5 you can use:
$.ajax({
type: "GET",
url: "http://localhost:99000/Services.svc/ReturnPersons",
dataType: "jsonp",
success: readData(data),
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
})
You could use org.apache.commons.lang.ArrayUtils :
ArrayUtils.reverse(array)
For me the filename involved was appended with a querystring, which this function didn't like.
$path = 'path/to/my/file.js?v=2'
Solution was to chop that off first:
$path = preg_replace('/\?v=[\d]+$/', '', $path);
$fileTime = filemtime($path);
I also ran into this issue trying the Microsoft.ServiceModel.Samples.Calculator WCF sample. I am using IIS 5.1. I resolved it by ensuring that the website that was auto-generated (servicemodelsamples) was not an application. Right-click the folder, click "Properties" and click the "Create" button.
I Created this simple program to get HSV Codes in realtime
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
def nothing(x):
pass
# Creating a window for later use
cv2.namedWindow('result')
# Starting with 100's to prevent error while masking
h,s,v = 100,100,100
# Creating track bar
cv2.createTrackbar('h', 'result',0,179,nothing)
cv2.createTrackbar('s', 'result',0,255,nothing)
cv2.createTrackbar('v', 'result',0,255,nothing)
while(1):
_, frame = cap.read()
#converting to HSV
hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)
# get info from track bar and appy to result
h = cv2.getTrackbarPos('h','result')
s = cv2.getTrackbarPos('s','result')
v = cv2.getTrackbarPos('v','result')
# Normal masking algorithm
lower_blue = np.array([h,s,v])
upper_blue = np.array([180,255,255])
mask = cv2.inRange(hsv,lower_blue, upper_blue)
result = cv2.bitwise_and(frame,frame,mask = mask)
cv2.imshow('result',result)
k = cv2.waitKey(5) & 0xFF
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
You need to run this command in the top-level directory of a Selenium SVN repository checkout.
Another possible solution for you future searchers: (If your problem is not a mimetype issue.)
For some reason videos would not play on iPad unless i set the controls="true" flag.
Example: This worked for me on iPhone but not iPad.
<video loop autoplay width='100%' height='100%' src='//some_video.mp4' type='video/mp4'></video>
And this now works on both iPad and iPhone:
<video loop autoplay controls="true" width='100%' height='100%' src='//some_video.mp4' type='video/mp4'></video>
I did not find where the .rnd file is so I ran the cmd as administrator and it worked like a charm.
KJScompress
http://opensource.seznam.cz/KJScompress/index.html
Kjscompress/csskompress is set of two applications (kjscompress a csscompress) to remove non-significant whitespaces and comments from files containing JavaScript and CSS. Both are command-line applications for GNU/Linux operating system.
Suppose your data looks like this:
import pandas as pd
import numpy as np
np.random.seed(2015)
df = pd.DataFrame([])
for i in range(5):
data = dict(zip(np.random.choice(10, replace=False, size=5),
np.random.randint(10, size=5)))
data = pd.DataFrame(data.items())
data = data.transpose()
data.columns = data.iloc[0]
data = data.drop(data.index[[0]])
df = df.append(data)
print('{}\n'.format(df))
# 0 0 1 2 3 4 5 6 7 8 9
# 1 6 NaN NaN 8 5 NaN NaN 7 0 NaN
# 1 NaN 9 6 NaN 2 NaN 1 NaN NaN 2
# 1 NaN 2 2 1 2 NaN 1 NaN NaN NaN
# 1 6 NaN 6 NaN 4 4 0 NaN NaN NaN
# 1 NaN 9 NaN 9 NaN 7 1 9 NaN NaN
Then it could be replaced with
np.random.seed(2015)
data = []
for i in range(5):
data.append(dict(zip(np.random.choice(10, replace=False, size=5),
np.random.randint(10, size=5))))
df = pd.DataFrame(data)
print(df)
In other words, do not form a new DataFrame for each row. Instead, collect all the data in a list of dicts, and then call df = pd.DataFrame(data)
once at the end, outside the loop.
Each call to df.append
requires allocating space for a new DataFrame with one extra row, copying all the data from the original DataFrame into the new DataFrame, and then copying data into the new row. All that allocation and copying makes calling df.append
in a loop very inefficient. The time cost of copying grows quadratically with the number of rows. Not only is the call-DataFrame-once code easier to write, it's performance will be much better -- the time cost of copying grows linearly with the number of rows.
Your second solution is probably the most correct. You should use the HTTP spec and mimetypes the way they were intended and upload the file via multipart/form-data
. As far as handling the relationships, I'd use this process (keeping in mind I know zero about your assumptions or system design):
POST
to /users
to create the user entity.POST
the image to /images
, making sure to return a Location
header to where the image can be retrieved per the HTTP spec.PATCH
to /users/carPhoto
and assign it the ID of the photo given in the Location
header of step 2.Create custom TextWatcher subclass:
public class CustomWatcher implements TextWatcher {
private boolean mWasEdited = false;
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (mWasEdited){
mWasEdited = false;
return;
}
// get entered value (if required)
String enteredValue = s.toString();
String newValue = "new value";
// don't get trap into infinite loop
mWasEdited = true;
// just replace entered value with whatever you want
s.replace(0, s.length(), newValue);
}
}
Set listener for your EditText:
mTargetEditText.addTextChangedListener(new CustomWatcher());
I think Niklas has the right answer to your problem. Besides that, I think the following date validation function is a little bit easier to read:
// Validates that the input string is a valid date formatted as "mm/dd/yyyy"
function isValidDate(dateString)
{
// First check for the pattern
if(!/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dateString))
return false;
// Parse the date parts to integers
var parts = dateString.split("/");
var day = parseInt(parts[1], 10);
var month = parseInt(parts[0], 10);
var year = parseInt(parts[2], 10);
// Check the ranges of month and year
if(year < 1000 || year > 3000 || month == 0 || month > 12)
return false;
var monthLength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
// Adjust for leap years
if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
monthLength[1] = 29;
// Check the range of the day
return day > 0 && day <= monthLength[month - 1];
};
Based on my experience, even with python 3.3+, an empty __init__.py
is still needed sometimes. One situation is when you want to refer a subfolder as a package. For example, when I ran python -m test.foo
, it didn't work until I created an empty __init__.py
under the test folder. And I'm talking about 3.6.6 version here which is pretty recent.
Apart from that, even for reasons of compatibility with existing source code or project guidelines, its nice to have an empty __init__.py
in your package folder.
The command for listing all triggers is:
show triggers;
or you can access the INFORMATION_SCHEMA
table directly by:
select trigger_schema, trigger_name, action_statement
from information_schema.triggers
TRIGGERS
table is here.It is work, I hope help you
.btn:focus, .btn:focus:active {
outline: none;
}
I don't know why you want to do that, but try:
SELECT *
INTO NewTable
FROM OldTable
WHERE 1 = 2
It should work.
var arr_select_val=[];
$("select").each(function() {
var name=this.name;
arr_select_val[name]=$('select option:first-child').val();
});
// Process the array object
$('.orders_status_summary_div').print(arr_select_val);
In my case reload() doesn't work because the asp.net controls behavior. So, to solve this issue I've used this approach, despite seems a work around.
self.clear = function () {
//location.reload(true); Doesn't work to IE neither Firefox;
//also, hash tags must be removed or no postback will occur.
window.location.href = window.location.href.replace(/#.*$/, '');
};
Yet another approach is ISNULL().
UPDATE [DATABASE].[dbo].[TABLE_NAME]
SET
[ABC] = ISNULL(@ABC, [ABC]),
[ABCD] = ISNULL(@ABCD, [ABCD])
The difference between ISNULL and COALESCE is the return type. COALESCE can also take more than 2 arguments, and use the first that is not null. I.e.
select COALESCE(null, null, 1, 'two') --returns 1
select COALESCE(null, null, null, 'two') --returns 'two'
In the possibility that the second page doesn't have shared access to the session cookie, you'll need to set the session cookie path using session_set_cookie_params:
<?php
session_set_cookie_params( $lifetime, '/shared/path/to/files/' );
session_start();
$_SESSION['myvar']='myvalue';
And
<?php
session_set_cookie_params( $lifetime, '/shared/path/to/files/' );
session_start();
echo("1");
if(isset($_SESSION['myvar']))
{
echo("2");
if($_SESSION['myvar'] == 'myvalue')
{
echo("3");
exit;
}
}
Simply you can find index name and column names of a particular table using below command
SP_HELPINDEX 'tablename'
It work's for me
mylist = [1,2,3]
def multiple_appends(listname, *element):
listname.extend(element)
multiple_appends(mylist, 4, 5, "string", False)
print(mylist)
OUTPUT:
[1, 2, 3, 4, 5, 'string', False]
I periodically search for a satisfactory answer to this, but no luck so far. I use soapUI + requests + manual labour.
I gave up and used Java the last time I needed to do this, and simply gave up a few times the last time I wanted to do this, but it wasn't essential.
Having successfully used the requests library last year with Project Place's RESTful API, it occurred to me that maybe I could just hand-roll the SOAP requests I want to send in a similar way.
Turns out that's not too difficult, but it is time consuming and prone to error, especially if fields are inconsistently named (the one I'm currently working on today has 'jobId', JobId' and 'JobID'. I use soapUI to load the WSDL to make it easier to extract endpoints etc and perform some manual testing. So far I've been lucky not to have been affected by changes to any WSDL that I'm using.
Just convert it to int
:
char registered = '®';
int code = (int) registered;
In fact there's an implicit conversion from char
to int
so you don't have to specify it explicitly as I've done above, but I would do so in this case to make it obvious what you're trying to do.
This will give the UTF-16 code unit - which is the same as the Unicode code point for any character defined in the Basic Multilingual Plane. (And only BMP characters can be represented as char
values in Java.) As Andrzej Doyle's answer says, if you want the Unicode code point from an arbitrary string, use Character.codePointAt()
.
Once you've got the UTF-16 code unit or Unicode code points, but of which are integers, it's up to you what you do with them. If you want a string representation, you need to decide exactly what kind of representation you want. (For example, if you know the value will always be in the BMP, you might want a fixed 4-digit hex representation prefixed with U+
, e.g. "U+0020"
for space.) That's beyond the scope of this question though, as we don't know what the requirements are.
You just need to create your own class inherited from parent. Place an ImageView on that, and on the mousedown and mouse up events just change the images of the ImageView.
public class ImageButton extends Parent {
private static final Image NORMAL_IMAGE = ...;
private static final Image PRESSED_IMAGE = ...;
private final ImageView iv;
public ImageButton() {
this.iv = new ImageView(NORMAL_IMAGE);
this.getChildren().add(this.iv);
this.iv.setOnMousePressed(new EventHandler<MouseEvent>() {
public void handle(MouseEvent evt) {
iv.setImage(PRESSED_IMAGE);
}
});
// TODO other event handlers like mouse up
}
}
Backticks enclose template literals, previously known as template strings. Template literals are string literals that allow embedded expressions and string interpolation features.
Template literals have expressions embedded in placeholders, denoted by the dollar sign and curly brackets around an expression, i.e. ${expression}
. The placeholder / expressions get passed to a function. The default function just concatenates the string.
To escape a backtick, put a backslash before it:
`\`` === '`'; => true
Use backticks to more easily write multi-line string:
console.log(`string text line 1
string text line 2`);
or
console.log(`Fifteen is ${a + b} and
not ${2 * a + b}.`);
vs. vanilla JavaScript:
console.log('string text line 1\n' +
'string text line 2');
or
console.log('Fifteen is ' + (a + b) + ' and\nnot ' + (2 * a + b) + '.');
Escape sequences:
\u
, for example \u00A9
\u{}
, for example \u{2F804}
\x
, for example \xA9
\
and (a) digit(s), for example \251
First give your input type submit a name, like this name='submitform'
.
and then put this in your php file
if (isset($_POST['submitform']))
{
?>
<script type="text/javascript">
window.location = "http://www.google.com/";
</script>
<?php
}
Don't forget to change the url to yours.
I use this in my utils library (Swift 4.2):
public class PrintTimer {
let start = Date()
let name: String
public init(file: String=#file, line: Int=#line, function: String=#function, name: String?=nil) {
let file = file.split(separator: "/").last!
self.name = name ?? "\(file):\(line) - \(function)"
}
public func done() {
let end = Date()
print("\(self.name) took \((end.timeIntervalSinceReferenceDate - self.start.timeIntervalSinceReferenceDate).roundToSigFigs(5)) s.")
}
}
... then call in a method like:
func myFunctionCall() {
let timer = PrintTimer()
// ...
timer.done()
}
... which in turn looks like this in the console after running:
MyFile.swift:225 - myFunctionCall() took 1.8623 s.
Not as concise as TICK/TOCK above, but it is clear enough to see what it is doing and automatically includes what is being timed (by file, line at the start of the method, and function name). Obviously if I wanted more detail (ex, if I'm not just timing a method call as is the usual case but instead am timing a block within that method) I can add the "name="Foo"" parameter on the PrintTimer init to name it something besides the defaults.
For Saturday and Sunday You can do something like this
$('#orderdate').datepicker({
daysOfWeekDisabled: [0,6]
});
Much more simple: Right click -> Refactor -> Move.
Set content-type and other headers before you write the file out. For small files the content is buffered, and the browser gets the headers first. For big ones the data come first.
You can use http_response_code()
to set HTTP response code.
If you pass no parameters then http_response_code will get the current status code. If you pass a parameter it will set the response code.
http_response_code(201); // Set response status code to 201
For Laravel(Reference from: https://stackoverflow.com/a/14717895/2025923):
return Response::json([
'hello' => $value
], 201); // Status code here
In openCV's documentation there is an example for getting video frame by frame. It is written in c++ but it is very easy to port the example to python - you can search for each fumction documentation to see how to call them in python.
#include "opencv2/opencv.hpp"
using namespace cv;
int main(int, char**)
{
VideoCapture cap(0); // open the default camera
if(!cap.isOpened()) // check if we succeeded
return -1;
Mat edges;
namedWindow("edges",1);
for(;;)
{
Mat frame;
cap >> frame; // get a new frame from camera
cvtColor(frame, edges, CV_BGR2GRAY);
GaussianBlur(edges, edges, Size(7,7), 1.5, 1.5);
Canny(edges, edges, 0, 30, 3);
imshow("edges", edges);
if(waitKey(30) >= 0) break;
}
// the camera will be deinitialized automatically in VideoCapture destructor
return 0;
}
There is also Mappa - http://mappatool.com/.
It only supports polygons, but they are definitely the hardest parts :)
It is better to rely on regexps like ^[^0-9]+$
rather than on regexps like [a-zA-Z]+
as your app may one day accept user inputs from users speaking language like Polish, where many more characters should be accepted rather than only [a-zA-Z]+
. Using ^[^0-9]+$
easily rules out any such undesired side effects.
This is work for my project, source https://gist.github.com/artem-zinnatullin/7749076
Create fonts directory inside Asset Folder and then copy your custom font to fonts directory, example I am using trebuchet.ttf;
Create a class TypefaceUtil.java;
import android.content.Context;
import android.graphics.Typeface;
import android.util.Log;
import java.lang.reflect.Field;
public class TypefaceUtil {
public static void overrideFont(Context context, String defaultFontNameToOverride, String customFontFileNameInAssets) {
try {
final Typeface customFontTypeface = Typeface.createFromAsset(context.getAssets(), customFontFileNameInAssets);
final Field defaultFontTypefaceField = Typeface.class.getDeclaredField(defaultFontNameToOverride);
defaultFontTypefaceField.setAccessible(true);
defaultFontTypefaceField.set(null, customFontTypeface);
} catch (Exception e) {
}
}
}
Edit theme in styles.xml add below
<item name="android:typeface">serif</item>
Example in My styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:typeface">serif</item><!-- Add here -->
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:windowActionBarOverlay">true</item>
<item name="android:windowFullscreen">true</item>
</style>
</resources>
Finally, in Activity or Fragment onCreate call TypefaceUtil.java
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TypefaceUtil.overrideFont(getContext(), "SERIF", "fonts/trebuchet.ttf");
}
A modulable version with JQuery, add this at the end of your file:
<script>
$(function() {
$('img[data-src-error]').error(function() {
var o = $(this);
var errorSrc = o.attr('data-src-error');
if (o.attr('src') != errorSrc) {
o.attr('src', errorSrc);
}
});
});
</script>
and on your img
tag:
<img src="..." data-src-error="..." />
There are a few base64 encoders online to help you with this, this is probably the best I've seen:
http://www.greywyvern.com/code/php/binary2base64
As that page shows your main options for this are CSS:
div.image {
width:100px;
height:100px;
background-image:url(data:image/png;base64,iVBORwA<MoreBase64SringHere>);
}
Or the <img>
tag itself, like this:
<img alt="My Image" src="data:image/png;base64,iVBORwA<MoreBase64SringHere>" />
$("input").click(function(){
var name = $(this).attr("name");
$('input[name="' + name + '"]').hide();
});
Also works with ID:
var id = $(this).attr("id");
$('input[id="' + id + '"]').hide();
when, (sometimes)
$('input#' + id).hide();
does not work, as it should.
You can even do both:
$('input[name="' + name + '"][id="' + id + '"]').hide();
Sometimes it is helpful to avoid creating a compile-time dependency between two view controllers. Here's how you can do it without caring about the type of the destination view controller:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.destinationViewController respondsToSelector:@selector(setMyData:)]) {
[segue.destinationViewController performSelector:@selector(setMyData:)
withObject:myData];
}
}
So as long as your destination view controller declares a public property, e.g.:
@property (nonatomic, strong) MyData *myData;
you can set this property in the previous view controller as I described above.
Wrote a little function myself.Simpler Using Lists
public static boolean checkVersionUpdate(String olderVerison, String newVersion) {
if (olderVerison.length() == 0 || newVersion.length() == 0) {
return false;
}
List<String> newVerList = Arrays.asList(newVersion.split("\\."));
List<String> oldVerList = Arrays.asList(olderVerison.split("\\."));
int diff = newVerList.size() - oldVerList.size();
List<String> newList = new ArrayList<>();
if (diff > 0) {
newList.addAll(oldVerList);
for (int i = 0; i < diff; i++) {
newList.add("0");
}
return examineArray(newList, newVerList, diff);
} else if (diff < 0) {
newList.addAll(newVerList);
for (int i = 0; i < -diff; i++) {
newList.add("0");
}
return examineArray(oldVerList, newList, diff);
} else {
return examineArray(oldVerList, newVerList, diff);
}
}
public static boolean examineArray(List<String> oldList, List<String> newList, int diff) {
boolean newVersionGreater = false;
for (int i = 0; i < oldList.size(); i++) {
if (Integer.parseInt(newList.get(i)) > Integer.parseInt(oldList.get(i))) {
newVersionGreater = true;
break;
} else if (Integer.parseInt(newList.get(i)) < Integer.parseInt(oldList.get(i))) {
newVersionGreater = false;
break;
} else {
newVersionGreater = diff > 0;
}
}
return newVersionGreater;
}
You can use a $where. Just be aware it will be fairly slow (has to execute Javascript code on every record) so combine with indexed queries if you can.
db.T.find( { $where: function() { return this.Grade1 > this.Grade2 } } );
or more compact:
db.T.find( { $where : "this.Grade1 > this.Grade2" } );
you can use $expr
as described in recent answer
Put the table in a div and give that div the class pre-scrollable
.
I have python 3.5 with anaconda. First I tried everything given above but it did not work for me on windows 10 64bit. So I simply tried:-
If you just have one version, then type in cmd:
C:/>conda install tensorflow
for multiple versions of python, type in cmd:
C:/>conda install tensorflow python=version(e.g.python=3.5)
It works, just give it a try.
After installation open ipython console and import tensorflow:
import tensorflow
If tensorflow installed properly then you are ready to go. Enjoy machine learning:-)
If you use relative links to images then the images won't display as all folder structures are not preserved after the iOS app is compiled. What you can do is convert your local web folder into a bundle instead by adding the '.bundle' filename extension.
So if you local website is contained in a folder "www", this should be renamed to "www.bundle". This allows the image folders and directory structure to be preserved. Then load the 'index.html' file into the WebView as an HTML string with 'baseURL' (set to www.bundle path) to enable loading relative image links.
NSString *mainBundlePath = [[NSBundle mainBundle] resourcePath];
NSString *wwwBundlePath = [mainBundlePath stringByAppendingPathComponent:@"www.bundle"];
NSBundle *wwwBundle = [NSBundle bundleWithPath:wwwBundlePath];
if (wwwBundle != nil) {
NSURL *baseURL = [NSURL fileURLWithPath:[wwwBundle bundlePath]];
NSError *error = nil;
NSString *page = [[NSBundle mainBundle] pathForResource:@"index.html" ofType:nil];
NSString *pageSource = [NSString stringWithContentsOfFile:page encoding:NSUTF8StringEncoding error:&error];
[self.webView loadHTMLString:pageSource baseURL:baseURL];
}
function hasDuplicate($array){
$d = array();
foreach($array as $elements) {
if(!isset($d[$elements])){
$d[$elements] = 1;
}else{
return true;
}
}
return false;
}
There is a package called eclipse-cdt
in the Ubuntu 12.10 repositories, this is what you want. If you haven't got g++
already, you need to install that as well, so all you need is:
sudo apt-get install eclipse eclipse-cdt g++
Whether you messed up your system with your previous installation attempts depends heavily on how you did it. If you did it the safe way for trying out new packages not from repositories (i.e., only installed in your home folder, no sudo
s blindly copied from installation manuals...) you're definitely fine. Otherwise, you may well have thousands of stray files all over your file system now. In that case, run all uninstall scripts you can find for the things you installed, then install using apt-get
and hope for the best.
Your problem is here:
2013-11-14 17:57:20 5180 [ERROR] InnoDB: .\ibdata1 can't be opened in read-write mode
There's some problem with the ibdata1 file - maybe the permissions have changed on it? Perhaps some other process has it open. Does it even exist?
Fix this and possibly everything else will fall into place.
If you'd like to initialize the array to values other than 0, with gcc
you can do:
int array[1024] = { [ 0 ... 1023 ] = -1 };
This is a GNU extension of C99 Designated Initializers. In older GCC, you may need to use -std=gnu99
to compile your code.
You can stub a static void method like this:
PowerMockito.doNothing().when(StaticResource.class, "getResource", anyString());
Although I'm not sure why you would bother, because when you call mockStatic(StaticResource.class) all static methods in StaticResource are by default stubbed
More useful, you can capture the value passed to StaticResource.getResource() like this:
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
PowerMockito.doNothing().when(
StaticResource.class, "getResource", captor.capture());
Then you can evaluate the String that was passed to StaticResource.getResource like this:
String resourceName = captor.getValue();
RichTextBox will allow you to use html to specify the color. Another alternative is using a listbox and using the DrawItem event to draw how you would like. AFAIK, textbox itself can't be used in the way you're hoping.
Thanks Marcelo. This worked for me. I wanted to open a new IE Window and open two tabs in that so I modified the code:
start iexplore.exe website
PING 1.1.1.1 -n 1 -w 2000 >NUL
START /d iexplore.exe website
CASE WHEN last_name IS NULL THEN '' ELSE ' '+last_name END
This gets part way there. There is no ActualFontSize property but there is an ActualHeight and that would relate to the FontSize. Right now this only sizes for the original render. I could not figure out how to register the Converter as resize event. Actually maybe need to register the FontSize as a resize event. Please don't mark me down for an incomplete answer. I could not put code sample in a comment.
<Window.Resources>
<local:WidthConverter x:Key="widthConverter"/>
</Window.Resources>
<Grid>
<Grid>
<StackPanel VerticalAlignment="Center" Orientation="Vertical" >
<Viewbox Margin="100,0,100,0">
<TextBlock x:Name="headerText" Text="Lorem ipsum dolor" Foreground="Black"/>
</Viewbox>
<TextBlock Margin="150,0,150,0" FontSize="{Binding ElementName=headerText, Path=ActualHeight, Converter={StaticResource widthConverter}}" x:Name="subHeaderText" Text="Lorem ipsum dolor, Lorem ipsum dolor, lorem isum dolor, Lorem ipsum dolor, Lorem ipsum dolor, lorem isum dolor, " TextWrapping="Wrap" Foreground="Gray" />
</StackPanel>
</Grid>
</Grid>
Converter
[ValueConversion(typeof(double), typeof(double))]
public class WidthConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
double width = (double)value*.7;
return width; // columnsCount;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Do you just want to know how to write a line to a file? First, you need to open the file:
f = open("filename.txt", 'w')
Then, you need to write the string to the file:
f.write("dict = {'one': 1, 'two': 2}" + '\n')
You can repeat this for each line (the +'\n'
adds a newline if you want it).
Finally, you need to close the file:
f.close()
You can also be slightly more clever and use with
:
with open("filename.txt", 'w') as f:
f.write("dict = {'one': 1, 'two': 2}" + '\n')
### repeat for all desired lines
This will automatically close the file, even if exceptions are raised.
But I suspect this is not what you are asking...
I am using this script after I rename my iOS Project. It helps to change the directories name and make the names in sync.
NOTE: you will need to manually change the scheme's name.
I tried Atom and it looks really nice BUT there is one major problem (at least in v 0.84):
It doesn't support vertical select Alt+Drag - this is a must for every modern code editor.
You can have multiple CSS declarations for the same properties by separating them with commas:
.abc, .xyz {
margin-left: 20px;
}
Fragment fr = new Fragment_class();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.add(R.id.viewpagerId, fr);
fragmentTransaction.commit();
Just to be precise, R.id.viewpagerId
is cretaed in your current class layout, upon calling, the new fragment automatically gets infiltrated.
Another trick is to use
.class {
position: absolute;
visibility:hidden;
display:none;
}
This is not likely to mess up your flow (because it takes it out of flow) and makes sure that the user can't see it, and then if display:none
works later on it will be working. Keep in mind that visibility:hidden
may not remove it from screen readers.
Use:
SELECT *
FROM YOUR_TABLE
WHERE creation_date <= TRUNC(SYSDATE) - 30
SYSDATE returns the date & time; TRUNC resets the date to being as of midnight so you can omit it if you want the creation_date
that is 30 days previous including the current time.
Depending on your needs, you could also look at using ADD_MONTHS:
SELECT *
FROM YOUR_TABLE
WHERE creation_date <= ADD_MONTHS(TRUNC(SYSDATE), -1)
The answer from @plaisthos broke in the latest gradle version, but there is still a way to do it.
Create a native-libs
directory in the root of your project directory and copy all y our libs into this directory.
Add the following lines to your build.gradle. Build and be happy.
task copyNativeLibs(type: Copy) {
from(new File(project(':<your project>').getProjectDir(), 'native-libs')) { include '**/*.so' }
into new File(buildDir, 'native-libs')
}
tasks.withType(Compile) { compileTask -> compileTask.dependsOn copyNativeLibs }
clean.dependsOn 'cleanCopyNativeLibs'
Add this permission in Manifest
,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
File folder = new File(Environment.getExternalStorageDirectory() +
File.separator + "TollCulator");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
// Do something on success
} else {
// Do something else on failure
}
when u run the application go too DDMS->File Explorer->mnt folder->sdcard folder->toll-creation folder
Another good way of dealing with Lion's hidden scroll bars is to display a prompt to scroll down. It doesn't work with small scroll areas such as text fields but well with large scroll areas and keeps the overall style of the site. One site doing this is http://versusio.com, just check this example page and wait 1.5 seconds to see the prompt:
http://versusio.com/en/samsung-galaxy-nexus-32gb-vs-apple-iphone-4s-64gb
The implementation isn't hard but you have to take care, that you don't display the prompt when the user has already scrolled.
You need jQuery + Underscore and
$(window).scroll
to check if the user already scrolled by himself,
_.delay()
to trigger a delay before you display the prompt -- the prompt shouldn't be to obtrusive
$('#prompt_div').fadeIn('slow')
to fade in your prompt and of course
$('#prompt_div').fadeOut('slow')
to fade out when the user scrolled after he saw the prompt
In addition, you can bind Google Analytics events to track user's scrolling behavior.
Not so hard:
#include <thread>
void Test::runMultiThread()
{
std::thread t1(&Test::calculate, this, 0, 10);
std::thread t2(&Test::calculate, this, 11, 20);
t1.join();
t2.join();
}
If the result of the computation is still needed, use a future instead:
#include <future>
void Test::runMultiThread()
{
auto f1 = std::async(&Test::calculate, this, 0, 10);
auto f2 = std::async(&Test::calculate, this, 11, 20);
auto res1 = f1.get();
auto res2 = f2.get();
}
You can set its before
and after
to force a constant width-to-height ratio
HTML:
<div class="squared"></div>
CSS:
.squared {
background: #333;
width: 300px;
}
.squared::before {
content: '';
padding-top: 100%;
float: left;
}
.squared::after {
content: '';
display: block;
clear: both;
}
function Vcount() {
var modify = document.getElementById("C_name1").value;
var oTable = document.getElementById('dataTable');
var i;
var rowLength = oTable.rows.length;
for (i = 1; i < rowLength; i++) {
var oCells = oTable.rows.item(i).cells;
if (modify == oCells[0].firstChild.data) {
document.getElementById("Error").innerHTML = " * duplicate value";
return false;
break;
}
}
"Vanilla JS” is an expression that got popular after the publishing of a satire website in 2012 (http://vanilla-js.com/). There’s a section covering its story/meaning in this post.
So why the joke? It kind of came as a modern response to the old school knee-jerk reflex of relying on jQuery and additional JS libraries. With the ECMAScript spec and modern browsers capabilities, the need to bypass plain JS with external libraries to maintain consistency across browsers just isn’t there anymore. Here’s a site that shows you how true this is with concrete examples: http://youmightnotneedjquery.com/
Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.
So, first build a list, then use pickle.dump
to send it to a file...
Python 3.4.1 (default, May 21 2014, 12:39:51)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>
>>> import pickle
>>>
>>> with open('parrot.pkl', 'wb') as f:
... pickle.dump(mylist, f)
...
>>>
Then quit and come back later… and open with pickle.load
...
Python 3.4.1 (default, May 21 2014, 12:39:51)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
... mynewlist = pickle.load(f)
...
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>
In Netbeans 11(Gladle Project) follow these steps:
In the tab files>yourprojectname>
double click in the file "build.gladle"
than set in line "mainClassName:'yourpackagepath.YourMainClass'"
Hope this helps!
MozWebSocket
MozWebSocket
Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.
See caniuse for the current status of WebSockets support in desktop and mobile browsers.
See the test reports from the WS testsuite included in Autobahn WebSockets for feature/protocol conformance tests.
It depends on which language you use.
In Java/Java EE:
V 7.5 supports RFC6455
- Jetty 9.1 supports javax.websocket / JSR 356)V 3.1.2 supports RFC6455
V 4.0.25 supports RFC6455
V 7.0.28 supports RFC6455
Some other Java implementations:
V 5.6 supports RFC6455
V 2.10 supports RFC6455
In C#:
In PHP:
In Python:
In C:
In Node.js:
Vert.x (also known as Node.x) : A node like polyglot implementation running on a Java 7 JVM and based on Netty with :
Pusher.com is a Websocket cloud service accessible through a REST API.
DotCloud cloud platform supports Websockets, and Java (Jetty Servlet Container), NodeJS, Python, Ruby, PHP and Perl programming languages.
Openshift cloud platform supports websockets, and Java (Jboss, Spring, Tomcat & Vertx), PHP (ZendServer & CodeIgniter), Ruby (ROR), Node.js, Python (Django & Flask) plateforms.
For other language implementations, see the Wikipedia article for more information.
The RFC for Websockets : RFC6455
Edit: This is out of date, see @Merlin's answer.
[False]
, being a nonempty list, is not the same as False
. You should write:
test = df.sort('one', ascending=False)
Just use preg_replace()
$string = preg_replace('~[\r\n]+~', '', $string);
You could get away with str_replace()
on this one, although the code doesn't look as clean:
$string = str_replace(array("\n", "\r"), '', $string);
See it live on ideone
You can use the extra arguments to setTimeout to pass parameters to the callback function.
for (var i = 1; i <= 2; i++) {
setTimeout(function(j) { alert(j) }, 100, i);
}
Note: This doesn't work on IE9 and below browsers.
To avoid freezing when you call a function somewhere down the call stack that tries to re-join the current thread (which is stuck in a Wait), you need to do the following:
class Program
{
static void Main(string[] args)
{
Bootstrapper bs = new Bootstrapper();
List<TvChannel> list = Task.Run((Func<Task<List<TvChannel>>>)bs.GetList).Result;
}
}
(the cast is only required to resolve ambiguity)
You can change the size of the plot by adding this before you create the figure.
plt.rcParams["figure.figsize"] = [16,9]
There's another post here. Try looking at this.
BTW, you're looking for the .lower()
method:
string1 = "hi"
string2 = "HI"
if string1.lower() == string2.lower():
print "Equals!"
else:
print "Different!"
Go with range for these reasons:
1) xrange will be going away in newer Python versions. This gives you easy future compatibility.
2) range will take on the efficiencies associated with xrange.
Complementing Elmer's answer, as my edit was rolled back.
To cache static content for 365 days with public cache-control header, IIS can be configured with the following
<staticContent>
<clientCache cacheControlCustom="public" cacheControlMode="UseMaxAge" cacheControlMaxAge="365.00:00:00" />
</staticContent>
This will translate into a header like this:
Cache-Control: public,max-age=31536000
Note that max-age is a delta in seconds, being expressed by a positive 32bit integer as stated in RFC 2616 Sections 14.9.3 and 14.9.4. This represents a maximum value of 2^31 or 2,147,483,648 seconds (over 68 years). However, to better ensure compatibility between clients and servers, we adopt a recommended maximum of 365 days (one year).
As mentioned on other answers, you can use these directives also on the web.config of your site for all static content. As an alternative, you can use it only for contents in a specific location too (on the sample, 30 days public cache for contents in "cdn" folder):
<location path="cdn">
<system.webServer>
<staticContent>
<clientCache cacheControlCustom="public" cacheControlMode="UseMaxAge" cacheControlMaxAge="30.00:00:00"/>
</staticContent>
</system.webServer>
</location>
Use the keyword super within the overridden method in the child class to use the parent class method. You can only use the keyword within the overridden method though. The example below will help.
public class Parent {
public int add(int m, int n){
return m+n;
}
}
public class Child extends Parent{
public int add(int m,int n,int o){
return super.add(super.add(m, n),0);
}
}
public class SimpleInheritanceTest {
public static void main(String[] a){
Child child = new Child();
child.add(10, 11);
}
}
The add
method in the Child class calls super.add
to reuse the addition logic.
This happened to me because I was using a Tomcat 5.5 catalina.sh
file with a Tomcat 7 installation. Using the catalina.sh
that came with the Tomcat 7 install fixed the problem.
The auto_increment
property only works for numeric columns (integer and floating point), not char
columns:
CREATE TABLE discussion_topics (
topic_id INT NOT NULL AUTO_INCREMENT,
project_id char(36) NOT NULL,
topic_subject VARCHAR(255) NOT NULL,
topic_content TEXT default NULL,
date_created DATETIME NOT NULL,
date_last_post DATETIME NOT NULL,
created_by_user_id char(36) NOT NULL,
last_post_user_id char(36) NOT NULL,
posts_count char(36) default NULL,
PRIMARY KEY (topic_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
Creating a resource is generally mapped to POST, and that should return the location of the new resource; for example, in a Rails scaffold a CREATE will redirect to the SHOW for the newly created resource. The same approach might make sense for updating (PUT), but that's less of a convention; an update need only indicate success. A delete probably only needs to indicate success as well; if you wanted to redirect, returning the LIST of resources probably makes the most sense.
Success can be indicated by HTTP_OK, yes.
The only hard-and-fast rule in what I've said above is that a CREATE should return the location of the new resource. That seems like a no-brainer to me; it makes perfect sense that the client will need to be able to access the new item.
There's an alternative approach to this:
#include <iterator>
#include <algorithm>
// ...
copy(istream_iterator<int>(iFile), istream_iterator<int>(),
ostream_iterator<int>(cerr, "\n"));
I cross that situation by replacing all androidx.*
to appropiate package name
.
change your line
implementation 'androidx.appcompat:appcompat:1.0.0-alpha3'
implementation 'androidx.constraintlayout:constraintlayout:1.1.1'
androidTestImplementation 'androidx.test:runner:1.1.0-alpha3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha3'
to
implementation 'com.android.support:appcompat-v7:28.0.0-alpha3'
implementation 'com.android.support.constraint:constraint-layout:1.1.1'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
NOTED
tools:replace="android:appComponentFactory"
from AndroidManifestI had the same problem. The problem sit in the Excel Source task. When you setup this task the first time, the task will connect to the specified Excel file (via the Excel connection) and decide what type each column is based on the current spreadsheet.
Thus, if you set up the Excel Source task, just make sure that the columns that should be text only has text in the column. This means that the Excel Source task will always assume that any subsequent spreadsheets will have the same format and will read 12345 as text because the column was text when the task was set up.
Hope it makes sense!
Keep the first 19 characters that you wanted via slicing:
>>> str(datetime.datetime.now())[:19]
'2011-11-03 14:37:50'
Working code:
addresses = geocoder.getFromLocation(mMap.getCameraPosition().target.latitude, mMap.getCameraPosition().target.longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
String locality = addresses.get(0).getLocality(); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String subLocality = addresses.get(0).getSubLocality(); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
//String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String address1 = addresses.get(0).getAddressLine(1); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String address2 = addresses.get(0).getAddressLine(2); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
// String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();
If unplugging the device and plugging it back in doesn't work, try increasing the upload timeout to something really huge like 20000 ms. It's at Window ? Preferences ? Android ? DDMS ? "ADB connection time out (ms)".
Revisit all your queries, maybe you have some query that select without ROWLOCK/FOR UPDATE hint from the same table you have SELECT FOR UPDATE.
MSSQL often escalates those row locks to page-level locks (even table-level locks, if you don't have index on field you are querying), see this explanation. Since you ask for FOR UPDATE, i could assume that you need transacion-level(e.g. financial, inventory, etc) robustness. So the advice on that site is not applicable to your problem. It's just an insight why MSSQL escalates locks.
If you are already using MSSQL 2005(and up), they are MVCC-based, i think you should have no problem with row-level lock using ROWLOCK/UPDLOCK hint. But if you are already using MSSQL 2005 and up, try to check some of your queries which query the same table you want to FOR UPDATE if they escalate locks by checking the fields on their WHERE clause if they have index.
P.S.
I'm using PostgreSQL, it also uses MVCC have FOR UPDATE, i don't encounter same problem. Lock escalations is what MVCC solves, so i would be surprised if MSSQL 2005 still escalate locks on table with WHERE clauses that doesn't have index on its fields. If that(lock escalation) is still the case for MSSQL 2005, try to check the fields on WHERE clauses if they have index.
Disclaimer: my last use of MSSQL is version 2000 only.
You use something like
from flask import send_file
@app.route('/get_image')
def get_image():
if request.args.get('type') == '1':
filename = 'ok.gif'
else:
filename = 'error.gif'
return send_file(filename, mimetype='image/gif')
to send back ok.gif
or error.gif
, depending on the type query parameter. See the documentation for the send_file
function and the request
object for more information.
You have to add repositories
to your build file. For maven repositories you have to prefix repository name with maven{}
repositories {
maven { url "http://maven.springframework.org/release" }
maven { url "http://maven.restlet.org" }
mavenCentral()
}
A[A==NDV]=numpy.nan
A==NDV will produce a boolean array that can be used as an index for A
Have tried this on a Windows machine and it works
If you wanna install opencv for python version 3.7, heres how you do it!
py -3.7 -m pip install opencv-python
make sure that you have set the image to Image property, but not to the Background
According to Yashu's instructions, I wrote the following function (it's PL/SQL code, but it should be easily adaptable to any other language).
FUNCTION field(str IN VARCHAR2) RETURN VARCHAR2 IS
C_NEWLINE CONSTANT CHAR(1) := '
'; -- newline is intentional
v_aux VARCHAR2(32000);
v_has_double_quotes BOOLEAN;
v_has_comma BOOLEAN;
v_has_newline BOOLEAN;
BEGIN
v_has_double_quotes := instr(str, '"') > 0;
v_has_comma := instr(str,',') > 0;
v_has_newline := instr(str, C_NEWLINE) > 0;
IF v_has_double_quotes OR v_has_comma OR v_has_newline THEN
IF v_has_double_quotes THEN
v_aux := replace(str,'"','""');
ELSE
v_aux := str;
END IF;
return '"'||v_aux||'"';
ELSE
return str;
END IF;
END;
If your rotation angles are fairly uniform, you can use CSS:
<img id="image_canv" src="/image.png" class="rotate90">
CSS:
.rotate90 {
-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-o-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
}
Otherwise, you can do this by setting a data attribute in your HTML, then using Javascript to add the necessary styling:
<img id="image_canv" src="/image.png" data-rotate="90">
Sample jQuery:
$('img').each(function() {
var deg = $(this).data('rotate') || 0;
var rotate = 'rotate(' + deg + 'deg)';
$(this).css({
'-webkit-transform': rotate,
'-moz-transform': rotate,
'-o-transform': rotate,
'-ms-transform': rotate,
'transform': rotate
});
});
Demo:
Try this :
`CREATE TABLE new-table (id INT(11) auto_increment primary key) SELECT old-table.name, old-table.group, old-table.floor, old-table.age from old-table;`
I selected 4 columns from old-table and made a new table.
Make the outer loop a while loop, and "Exit While" in the if statement.
file_put_contents('file.txt', 'bar');
echo file_get_contents('file.txt'); // bar
file_put_contents('file.txt', 'foo');
echo file_get_contents('file.txt'); // foo
Alternatively, if you're stuck with fopen()
you can use the w
or w+
modes:
'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
'w+' Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
Give the buttons a value attribute and then retrieve the values using this:
$("button").click(function(){
var value=$(this).attr("value");
});
Pushing and popping registers are behind the scenes equivalent to this:
push reg <= same as => sub $8,%rsp # subtract 8 from rsp
mov reg,(%rsp) # store, using rsp as the address
pop reg <= same as=> mov (%rsp),reg # load, using rsp as the address
add $8,%rsp # add 8 to the rsp
Note this is x86-64 At&t syntax.
Used as a pair, this lets you save a register on the stack and restore it later. There are other uses, too.
the most effective method is to use org.apache.http.entity.mime.MultipartEntity;
see this code from the link using org.apache.http.entity.mime.MultipartEntity;
public class SimplePostRequestTest3 {
/**
* @param args
*/
public static void main(String[] args) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost:8080/HTTP_TEST_APP/index.jsp");
try {
FileBody bin = new FileBody(new File("C:/ABC.txt"));
StringBody comment = new StringBody("BETHECODER HttpClient Tutorials");
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("fileup0", bin);
reqEntity.addPart("fileup1", comment);
reqEntity.addPart("ONE", new StringBody("11111111"));
reqEntity.addPart("TWO", new StringBody("222222222"));
httppost.setEntity(reqEntity);
System.out.println("Requesting : " + httppost.getRequestLine());
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost, responseHandler);
System.out.println("responseBody : " + responseBody);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpclient.getConnectionManager().shutdown();
}
}
}
This is badly formed HTML. You need to either have a single id or space separated classes. Either way if you're new I'd look into jQuery.
<div id="sub1">some text</div>
or
<div class="sub1 sub2 sub3">some text</div>
If you had the following HTML:
<div id="sub1">some text</div>
<div id="welcome" style="display:none;">Some welcome message</div>
$(document).ready(function() {
$('#sub1').hover(
function() { $('#welcome').show(); },
function() { $('#welcome').hide(); }
);
});
you'd probably want to include the events on your html:
<div id="sub1" onmouseover="showWelcome();" onmouseout="hideWelcome();">some text</div>
then your javascript would have these two functions
function showWelcome()
{
var welcome = document.getElementById('welcome');
welcome.style.display = 'block';
}
function hideWelcome()
{
var welcome = document.getElementById('welcome');
welcome.style.display = 'none';
}
Please note: this javascript doesn't take cross browser issues into consideration. for this you'd need to elaborate on your code, just another reason to use jquery.
<input type="checkbox" name="check_list[<? echo $row['Report ID'] ?>]" value="<? echo $row['Report ID'] ?>">
And after the post, you can loop through them:
if(!empty($_POST['check_list'])){
foreach($_POST['check_list'] as $report_id){
echo "$report_id was checked! ";
}
}
Or get a certain value posted from previous page:
if(isset($_POST['check_list'][$report_id])){
echo $report_id . " was checked!<br/>";
}
As of today, your best bet is to use:
img = cv2.imread(image_path) # reads an image in the BGR format
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # BGR -> RGB
You'll see img
will be a numpy array of type:
<class 'numpy.ndarray'>
This can be done without regex
which is more efficient:
var questionText = "1 ding ?"
var index = 0;
var num = "";
do
{
num += questionText[index];
} while (questionText[++index] >= "0" && questionText[index] <= "9");
questionText = questionText.substring(num.length);
And as a bonus, it also stores the number, which may be useful to some people.
Best answer doesn't work for me. I needed ssh://
from the beggining.
# does not work
git remote set-url origin [email protected]:10000/aaa/bbbb/ccc.git
# work
git remote set-url origin ssh://[email protected]:10000/aaa/bbbb/ccc.git
In addition to @Dan Herbert's answer , You we should encode just the values generally.
Split has params parameter Split('&','='); expression firstly split by & then '=' so odd elements are all values to be encoded shown below.
public static void EncodeQueryString(ref string queryString)
{
var array=queryString.Split('&','=');
for (int i = 0; i < array.Length; i++) {
string part=array[i];
if(i%2==1)
{
part=System.Web.HttpUtility.UrlEncode(array[i]);
queryString=queryString.Replace(array[i],part);
}
}
}
I have written a quick example to demonstrate how to create a layout programmatically.
public class CodeLayout extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Creating a new RelativeLayout
RelativeLayout relativeLayout = new RelativeLayout(this);
// Defining the RelativeLayout layout parameters.
// In this case I want to fill its parent
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.FILL_PARENT);
// Creating a new TextView
TextView tv = new TextView(this);
tv.setText("Test");
// Defining the layout parameters of the TextView
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT);
// Setting the parameters on the TextView
tv.setLayoutParams(lp);
// Adding the TextView to the RelativeLayout as a child
relativeLayout.addView(tv);
// Setting the RelativeLayout as our content view
setContentView(relativeLayout, rlp);
}
}
In theory everything should be clear as it is commented. If you don't understand something just tell me.
Since Joda is getting faded, someone might want to convert LocaltDate
to LocalDateTime
in Java 8. In Java 8 LocalDateTime
it will give a way to create a LocalDateTime
instance using a LocalDate
and LocalTime
. Check here.
public static LocalDateTime of(LocalDate date, LocalTime time)
Sample would be,
// just to create a sample LocalDate
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate ld = LocalDate.parse("20180306", dtf);
// convert ld into a LocalDateTime
// We need to specify the LocalTime component here as well, it can be any accepted value
LocalDateTime ldt = LocalDateTime.of(ld, LocalTime.of(0,0)); // 2018-03-06T00:00
Just for reference, For getting the epoch seconds below can be used,
ZoneId zoneId = ZoneId.systemDefault();
long epoch = ldt.atZone(zoneId).toEpochSecond();
// If you only care about UTC
long epochUTC = ldt.toEpochSecond(ZoneOffset.UTC);
You can also use the Runtime to create a cross platform solution:
import java.awt.Desktop;
import java.net.URI;
public class App {
public static void main(String[] args) throws Exception {
String url = "http://stackoverflow.com";
if (Desktop.isDesktopSupported()) {
// Windows
Desktop.getDesktop().browse(new URI(url));
} else {
// Ubuntu
Runtime runtime = Runtime.getRuntime();
runtime.exec("/usr/bin/firefox -new-window " + url);
}
}
}
You can use gdb, but I would first try Valgrind. See the quick start guide.
Briefly, Valgrind instruments your program so it can detect several kinds of errors in using dynamically allocated memory, such as double frees and writes past the end of allocated blocks of memory (which can corrupt the heap). It detects and reports the errors as soon as they occur, thus pointing you directly to the cause of the problem.
If you are on Windows using SMTP, you can use error_get_last()
when mail()
returns false. Keep in mind this does not work with PHP's native mail() function.
$success = mail('[email protected]', 'My Subject', $message);
if (!$success) {
$errorMessage = error_get_last()['message'];
}
With print_r(error_get_last())
, you get something like this:
[type] => 2
[message] => mail(): Failed to connect to mailserver at "x.x.x.x" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()
[file] => C:\www\X\X.php
[line] => 2