var i2 = JsonConvert.DeserializeObject(obj["id"].ToString(), type);
throws a parsing exception due to missing quotes around the first argument (I think). I got it to work by adding the quotes:
var i2 = JsonConvert.DeserializeObject("\"" + obj["id"].ToString() + "\"", type);
change
public class LinqHelper
to
public static class LinqHelper
Following points need to be considered when creating an extension method:
non-generic
, static
and non-nested
static
methodthis
keyword. We have a winXP build pc, and use Visual Build Pro 6 to build our software. since some of our developers use VS 2010 the project files now contain reference to "tool version 4.0" and from what I can tell, this tells Visual Build it needs to find a sdk7.x somewhere, even though we only build for .NET 3.5. This caused it not to find lc.exe. I tried to fool it by pointing all the macros to the 6.0A sdk that came with VS2008 which is installed on the pc, but that did not work.
I eventually got it working by downloading and installing sdk 7.1. I then created a registry key for 7.0A and pointed the install path to the install path of the 7.1 sdk. now it happily finds a compatible "lc.exe" and all the code compiles fine. I have a feeling I will now also be able to compile .NET 4.0 code even though VS2010 is not installed, but I have not tried that yet.
Update your pom.xml
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>3.1</version>
</dependency>
I also came across this problem. In my case, I didn't know the type of the IEnumerable. So the answers given above wont work. However, I solved it like this:
public static DataTable CreateDataTable(IEnumerable source)
{
var table = new DataTable();
int index = 0;
var properties = new List<PropertyInfo>();
foreach (var obj in source)
{
if (index == 0)
{
foreach (var property in obj.GetType().GetProperties())
{
if (Nullable.GetUnderlyingType(property.PropertyType) != null)
{
continue;
}
properties.Add(property);
table.Columns.Add(new DataColumn(property.Name, property.PropertyType));
}
}
object[] values = new object[properties.Count];
for (int i = 0; i < properties.Count; i++)
{
values[i] = properties[i].GetValue(obj);
}
table.Rows.Add(values);
index++;
}
return table;
}
Keep in mind that using this method, requires at least one item in the IEnumerable. If that's not the case, the DataTable wont create any columns.
Marc's answer is the approach I use for this, but for simplicity (and a friendlier API?) you can define a property in the collection base class if you have one such as:
public abstract class CollectionBase<T> : IList<T>
{
...
public Type ElementType
{
get
{
return typeof(T);
}
}
}
I have found this approach useful, and is easy to understand for any newcomers to generics.
(2018) the new python requests library has simplified this process, we can use the 'files' variable to signal that we want to upload a multipart-encoded file
url = 'http://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)
r.text
You will find these assemblies in the Extensions group under Assemblies in Visual Studio 2010, 2012 & 2013 (Reference Manager)
regarding Kevin answer to write in a folder tmp
, it should be like this:
with open('./tmp/metadata.pdf', 'wb') as f:
f.write(response.content)
he forgot .
before the address and of-course your folder tmp
should have been created already
Completely Transparent StatusBar and NavigationBar
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
transparentStatusAndNavigation();
}
private void transparentStatusAndNavigation() {
//make full transparent statusBar
if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) {
setWindowFlag(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
| WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, true);
}
if (Build.VERSION.SDK_INT >= 19) {
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
);
}
if (Build.VERSION.SDK_INT >= 21) {
setWindowFlag(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
| WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, false);
getWindow().setStatusBarColor(Color.TRANSPARENT);
getWindow().setNavigationBarColor(Color.TRANSPARENT);
}
}
private void setWindowFlag(final int bits, boolean on) {
Window win = getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
if (on) {
winParams.flags |= bits;
} else {
winParams.flags &= ~bits;
}
win.setAttributes(winParams);
}
Laravel 5 promotes the use of namespaces for things like Models and Controllers. Your Model is under the App
namespace, so your code needs to call it like this:
Route::get('/posts', function(){
$results = \App\Post::all();
return $results;
});
As mentioned in the comments you can also use
or import a namespace in to a file so you don't need to quote the full path, like this:
use App\Post;
Route::get('/posts', function(){
$results = Post::all();
return $results;
});
While I'm doing a short primer on namespaces I might as well mention the ability to alias a class as well. Doing this means you can essentially rename your class just in the scope of one file, like this:
use App\Post as PostModel;
Route::get('/posts', function(){
$results = PostModel::all();
return $results;
});
More info on importing and aliasing namespaces here: http://php.net/manual/en/language.namespaces.importing.php
If the intention is adding the local/working copy to SVN, I used to do it the following way.
Note: I use the TortoiseSVN client and these steps assume that you already have the TortoiseSVN client installed.
I've did a "Update-Package –reinstall Microsoft.AspNet.Mvc" to fix it in Visual Studio 2015.
You have to explicitly cast the string types to the same in order to concatenate them, In your case you may solve the issue by simply addig an 'N' in front of 'SomeText' (N'SomeText'). If that doesn't work, try Cast('SomeText' as nvarchar(8)).
There can be a difference for loops. This is the practical application of post/pre-increment.
int i = 0;
while(i++ <= 10) {
Console.Write(i);
}
Console.Write(System.Environment.NewLine);
i = 0;
while(++i <= 10) {
Console.Write(i);
}
Console.ReadLine();
While the first one counts to 11 and loops 11 times, the second does not.
Mostly this is rather used in a simple while(x-- > 0 ) ; - - Loop to iterate for example all elements of an array (exempting foreach-constructs here).
The same tech note as refered to in the accepted answer (TN2265 - Troubleshooting Push Notifications) has since been updated with a solution for iOS 5 and above.
In short: create a backup and restore from it every time.
On iOS 5 and later, reset the push notifications permissions alert by restoring the device from a backup (r. 11450187). Here are the steps to do this efficiently:
- Use the Xcode Organizer to install your app on the device. The key is to install the app for the first time without running it.
- Use iTunes to back up the device.
- Run the app. The push notifications permissions alert will be presented.
- When you want to reset the push notifications permissions alert, restore the device from the backup you created in the first step.
If you need to find values for variables other than those standard VS macros, you could do that easily using Process Explorer. Start it, find the process your Visual Studio instance runs in, right click, Properties ? Environment. It lists all those $ vars as key-value pairs:
On Windows with Android Studio 1.5.1 : File --> Settings --> Editor --> General --> Auto Import
As mentioned in other answers, the Panel generates a <div>
in HTML, while the PlaceHolder does not. But there are a lot more reasons why you could choose either one.
Why a PlaceHolder?
Since it generates no tag of it's own you can use it safely inside other element that cannot contain a <div>
, for example:
<table>
<tr>
<td>Row 1</td>
</tr>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</table>
You can also use a PlaceHolder to control the Visibility of a group of Controls without wrapping it in a <div>
<asp:PlaceHolder ID="PlaceHolder1" runat="server" Visible="false">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</asp:PlaceHolder>
Why a Panel
It generates it's own <div>
and can also be used to wrap a group of Contols. But a Panel has a lot more properties that can be useful to format it's content:
<asp:Panel ID="Panel1" runat="server" Font-Bold="true"
BackColor="Green" ForeColor="Red" Width="200"
Height="200" BorderColor="Black" BorderStyle="Dotted">
Red text on a green background with a black dotted border.
</asp:Panel>
But the most useful feature is the DefaultButton
property. When the ID matches a Button in the Panel it will trigger a Form Post with Validation when enter
is pressed inside a TextBox. Now a user can submit the Form without pressing the Button.
<asp:Panel ID="Panel1" runat="server" DefaultButton="Button1">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="Input is required" ValidationGroup="myValGroup"
Display="Dynamic" ControlToValidate="TextBox1"></asp:RequiredFieldValidator>
<br />
<asp:Button ID="Button1" runat="server" Text="Button" ValidationGroup="myValGroup" />
</asp:Panel>
Try the above snippet by pressing enter
inside TextBox1
You just missed an extra pair of brackets for the "OR" symbol. The following should do the trick:
([0-9]+)\s+((\bseconds\b)|(\bminutes\b))
Without those you were either matching a number followed by seconds OR just the word minutes
Try:
select
id,
StartDate,
CASE WHEN StartDate IS NULL
THEN 'Awaiting'
ELSE 'Approved' END AS StartDateStatus
FROM myTable
You code would have been doing a When StartDate = NULL, I think.
NULL
is never equal to NULL
(as NULL is the absence of a value). NULL
is also never not equal to NULL
. The syntax noted above is ANSI SQL standard and the converse would be StartDate IS NOT NULL
.
You can run the following:
SELECT CASE WHEN (NULL = NULL) THEN 1 ELSE 0 END AS EqualityCheck,
CASE WHEN (NULL <> NULL) THEN 1 ELSE 0 END AS InEqualityCheck,
CASE WHEN (NULL IS NULL) THEN 1 ELSE 0 END AS NullComparison
And this returns:
EqualityCheck = 0
InEqualityCheck = 0
NullComparison = 1
For completeness, in SQL Server you can:
SET ANSI_NULLS OFF;
Which would result in your equals comparisons working differently:
SET ANSI_NULLS OFF
SELECT CASE WHEN (NULL = NULL) THEN 1 ELSE 0 END AS EqualityCheck,
CASE WHEN (NULL <> NULL) THEN 1 ELSE 0 END AS InEqualityCheck,
CASE WHEN (NULL IS NULL) THEN 1 ELSE 0 END AS NullComparison
Which returns:
EqualityCheck = 1
InEqualityCheck = 0
NullComparison = 1
But I would highly recommend against doing this. People subsequently maintaining your code might be compelled to hunt you down and hurt you...
Also, it will no longer work in upcoming versions of SQL server:
To get more than 20 you can use a load more button.
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Instagram more button example</title>
<!--
Instagram PHP API class @ Github
https://github.com/cosenary/Instagram-PHP-API
-->
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
ul {
width: 950px;
}
ul > li {
float: left;
list-style: none;
padding: 4px;
}
#more {
bottom: 8px;
margin-left: 80px;
position: fixed;
font-size: 13px;
font-weight: 700;
line-height: 20px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#more').click(function() {
var tag = $(this).data('tag'),
maxid = $(this).data('maxid');
$.ajax({
type: 'GET',
url: 'ajax.php',
data: {
tag: tag,
max_id: maxid
},
dataType: 'json',
cache: false,
success: function(data) {
// Output data
$.each(data.images, function(i, src) {
$('ul#photos').append('<li><img src="' + src + '"></li>');
});
// Store new maxid
$('#more').data('maxid', data.next_id);
}
});
});
});
</script>
</head>
<body>
<?php
/**
* Instagram PHP API
*/
require_once 'instagram.class.php';
// Initialize class with client_id
// Register at http://instagram.com/developer/ and replace client_id with your own
$instagram = new Instagram('ENTER CLIENT ID HERE');
// Get latest photos according to geolocation for Växjö
// $geo = $instagram->searchMedia(56.8770413, 14.8092744);
$tag = 'sweden';
// Get recently tagged media
$media = $instagram->getTagMedia($tag);
// Display first results in a <ul>
echo '<ul id="photos">';
foreach ($media->data as $data)
{
echo '<li><img src="'.$data->images->thumbnail->url.'"></li>';
}
echo '</ul>';
// Show 'load more' button
echo '<br><button id="more" data-maxid="'.$media->pagination->next_max_id.'" data-tag="'.$tag.'">Load more ...</button>';
?>
</body>
</html>
ajax.php
<?php
/**
* Instagram PHP API
*/
require_once 'instagram.class.php';
// Initialize class for public requests
$instagram = new Instagram('ENTER CLIENT ID HERE');
// Receive AJAX request and create call object
$tag = $_GET['tag'];
$maxID = $_GET['max_id'];
$clientID = $instagram->getApiKey();
$call = new stdClass;
$call->pagination->next_max_id = $maxID;
$call->pagination->next_url = "https://api.instagram.com/v1/tags/{$tag}/media/recent?client_id={$clientID}&max_tag_id={$maxID}";
// Receive new data
$media = $instagram->getTagMedia($tag,$auth=false,array('max_tag_id'=>$maxID));
// Collect everything for json output
$images = array();
foreach ($media->data as $data) {
$images[] = $data->images->thumbnail->url;
}
echo json_encode(array(
'next_id' => $media->pagination->next_max_id,
'images' => $images
));
?>
instagram.class.php
Find the function getTagMedia() and replace with:
public function getTagMedia($name, $auth=false, $params=null) {
return $this->_makeCall('tags/' . $name . '/media/recent', $auth, $params);
}
move c:\Sourcefoldernam\*.* e:\destinationFolder
^ This did not work for me for some reason
But when I tried using quotation marks, it suddenly worked:
move "c:\Sourcefoldernam\*.*" "e:\destinationFolder"
I think its because my directory had spaces in one of the folders. So if it doesn't work for you, try with quotation marks!
I'd recommend making "apple" its own class. You should avoid the starts-with/ends-with if you can because being able to select using div.apple
would be a lot faster. That's the more elegant solution. Don't be afraid to split things out into separate classes if it makes the task simpler/faster.
it is better that use current event and dont save handler in global handler. i get current element event then unbind then bind again. for a handler.
var element = $("#elemid")[0];
var tempHandler = jQuery._data(element)["events"]["click"][0].handler;
$("#elemid").unbind("click");
// do the job that click not suppose to listen;
$("#elemid").bind("click" , tempHandler );
for all handler
var element = $("#elemid")[0];
var clickHandlerList = jQuery._data(element)["events"]["click"];
var handlerList = [];
for(var i = 0 ; i < clickHandlerList .length ; i++) {
handlerList .push(clickHandlerList [i].handler);
}
$("#elemid").unbind("click");
// do the job that click not suppose to listen;
for(var i = 0 ; i < handlerList.length ; i++) {
// return back all handler to element.
$("#elemid").bind("click" , handlerList[i]);
}
From the C++ standard section 3.1:
A declaration introduces names into a translation unit or redeclares names introduced by previous declarations. A declaration specifies the interpretation and attributes of these names.
The next paragraph states (emphasis mine) that a declaration is a definition unless...
... it declares a function without specifying the function’s body:
void sqrt(double); // declares sqrt
... it declares a static member within a class definition:
struct X
{
int a; // defines a
static int b; // declares b
};
... it declares a class name:
class Y;
... it contains the extern
keyword without an initializer or function body:
extern const int i = 0; // defines i
extern int j; // declares j
extern "C"
{
void foo(); // declares foo
}
... or is a typedef
or using
statement.
typedef long LONG_32; // declares LONG_32
using namespace std; // declares std
Now for the big reason why it's important to understand the difference between a declaration and definition: the One Definition Rule. From section 3.2.1 of the C++ standard:
No translation unit shall contain more than one definition of any variable, function, class type, enumeration type, or template.
Explain step by step of Airsource Ltd's answer for adding image to simulator:
Update: for iOS Simulator 4.2, do these steps twice to get it work. Thanks kevboh
!
Update: This also works for iOS Simulator 6.1
Recent updates to ggplot (0.9.2+) have overhauled the syntax for themes. Most notably, opts()
is now deprecated, having been replaced by theme()
. Sandy's answer will still (as of Jan '12) generates a chart, but causes R to throw a bunch of warnings.
Here's updated code reflecting current ggplot syntax:
library(ggplot2)
a <- seq(1,20)
b <- a^0.25
df <- as.data.frame(cbind(a,b))
#base ggplot object
p <- ggplot(df, aes(x = a, y = b))
p +
#plots the points
geom_point() +
#theme with white background
theme_bw() +
#eliminates background, gridlines, and chart border
theme(
plot.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank()
) +
#draws x and y axis line
theme(axis.line = element_line(color = 'black'))
generates:
In a word - speed. An index for up to a million rows fits in a 32-bit word, so it can be used efficiently on 32-bit processors. Function arguments that fit in a CPU register are extremely efficient, while ones that are larger require accessing memory on each function call, a far slower operation. Updating a spreadsheet can be an intensive operation involving many cell references, so speed is important. Besides, the Excel team expects that anyone dealing with more than a million rows will be using a database rather than a spreadsheet.
Loadsh is the universal standard library for coping any object deepcopy. It's a recursive algorithm. It's check everything and does copy for the given object. Writing this kind of algorithm will take longer time. It's better to leverage the same.
Blobs are returned with file type from backend. The following function will accept any file type and popup download window:
downloadFile(route: string, filename: string = null): void{
const baseUrl = 'http://myserver/index.php/api';
const token = 'my JWT';
const headers = new HttpHeaders().set('authorization','Bearer '+token);
this.http.get(baseUrl + route,{headers, responseType: 'blob' as 'json'}).subscribe(
(response: any) =>{
let dataType = response.type;
let binaryData = [];
binaryData.push(response);
let downloadLink = document.createElement('a');
downloadLink.href = window.URL.createObjectURL(new Blob(binaryData, {type: dataType}));
if (filename)
downloadLink.setAttribute('download', filename);
document.body.appendChild(downloadLink);
downloadLink.click();
}
)
}
data-target
is used by bootstrap to make your life easier. You (mostly) do not need to write a single line of Javascript to use their pre-made JavaScript components.
The data-target
attribute should contain a CSS selector that points to the HTML Element that will be changed.
<!-- Button trigger modal -->
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
[...]
</div>
In this example, the button has data-target="#myModal"
, if you click on it, <div id="myModal">...</div>
will be modified (in this case faded in).
This happens because #myModal
in CSS selectors points to elements that have an id
attribute with the myModal
value.
Further information about the HTML5 "data-" attribute: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes
In your invocation, the two functions are the same.
average
can compute a weighted average though.
I ran into a real problem where it was indeed evil. Essentially a developer returned a reference to an object in a vector. That was Bad!!!
The full details I wrote about in Janurary: http://developer-resource.blogspot.com/2009/01/pros-and-cons-of-returing-references.html
Both are logical AND operations. The && though, is a "short-circuit" operator. From the MATLAB docs:
They are short-circuit operators in that they evaluate their second operand only when the result is not fully determined by the first operand.
See more here.
Use this one
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
// Get the layout inflater
LayoutInflater inflater = (activity).getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the
// dialog layout
builder.setTitle(title);
builder.setCancelable(false);
builder.setIcon(R.drawable.galleryalart);
builder.setView(inflater.inflate(R.layout.dialogue, null))
// Add action buttons
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
}
}
});
builder.create();
builder.show();
In my case, it was because the AJAX call was being blocked by the browser because of the same-origin policy. It was the least expected thing, because all my HTMLs and scripts where being served from 127.0.0.1
. How could they be considered as having different origins?
Anyway, the root cause was an innocent-looking <base>
tag:
<base href='<%=request.getScheme()%>://<%=request.getServerName() + ":" + request.getServerPort() + request.getContextPath()%>/'/>
I removed the <base>
tag, which I did not need by the way, and now it works fine!
We have solved the same error by following the below steps.
linux command for this type of error occurred then, first of all, check your php.ini file
If your php.ini file exists then in configuration file simply uncomment the extension:
;extension=php_pdo_mysql.dll
Else follow below steps
step1:php -v
step2: Install php mysql extension
php 7.0 sudo apt-get install php7.0-mysql
php 7.1 sudo apt-get install php7.1-mysql
php 7.2 sudo apt-get install php7.2-mysql
php 7.3 sudo apt-get install php7.3-mysql
step3: service apache2 restart
step4: php artisan migrate
You can just use the pipe on its own:
"string1|string2"
for example:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|string2", "blah"));
Output:
blah, blah, string3
The main reason to use parentheses is to limit the scope of the alternatives:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(1|2)", "blah"));
has the same output. but if you just do this:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|2", "blah"));
you get:
blah, stringblah, string3
because you've said "string1" or "2".
If you don't want to capture that part of the expression use ?:
:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(?:1|2)", "blah"));
Here's a fun way to do it with a decorator:
def restartable(func):
def wrapper(*args,**kwargs):
answer = 'y'
while answer == 'y':
func(*args,**kwargs)
while True:
answer = raw_input('Restart? y/n:')
if answer in ('y','n'):
break
else:
print "invalid answer"
return wrapper
@restartable
def main():
print "foo"
main()
Ultimately, I think you need 2 while loops. You need one loop bracketing the portion which prompts for the answer so that you can prompt again if the user gives bad input. You need a second which will check that the current answer is 'y'
and keep running the code until the answer isn't 'y'
.
The Java "for-each" loop construct will allow iteration over two types of objects:
T[]
(arrays of any type)java.lang.Iterable<T>
The Iterable<T>
interface has only one method: Iterator<T> iterator()
. This works on objects of type Collection<T>
because the Collection<T>
interface extends Iterable<T>
.
As mentioned by Jon F Hancock, this is how a fragment can 'close' the activity by suggesting the activity to close. This makes the fragment portable as is the reason for them. If you use it in a different activity, you might not want to close the activity.
Code below is a snippet from an activity and fragment which has a save and cancel button.
PlayerActivity
public class PlayerActivity extends Activity
implements PlayerInfo.PlayerAddListener {
public void onPlayerCancel() {
// Decide if its suitable to close the activity,
//e.g. is an edit being done in one of the other fragments?
finish();
}
}
PlayerInfoFragment, which contains an interface which the calling activity needs to implement.
public class PlayerInfoFragment extends Fragment {
private PlayerAddListener callback; // implemented in the Activity
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
callback= (PlayerAddListener) activity;
}
public interface PlayerAddListener {
public void onPlayerSave(Player p); // not shown in impl above
public void onPlayerCancel();
}
public void btnCancel(View v) {
callback.onPlayerCancel(); // the activity's implementation
}
}
Note - the RFC proposing this is still in the draft state.
class Singleton
{
private static function __static()
{
//...
}
//...
}
proposed for PHP 7.x (see https://wiki.php.net/rfc/static_class_constructor )
<section class="min-vh-100 d-flex align-items-center justify-content-center py-3">
<div class="container">
<div class="row justify-content-between align-items-center">
x
x
x
</div>
</div>
</section>
_x000D_
You can also try the following project that aims to help use that api. It's here:https://github.com/MathiasSeguy-Android2EE/GDirectionsApiUtils
How it works, definitly simply:
public class MainActivity extends ActionBarActivity implements DCACallBack{
/**
* Get the Google Direction between mDevice location and the touched location using the Walk
* @param point
*/
private void getDirections(LatLng point) {
GDirectionsApiUtils.getDirection(this, mDeviceLatlong, point, GDirectionsApiUtils.MODE_WALKING);
}
/*
* The callback
* When the direction is built from the google server and parsed, this method is called and give you the expected direction
*/
@Override
public void onDirectionLoaded(List<GDirection> directions) {
// Display the direction or use the DirectionsApiUtils
for(GDirection direction:directions) {
Log.e("MainActivity", "onDirectionLoaded : Draw GDirections Called with path " + directions);
GDirectionsApiUtils.drawGDirection(direction, mMap);
}
}
If you are using gvim, you could just hit Ctrl + Home to go the first line. Similarly, Ctrl + End goes to the last line.
The location=1
part should enable an editable location bar.
As a side note, you can drop the language="javascript"
attribute from your script as it is now deprecated.
update:
Setting the statusbar=1
to the correct parameter status=1
works for me
You could do the following:
.interrupt
the working threads if they wait for data in some blocking call)writeBatch
in your case) to finish, by calling the Thread.join()
method on the working threads.Some sketchy code:
static volatile boolean keepRunning = true;
In run() you change to
for (int i = 0; i < N && keepRunning; ++i)
writeBatch(pw, i);
In main() you add:
final Thread mainThread = Thread.currentThread();
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
keepRunning = false;
mainThread.join();
}
});
That's roughly how I do a graceful "reject all clients upon hitting Control-C" in terminal.
From the docs:
When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt.
That is, a shutdown hook keeps the JVM running until the hook has terminated (returned from the run()-method.
Hide it for all activities using the theme
<style name="MyTheme" parent="Theme">
<item name="android:windowSoftInputMode">stateHidden</item>
</style>
set the theme
<application android:theme="@style/MyTheme">
replace()
method:From the urlStr
string:
paramVal = urlStr.replace(/.*param_name=([^&]*).*|(.*)/, '$1');
or from the current URL:
paramVal = document.URL.replace(/.*param_name=([^&]*).*|(.*)/, '$1');
Explanation:
document.URL
- interface returns the document location (page url) as a string.replace()
- method returns a new string with some or all matches of a pattern replaced by a replacement./.*param_name=([^&]*).*/
- the regular expression pattern enclosed between slashes which means:
.*
- zero or more of any characters,param_name=
- param name which is serched,()
- group in regular expression,[^&]*
- one or more of any characters excluding &
,|
- alternation,$1
- reference to first group in regular expression.var urlStr = 'www.test.com/t.html?a=1&b=3&c=m2-m3-m4-m5';_x000D_
var c = urlStr.replace(/.*c=([^&]*).*|(.*)/, '$1');_x000D_
var notExisted = urlStr.replace(/.*not_existed=([^&]*).*|(.*)/, '$1');_x000D_
console.log(`c === '${c}'`);_x000D_
console.log(`notExisted === '${notExisted}'`);
_x000D_
You do not define a binding in your service's config, so you are getting the default values for wsHttpBinding
, and the default value for securityMode\transport
for that binding is Message
.
Try copying your binding configuration from the client's config to your service config and assign that binding to the endpoint via the bindingConfiguration
attribute:
<bindings>
<wsHttpBinding>
<binding name="ota2010AEndpoint"
.......>
<readerQuotas maxDepth="32" ... />
<reliableSession ordered="true" .... />
<security mode="Transport">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="Windows" negotiateServiceCredential="true"
establishSecurityContext="true" />
</security>
</binding>
</wsHttpBinding>
</bindings>
(Snipped parts of the config to save space in the answer).
<service name="Synxis" behaviorConfiguration="SynxisWCF">
<endpoint address="" name="wsHttpEndpoint"
binding="wsHttpBinding"
bindingConfiguration="ota2010AEndpoint"
contract="Synxis" />
This will then assign your defined binding (with Transport security) to the endpoint.
For background pushes in iOS13, you must set below parameters:
apns-priority = 5
apns-push-type = background
//Required for WatchOS
//Highly recommended for Other platforms
The video link: https://developer.apple.com/videos/play/wwdc2019/707/
I use gitk
to see the difference:
gitk k73ud..dj374
It has a GUI mode so that reviewing is easier.
So, what happens when a server listen for incoming connections on a TCP port? For example, let's say you have a web-server on port 80. Let's assume that your computer has the public IP address of 24.14.181.229 and the person that tries to connect to you has IP address 10.1.2.3. This person can connect to you by opening a TCP socket to 24.14.181.229:80. Simple enough.
Intuitively (and wrongly), most people assume that it looks something like this:
Local Computer | Remote Computer
--------------------------------
<local_ip>:80 | <foreign_ip>:80
^^ not actually what happens, but this is the conceptual model a lot of people have in mind.
This is intuitive, because from the standpoint of the client, he has an IP address, and connects to a server at IP:PORT. Since the client connects to port 80, then his port must be 80 too? This is a sensible thing to think, but actually not what happens. If that were to be correct, we could only serve one user per foreign IP address. Once a remote computer connects, then he would hog the port 80 to port 80 connection, and no one else could connect.
Three things must be understood:
1.) On a server, a process is listening on a port. Once it gets a connection, it hands it off to another thread. The communication never hogs the listening port.
2.) Connections are uniquely identified by the OS by the following 5-tuple: (local-IP, local-port, remote-IP, remote-port, protocol). If any element in the tuple is different, then this is a completely independent connection.
3.) When a client connects to a server, it picks a random, unused high-order source port. This way, a single client can have up to ~64k connections to the server for the same destination port.
So, this is really what gets created when a client connects to a server:
Local Computer | Remote Computer | Role
-----------------------------------------------------------
0.0.0.0:80 | <none> | LISTENING
127.0.0.1:80 | 10.1.2.3:<random_port> | ESTABLISHED
First, let's use netstat to see what is happening on this computer. We will use port 500 instead of 80 (because a whole bunch of stuff is happening on port 80 as it is a common port, but functionally it does not make a difference).
netstat -atnp | grep -i ":500 "
As expected, the output is blank. Now let's start a web server:
sudo python3 -m http.server 500
Now, here is the output of running netstat again:
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:500 0.0.0.0:* LISTEN -
So now there is one process that is actively listening (State: LISTEN) on port 500. The local address is 0.0.0.0, which is code for "listening for all". An easy mistake to make is to listen on address 127.0.0.1, which will only accept connections from the current computer. So this is not a connection, this just means that a process requested to bind() to port IP, and that process is responsible for handling all connections to that port. This hints to the limitation that there can only be one process per computer listening on a port (there are ways to get around that using multiplexing, but this is a much more complicated topic). If a web-server is listening on port 80, it cannot share that port with other web-servers.
So now, let's connect a user to our machine:
quicknet -m tcp -t localhost:500 -p Test payload.
This is a simple script (https://github.com/grokit/dcore/tree/master/apps/quicknet) that opens a TCP socket, sends the payload ("Test payload." in this case), waits a few seconds and disconnects. Doing netstat again while this is happening displays the following:
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:500 0.0.0.0:* LISTEN -
tcp 0 0 192.168.1.10:500 192.168.1.13:54240 ESTABLISHED -
If you connect with another client and do netstat again, you will see the following:
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:500 0.0.0.0:* LISTEN -
tcp 0 0 192.168.1.10:500 192.168.1.13:26813 ESTABLISHED -
... that is, the client used another random port for the connection. So there is never confusion between the IP addresses.
Here's an example using an extension. This assumes the view has the same width and height.
Need to use a layout change listener to get the view size.
Then you can just call this on a view like this myView.setRoundedBackground(Color.WHITE)
fun View.setRoundedBackground(@ColorInt color: Int) {
addOnLayoutChangeListener(object: View.OnLayoutChangeListener {
override fun onLayoutChange(v: View?, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int) {
val shape = GradientDrawable()
shape.cornerRadius = measuredHeight / 2f
shape.setColor(color)
background = shape
removeOnLayoutChangeListener(this)
}
})
}
I would definitely advise you to have a look at System.Diagnostics.Stopwatch
And when I looked around for more about Stopwatch I found this site;
There mentioned another possibility
Process.TotalProcessorTime
Try this code.You can replace any character with another given character. Here I tried to replace the letter 'a' with "-" character for the give string "abcdeaa"
OutPut -->_bcdef__
public class Replace {
public static void replaceChar(String str,String target){
String result = str.replaceAll(target, "_");
System.out.println(result);
}
public static void main(String[] args) {
replaceChar("abcdefaa","a");
}
}
$DISPLAY is the standard way. That's how users communicate with programs about which X server to use, if any.
Are you sure your HTML form is correct, and does, in fact, do an HTTP POST? I would suggest running Fiddler2, and then trying to log in via your Login.aspx, then the remote HTML site, and then comparing the requests that are sent to the server. For me, ASP.Net always worked fine -- if HTTP request contains a valid POST, I can get to values using Request.Form...
This code pen (not by me) demonstrates a super simple way of doing this and the other sides by themselves quite nicely:
box-shadow: 0 5px 5px -5px #333;
Use list comprehensions if you want a single line solution. The following code returns a list containing the url_string when it has the extensions .doc, .pdf and .xls or returns empty list when it doesn't contain the extension.
print [url_string for extension in extensionsToCheck if(extension in url_string)]
NOTE: This is only to check if it contains or not and is not useful when one wants to extract the exact word matching the extensions.
I too needed a rounded ImageView, I used the below code, you can modify it accordingly:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
public class RoundedImageView extends ImageView {
public RoundedImageView(Context context) {
super(context);
}
public RoundedImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
if (drawable == null) {
return;
}
if (getWidth() == 0 || getHeight() == 0) {
return;
}
Bitmap b = ((BitmapDrawable) drawable).getBitmap();
Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);
int w = getWidth();
@SuppressWarnings("unused")
int h = getHeight();
Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
canvas.drawBitmap(roundBitmap, 0, 0, null);
}
public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
Bitmap sbmp;
if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
float factor = smallest / radius;
sbmp = Bitmap.createScaledBitmap(bmp,
(int) (bmp.getWidth() / factor),
(int) (bmp.getHeight() / factor), false);
} else {
sbmp = bmp;
}
Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final String color = "#BAB399";
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, radius, radius);
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(Color.parseColor(color));
canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
radius / 2 + 0.1f, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(sbmp, rect, rect, paint);
return output;
}
}
The use of fork
and exec
exemplifies the spirit of UNIX in that it provides a very simple way to start new processes.
The fork
call basically makes a duplicate of the current process, identical in almost every way. Not everything is copied over (for example, resource limits in some implementations) but the idea is to create as close a copy as possible.
The new process (child) gets a different process ID (PID) and has the PID of the old process (parent) as its parent PID (PPID). Because the two processes are now running exactly the same code, they can tell which is which by the return code of fork
- the child gets 0, the parent gets the PID of the child. This is all, of course, assuming the fork
call works - if not, no child is created and the parent gets an error code.
The exec
call is a way to basically replace the entire current process with a new program. It loads the program into the current process space and runs it from the entry point.
So, fork
and exec
are often used in sequence to get a new program running as a child of a current process. Shells typically do this whenever you try to run a program like find
- the shell forks, then the child loads the find
program into memory, setting up all command line arguments, standard I/O and so forth.
But they're not required to be used together. It's perfectly acceptable for a program to fork
itself without exec
ing if, for example, the program contains both parent and child code (you need to be careful what you do, each implementation may have restrictions). This was used quite a lot (and still is) for daemons which simply listen on a TCP port and fork
a copy of themselves to process a specific request while the parent goes back to listening.
Similarly, programs that know they're finished and just want to run another program don't need to fork
, exec
and then wait
for the child. They can just load the child directly into their process space.
Some UNIX implementations have an optimized fork
which uses what they call copy-on-write. This is a trick to delay the copying of the process space in fork
until the program attempts to change something in that space. This is useful for those programs using only fork
and not exec
in that they don't have to copy an entire process space.
If the exec
is called following fork
(and this is what happens mostly), that causes a write to the process space and it is then copied for the child process.
Note that there is a whole family of exec
calls (execl
, execle
, execve
and so on) but exec
in context here means any of them.
The following diagram illustrates the typical fork/exec
operation where the bash
shell is used to list a directory with the ls
command:
+--------+
| pid=7 |
| ppid=4 |
| bash |
+--------+
|
| calls fork
V
+--------+ +--------+
| pid=7 | forks | pid=22 |
| ppid=4 | ----------> | ppid=7 |
| bash | | bash |
+--------+ +--------+
| |
| waits for pid 22 | calls exec to run ls
| V
| +--------+
| | pid=22 |
| | ppid=7 |
| | ls |
V +--------+
+--------+ |
| pid=7 | | exits
| ppid=4 | <---------------+
| bash |
+--------+
|
| continues
V
Simply put these codes at top of your PHP/index file:
error_reporting(E_ALL); // Error/Exception engine, always use E_ALL
ini_set('ignore_repeated_errors', TRUE); // always use TRUE
ini_set('display_errors', FALSE); // Error/Exception display, use FALSE only in production environment or real server. Use TRUE in development environment
ini_set('log_errors', TRUE); // Error/Exception file logging engine.
ini_set('error_log', 'your/path/to/errors.log'); // Logging file path
You can also try this pure CSS method:
font-size: calc(100% - 0.3em);
Put your domain name here: https://www.ssllabs.com/ssltest/analyze.html You should be able to see if there are any issues with your ssl certificate chain. I am guessing that you have SSL chain issues. A short description of the problem is that there's actually a list of certificates on your server (and not only one) and these need to be in the correct order. If they are there but not in the correct order, the website will be fine on desktop browsers (an iOs as well I think), but android is more strict about the order of certificates, and will give an error if the order is incorrect. To fix this you just need to re-order the certificates.
The CSPROJ
file, saved in XML format, stores all the references for your project including your compilation options. There is also an SLN file, which stores information about projects that make up your solution.
If you are using Visual Studio and you have the need to view or edit your CSPROJ
file, while in Visual Studio, you can do so by following these simple steps:
echo "<pre>";
print_r($this->session->all_userdata());
echo "</pre>";
Display yet formatting then you can view properly.
This is a problem often encountered with asynchronous code, the variable i
is mutable and at the time at which the function call is made the code using i
will be executed and i
will have mutated to its last value, thus meaning all functions created within the loop will create a closure and i
will be equal to 3 (the upper bound + 1 of the for
loop.
A workaround to this, is to create a function that will hold the value of i
for each iteration and force a copy i
(as it is a primitive, think of it as a snapshot if it helps you).
>>import pandas as pd
>>import numpy as np
>>data.shape
(480,193)
>>type(data)
numpy.ndarray
>>df=pd.DataFrame(data=data[0:,0:],
... index=[i for i in range(data.shape[0])],
... columns=['f'+str(i) for i in range(data.shape[1])])
>>df.head()
[![array to dataframe][1]][1]
Microsoft itself posted a KB article about this, and that article has a service pack that they claim fixes the problem. See below.
http://support.microsoft.com/kb/959417/
It took a while for the associated update to install itself, but once it did, I was able to run the Visual Studio setup successfully from the Add/Remove Programs control panel.
If the primary key happens to be an auto_increment value, you have to remove the auto increment, then drop the primary key then re-add the auto-increment
ALTER TABLE `xx`
MODIFY `auto_increment_field` INT,
DROP PRIMARY KEY,
ADD PRIMARY KEY (new_primary_key);
then add back the auto increment
ALTER TABLE `xx` ADD INDEX `auto_increment_field` (auto_increment_field),
MODIFY `auto_increment_field` int auto_increment;
then set auto increment back to previous value
ALTER TABLE `xx` AUTO_INCREMENT = 5;
You could use a character class ([./-]
) so that the seperators can be any of the defined characters
var dateReg = /^\d{2}[./-]\d{2}[./-]\d{4}$/
Or better still, match the character class for the first seperator, then capture that as a group ([./-])
and use a reference to the captured group \1
to match the second seperator, which will ensure that both seperators are the same:
var dateReg = /^\d{2}([./-])\d{2}\1\d{4}$/
"22-03-1981".match(dateReg) // matches
"22.03-1981".match(dateReg) // does not match
"22.03.1981".match(dateReg) // matches
I felt most of the examples here demonstrated the power of module
rather than how ActiveSupport::Concern
adds value to module
.
Example 1: More readable modules.
So without concerns this how a typical module
will be.
module M
def self.included(base)
base.extend ClassMethods
base.class_eval do
scope :disabled, -> { where(disabled: true) }
end
end
def instance_method
...
end
module ClassMethods
...
end
end
After refactoring with ActiveSupport::Concern
.
require 'active_support/concern'
module M
extend ActiveSupport::Concern
included do
scope :disabled, -> { where(disabled: true) }
end
class_methods do
...
end
def instance_method
...
end
end
You see instance methods, class methods and included block are less messy. Concerns will inject them appropriately for you. That's one advantage of using ActiveSupport::Concern
.
Example 2: Handle module dependencies gracefully.
module Foo
def self.included(base)
base.class_eval do
def self.method_injected_by_foo_to_host_klass
...
end
end
end
end
module Bar
def self.included(base)
base.method_injected_by_foo_to_host_klass
end
end
class Host
include Foo # We need to include this dependency for Bar
include Bar # Bar is the module that Host really needs
end
In this example Bar
is the module that Host
really needs. But since Bar
has dependency with Foo
the Host
class have to include Foo
(but wait why does Host
want to know about Foo
? Can it be avoided?).
So Bar
adds dependency everywhere it goes. And order of inclusion also matters here. This adds lot of complexity/dependency to huge code base.
After refactoring with ActiveSupport::Concern
require 'active_support/concern'
module Foo
extend ActiveSupport::Concern
included do
def self.method_injected_by_foo_to_host_klass
...
end
end
end
module Bar
extend ActiveSupport::Concern
include Foo
included do
self.method_injected_by_foo_to_host_klass
end
end
class Host
include Bar # It works, now Bar takes care of its dependencies
end
Now it looks simple.
If you are thinking why can't we add Foo
dependency in Bar
module itself? That won't work since method_injected_by_foo_to_host_klass
have to be injected in a class that's including Bar
not on Bar
module itself.
Source: Rails ActiveSupport::Concern
<body onload=""> should override window.onload.
With <body onload="">, document.body.onload might be null, undefined or a function depending on the browser (although getAttribute("onload") should be somewhat consistent for getting the body of the anonymous function as a string). With window.onload, when you assign a function to it, window.onload will be a function consistently across browsers. If that matters to you, use window.onload.
window.onload is better for separating the JS from your content anyway. There's not much reason to use <body onload=""> anyway when you can use window.onload.
In Opera, the event target for window.onload and <body onload=""> (and even window.addEventListener("load", func, false)) will be the window instead of the document like in Safari and Firefox. But, 'this' will be the window across browsers.
What this means is that, when it matters, you should wrap the crud and make things consistent or use a library that does it for you.
How about:
echo text | sudo dd status=none of=privilegedfile
I want to change /proc/sys/net/ipv4/tcp_rmem.
I did:
sudo dd status=none of=/proc/sys/net/ipv4/tcp_rmem <<<"4096 131072 1024000"
eliminates the echo with a single line document
No answer helped me, so I build this.
' function Timestamp return current time in milliseconds.
' compatible with JSON or JavaScript Date objects.
Public Function Timestamp () As Currency
timestamp = (Round(Now(), 0) * 24 * 60 * 60 + Timer()) * 1000
End Function
' function Sleep let system execute other programs while the milliseconds are not elapsed.
Public Function Sleep(milliseconds As Currency)
If milliseconds < 0 Then Exit Function
Dim start As Currency
start = Timestamp ()
While (Timestamp () < milliseconds + start)
DoEvents
Wend
End Function
Note : In Excel 2007, Now()
send Double with decimals to seconds, so i use Timer()
to get milliseconds.
Note : Application.Wait()
accept seconds and no under (i.e. Application.Wait(Now())
? Application.Wait(Now()+100*millisecond))
)
Note : Application.Wait()
doesn't let system execute other program but hardly reduce performance. Prefer usage of DoEvents
.
Late answer but:
I see you do a GET - should be a POST ?
A slightly more generic powershell example. In powershell 7, the match is highlighted including the last space (can you highlight in stack?).
'a b c d e f ' | select-string '([a-f] ){6,}'
a b c d e f
Converting your value in milliseconds to days is simply (MsValue / 86,400,000)
We can get 1/1/1970 as numeric value by DATE(1970,1,1)
= (MsValueCellReference / 86400000) + DATE(1970,1,1)
Using your value of 1271664970687 and formatting it as dd/mm/yyyy hh:mm:ss
gives me a date and time of 19/04/2010 08:16:11
I ran into the same issues the other day and it took me days to make it work. The error message was "Could not find the main class", but I can run the executable jar exported from Eclipse in other Windows machines without any problem.
The solution was to install both x64 and x86 version of the same version of JRE. The path environment variable was pointed to the x64 version. No idea why, but it worked for me.
SWIFT 4.x :
self.mConstraint.constant = 100.0
UIView.animate(withDuration: 0.3) {
self.view.layoutIfNeeded()
}
Example with completion:
self.mConstraint.constant = 100
UIView.animate(withDuration: 0.3, animations: {
self.view.layoutIfNeeded()
}, completion: {res in
//Do something
})
Likely when you experience this issue, it is possible is a permission issue on your PC. Going to the PC properties and granting which ever account you use on your PC full control will solve it.
Again command /usr/local doesn't work on windows
If flexibility is one of your prerequisites, XSLT might be a good choice, which is completely supported by .NET framework and you would be able to even let the user edit those files. This article (http://www.aspfree.com/c/a/XML/XSL-Transformations-using-ASP-NET/) might be useful for a start (msdn has more info about it). As said by ScarletGarden NVelocity is another good choice but I do prefer XSLT for its " built-in" .NET framework support and platform agnostic.
A "true" in-place implementation [Algorithms 8.9, 8.11 from the Algorithm Design and Applications Book by Michael T. Goodrich and Roberto Tamassia]:
from random import randint
def partition (A, a, b):
p = randint(a,b)
# or mid point
# p = (a + b) / 2
piv = A[p]
# swap the pivot with the end of the array
A[p] = A[b]
A[b] = piv
i = a # left index (right movement ->)
j = b - 1 # right index (left movement <-)
while i <= j:
# move right if smaller/eq than/to piv
while A[i] <= piv and i <= j:
i += 1
# move left if greater/eq than/to piv
while A[j] >= piv and j >= i:
j -= 1
# indices stopped moving:
if i < j:
# swap
t = A[i]
A[i] = A[j]
A[j] = t
# place pivot back in the right place
# all values < pivot are to its left and
# all values > pivot are to its right
A[b] = A[i]
A[i] = piv
return i
def IpQuickSort (A, a, b):
while a < b:
p = partition(A, a, b) # p is pivot's location
#sort the smaller partition
if p - a < b - p:
IpQuickSort(A,a,p-1)
a = p + 1 # partition less than p is sorted
else:
IpQuickSort(A,p+1,b)
b = p - 1 # partition greater than p is sorted
def main():
A = [12,3,5,4,7,3,1,3]
print A
IpQuickSort(A,0,len(A)-1)
print A
if __name__ == "__main__": main()
In the same way for Chrome Browser below are the things to be considered.
Step 1-->Import files Required for Chrome :
import org.openqa.selenium.chrome.*;
Step 2--> Set the Path and initialize the Chrome Driver:
System.setProperty("webdriver.chrome.driver","S:\\chromedriver_win32\\chromedriver.exe");
Note: In Step 2 the location should point the chromedriver.exe file's storage location in your system drive
step 3--> Create an instance of Chrome browser
WebDriver driver = new ChromeDriver();
Rest will be the same as...
Read Eric Lippert 's answers to these questions
NOTE: This answer is for SQL Server 2005. For SQL Server 2008 and later, there are much better methods as seen in the other answers.
You can use INSERT with SELECT UNION ALL:
INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First' ,1
UNION ALL
SELECT 'Second' ,2
UNION ALL
SELECT 'Third' ,3
...
Only for small datasets though, which should be fine for your 4 records.
Problem I found in Windows server 2016 was that the permissions were wrong on the temp directory used by PHP. I added IUSR.
You will need Javascript to do this:
HTML
<input id="datefield" type='date' min='1899-01-01' max='2000-13-13'></input>
JS
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){
dd='0'+dd
}
if(mm<10){
mm='0'+mm
}
today = yyyy+'-'+mm+'-'+dd;
document.getElementById("datefield").setAttribute("max", today);
You can just change the reference of input value, as below
<div>
<input type="text" placeholder="Search..." #reference>
<button (click)="reference.value=''">Clear</button>
</div>
Thanks for this! I'd liek to add a little riff on the J-P's answer - I don't know if this will help anyone, but this way you don't have to create an array of images, and you can preload all your large images if you name your thumbs correctly. This is handy because I have someone who is writing all the pages in html, and it ensures one less step for them to do - eliminating the need to create the image array, and another step where things could get screwed up.
$("img").each(function(){
var imgsrc = $(this).attr('src');
if(imgsrc.match('_th.jpg') || imgsrc.match('_home.jpg')){
imgsrc = thumbToLarge(imgsrc);
(new Image()).src = imgsrc;
}
});
Basically, for each image on the page it grabs the src of each image, if it matches certain criteria (is a thumb, or home page image) it changes the name(a basic string replace in the image src), then loads the images.
In my case the page was full of thumb images all named something like image_th.jpg, and all the corresponding large images are named image_lg.jpg. The thumb to large just replaces the _th.jpg with _lg.jpg and then preloads all the large images.
Hope this helps someone.
Here's a cross-browser CSS-only solution. Hope it helps!
.progress .progress-bar {_x000D_
-moz-animation-name: animateBar;_x000D_
-moz-animation-iteration-count: 1;_x000D_
-moz-animation-timing-function: ease-in;_x000D_
-moz-animation-duration: .4s;_x000D_
_x000D_
-webkit-animation-name: animateBar;_x000D_
-webkit-animation-iteration-count: 1;_x000D_
-webkit-animation-timing-function: ease-in;_x000D_
-webkit-animation-duration: .4s;_x000D_
_x000D_
animation-name: animateBar;_x000D_
animation-iteration-count: 1;_x000D_
animation-timing-function: ease-in;_x000D_
animation-duration: .4s;_x000D_
}_x000D_
_x000D_
@-moz-keyframes animateBar {_x000D_
0% {-moz-transform: translateX(-100%);}_x000D_
100% {-moz-transform: translateX(0);}_x000D_
}_x000D_
@-webkit-keyframes animateBar {_x000D_
0% {-webkit-transform: translateX(-100%);}_x000D_
100% {-webkit-transform: translateX(0);}_x000D_
}_x000D_
@keyframes animateBar {_x000D_
0% {transform: translateX(-100%);}_x000D_
100% {transform: translateX(0);}_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="container">_x000D_
_x000D_
<h3>Progress bar animation on load</h3>_x000D_
_x000D_
<div class="progress">_x000D_
<div class="progress-bar progress-bar-success" style="width: 75%;"></div>_x000D_
</div>_x000D_
</div>
_x000D_
I found the solution to this problem here: http://www.hildeberto.com/2008/05/hibernate-and-jersey-conflict-on.html
First represent the epoch of the millisecond time as a date (usually 1/1/1970), then add your millisecond time divided by the number of milliseconds in a day (86400000):
=DATE(1970,1,1)+(A1/86400000)
If your cell is properly formatted, you should see a human-readable date/time.
After an activity started, restarted (onRestart() happens before onStart()), or paused (onPause()), onResume() called. When the activity is in the state of onResume(), the activity is ready to be used by the app user.
I have studied the activity lifecycle a little bit, and here's my understanding of this topic: If you want to restart the activity (A) at the end of the execution of another, there could be a few different cases.
The other activity (B) has been paused and/or stopped or destroyed, and the activity A possibly had been paused (onPause()), in this case, activity A will call onResume()
The activity B has been paused and/or stopped or destroyed, the activity A possibly had been stopped (onStop()) due to memory thing, in this case, activity A will call onRestart() first, onStart() second, then onResume()
The activity B has been paused and/or stopped or destroyed, the activity A has been destroyed, the programmer can call onStart() manually to start the activity first, then onResume() because when an activity is in the destroyed status the activity has not started, and this happens before the activity being completely removed. If the activity is removed, the activity needs to be created again. Manually calling onStart() I think it's because if the activity not started and it is created, onStart() will be called after onCreate().
If you want to update data, make a data update function and put the function inside the onResume(). Or put a loadData function inside onResume()
It's better to understand the lifecycle with the help of the Activity lifecycle diagram.
I have suffered a similar problem, with a Sub not accessible in runtime, but absolutely legal in editor. It was solved by changing destination Framework from 4.5.1 to 4.5. It seems that my IIS only had 4.5 version.
:)
no need for the padding or the corners.
here's a sample:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
<gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF"
android:angle="270"/>
</shape>
based on :
If the pages are blank coming from SSRS, you need to tweak your report layout. This will be far more efficient than running the output through and post process to repair the side effects of a layout problem.
SSRS is very finicky when it comes to pushing the boundaries of the margins. It is easy to accidentally widen/lengthen the report just by adjusting text box or other control on the report. Check the width and height property of the report surface carefully and squeeze them as much as possible. Watch out for large headers and footers.
For Ubuntu 17.0 +
Adding to @netcoder answer above, If you are using Ubuntu 17+, installing libcurl header files is half of the solution. The installation path in ubuntu 17.0+ is different than the installation path in older Ubuntu version. After installing libcurl, you will still get the "cURL not found" error. You need to perform one extra step (as suggested by @minhajul in the OP comment section).
Add a symlink in /usr/include of the cURL installation folder (cURL installation path in Ubuntu 17.0.4 is /usr/include/x86_64-linux-gnu/curl).
My server was running Ubuntu 17.0.4, the commands to enable cURL support were
sudo apt-get install libcurl4-gnutls-dev
Then create a link to cURL installation
cd /usr/include
sudo ln -s x86_64-linux-gnu/curl
After reading this tutorial, I tried to implement it to my program.
I have 4-5 files that contain addresses. Each file has approx 30 million records. I am using the same configuration that you are suggesting but my number of INSERTs per second is way low (~10.000 records per sec).
Here is where your suggestion fails. You use a single transaction for all the records and a single insert with no errors/fails. Let's say that you are splitting each record into multiple inserts on different tables. What happens if the record is broken?
The ON CONFLICT command does not apply, cause if you have 10 elements in a record and you need each element inserted to a different table, if element 5 gets a CONSTRAINT error, then all previous 4 inserts need to go too.
So here is where the rollback comes. The only issue with the rollback is that you lose all your inserts and start from the top. How can you solve this?
My solution was to use multiple transactions. I begin and end a transaction every 10.000 records (Don't ask why that number, it was the fastest one I tested). I created an array sized 10.000 and insert the successful records there. When the error occurs, I do a rollback, begin a transaction, insert the records from my array, commit and then begin a new transaction after the broken record.
This solution helped me bypass the issues I have when dealing with files containing bad/duplicate records (I had almost 4% bad records).
The algorithm I created helped me reduce my process by 2 hours. Final loading process of file 1hr 30m which is still slow but not compared to the 4hrs that it initially took. I managed to speed the inserts from 10.000/s to ~14.000/s
If anyone has any other ideas on how to speed it up, I am open to suggestions.
UPDATE:
In Addition to my answer above, you should keep in mind that inserts per second depending on the hard drive you are using too. I tested it on 3 different PCs with different hard drives and got massive differences in times. PC1 (1hr 30m), PC2 (6hrs) PC3 (14hrs), so I started wondering why would that be.
After two weeks of research and checking multiple resources: Hard Drive, Ram, Cache, I found out that some settings on your hard drive can affect the I/O rate. By clicking properties on your desired output drive you can see two options in the general tab. Opt1: Compress this drive, Opt2: Allow files of this drive to have contents indexed.
By disabling these two options all 3 PCs now take approximately the same time to finish (1hr and 20 to 40min). If you encounter slow inserts check whether your hard drive is configured with these options. It will save you lots of time and headaches trying to find the solution
Hibernate logging has to be also enabled in hibernate configuration.
Add lines
hibernate.show_sql=true
hibernate.format_sql=true
either to
server\default\deployers\ejb3.deployer\META-INF\jpa-deployers-jboss-beans.xml
or to application's persistence.xml
in <persistence-unit><properties>
tag.
Anyway hibernate logging won't include (in useful form) info on actual prepared statements' parameters.
There is an alternative way of using log4jdbc for any kind of sql logging.
The above answer assumes that you run the code that uses hibernate on JBoss, not in IDE. In this case you should configure logging also on JBoss in server\default\deploy\jboss-logging.xml, not in local IDE classpath.
Note that JBoss 6 doesn't use log4j by default. So adding log4j.properties to ear won't help. Just try to add to jboss-logging.xml:
<logger category="org.hibernate">
<level name="DEBUG"/>
</logger>
Then change threshold for root logger. See SLF4J logger.debug() does not get logged in JBoss 6.
If you manage to debug hibernate queries right from IDE (without deployment), then you should have log4j.properties, log4j, slf4j-api and slf4j-log4j12 jars on classpath. See http://www.mkyong.com/hibernate/how-to-configure-log4j-in-hibernate-project/.
In controller you can use MvcHtmlString
public class HomeController : Controller
{
public ActionResult Index()
{
string rawHtml = "<HTML></HTML>";
ViewBag.EncodedHtml = MvcHtmlString.Create(rawHtml);
return View();
}
}
In your View you can simply use that dynamic property which you set in your Controller like below
<div>
@ViewBag.EncodedHtml
</div>
Actually the enhanced for loop should look like this
for (final Room room : rooms) {
// Here your room is available
}
Following are the build-in constants you can use as per your requirements for getting the paths in Codeigniter:
EXT: The PHP file extension
FCPATH: Path to the front controller (this file) (root of CI)
SELF: The name of THIS file (index.php)
BASEPATH: Path to the system folder
APPPATH: The path to the “application” folder
Thanks.
To enable Zombie logging double-click the executable in the executables group of your Xcode project. At this point click the Arguments tab and in the Variables to be set in the environment:
section, make a variable called NSZombieEnabled
and set its value to YES
.
To get something like this
with Bootstrap 3 and Jquery use the following HTML code:
<div class="btn-group">
<input id="searchinput" type="search" class="form-control">
<span id="searchclear" class="glyphicon glyphicon-remove-circle"></span>
</div>
and some CSS:
#searchinput {
width: 200px;
}
#searchclear {
position: absolute;
right: 5px;
top: 0;
bottom: 0;
height: 14px;
margin: auto;
font-size: 14px;
cursor: pointer;
color: #ccc;
}
and Javascript:
$("#searchclear").click(function(){
$("#searchinput").val('');
});
Of course you have to write more Javascript for whatever functionality you need, e.g. to hide the 'x' if the input is empty, make Ajax requests and so on. See http://www.bootply.com/121508
The following command line JMX utilities are available:
Groovy JMX Example:
import java.lang.management.*
import javax.management.ObjectName
import javax.management.remote.JMXConnectorFactory as JmxFactory
import javax.management.remote.JMXServiceURL as JmxUrl
def serverUrl = 'service:jmx:rmi:///jndi/rmi://localhost:9003/jmxrmi'
String beanName = "com.webwars.gameplatform.data:type=udmdataloadsystem,id=0"
def server = JmxFactory.connect(new JmxUrl(serverUrl)).MBeanServerConnection
def dataSystem = new GroovyMBean(server, beanName)
println "Connected to:\n$dataSystem\n"
println "Executing jmxForceRefresh()"
dataSystem.jmxForceRefresh();
cmdline-jmxclient example:
If you have an
With an Operation called:
Then you can write a simple bash script (assuming you download cmdline-jmxclient-0.10.3.jar and put in the same directory as your script):
#!/bin/bash
cmdLineJMXJar=./cmdline-jmxclient-0.10.3.jar
user=yourUser
password=yourPassword
jmxHost=localhost
port=9003
#No User and password so pass '-'
echo "Available Operations for com.company.data:type=datasystem,id=0"
java -jar ${cmdLineJMXJar} ${user}:${password} ${jmxHost}:${port} com.company.data:type=datasystem,id=0
echo "Executing XML update..."
java -jar ${cmdLineJMXJar} - ${jmxHost}:${port} com.company.data:type=datasystem,id=0 jmxForceRefresh
How do I run an executable JAR file? If you have a jar file called Example.jar, follow these rules:
Open a notepad.exe.
Write : java -jar Example.jar.
Save it with the extension .bat.
Copy it to the directory which has the .jar file.
Double click it to run your .jar file.
There's also the Event.eventPhase
property which can tell you if the event is at target or comes from somewhere else, and it is fully supported by browsers.
Expanding on the already great snippet from the accepted answer, this is the output using the eventPhase
property
var logElement = document.getElementById('log');
function log(msg) {
if (logElement.innerHTML == "<p>No logs</p>")
logElement.innerHTML = "";
logElement.innerHTML += ('<p>' + msg + '</p>');
}
function humanizeEvent(eventPhase){
switch(eventPhase){
case 1: //Event.CAPTURING_PHASE
return "Event is being propagated through the target's ancestor objects";
case 2: //Event.AT_TARGET
return "The event has arrived at the event's target";
case 3: //Event.BUBBLING_PHASE
return "The event is propagating back up through the target's ancestors in reverse order";
}
}
function capture(e) {
log('capture: ' + this.firstChild.nodeValue.trim() + "; " +
humanizeEvent(e.eventPhase));
}
function bubble(e) {
log('bubble: ' + this.firstChild.nodeValue.trim() + "; " +
humanizeEvent(e.eventPhase));
}
var divs = document.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
divs[i].addEventListener('click', capture, true);
divs[i].addEventListener('click', bubble, false);
}
_x000D_
p {
line-height: 0;
}
div {
display:inline-block;
padding: 5px;
background: #fff;
border: 1px solid #aaa;
cursor: pointer;
}
div:hover {
border: 1px solid #faa;
background: #fdd;
}
_x000D_
<div>1
<div>2
<div>3
<div>4
<div>5</div>
</div>
</div>
</div>
</div>
<button onclick="document.getElementById('log').innerHTML = '<p>No logs</p>';">Clear logs</button>
<section id="log"></section>
_x000D_
A good logic for your application could be something like:
public function uploadGalery(Request $request){
$this->validate($request, [
'file' => 'required|image|mimes:jpeg,png,jpg,bmp,gif,svg|max:2048',
]);
if ($request->hasFile('file')) {
$image = $request->file('file');
$name = time().'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/storage/galeryImages/');
$image->move($destinationPath, $name);
$this->save();
return back()->with('success','Image Upload successfully');
}
}
Run Developer Command Prompt For V2012 or any version installed in your system
gacutil /i pathofDll
Enter
Done!!!
Reading files using Java NIO's FileChannel and MappedByteBuffer will most likely result in a solution that will be much faster than any solution involving FileInputStream. Basically, memory-map large files, and use direct buffers for small ones.
Option 1: Discard tracked and untracked file changes
Discard changes made to both staged and unstaged files.
$ git reset --hard [HEAD]
Then discard (or remove) untracked files altogether.
$ git clean [-f]
Option 2: Stash
You can first stash your changes
$ git stash
And then either drop or pop it depending on what you want to do. See https://git-scm.com/docs/git-stash#_synopsis.
Option 3: Manually restore files to original state
First we switch to the target branch
$ git checkout <branch-name>
List all files that have changes
$ git status
Restore each file to its original state manually
$ git restore <file-path>
Try this small lib, works with Angular 5.0.0
Quickstart example with ng2-file-upload 1.3.0:
User clicks custom button, which triggers upload dialog from hidden input type="file" , uploading started automatically after selecting single file.
app.module.ts:
import {FileUploadModule} from "ng2-file-upload";
your.component.html:
...
<button mat-button onclick="document.getElementById('myFileInputField').click()" >
Select and upload file
</button>
<input type="file" id="myFileInputField" ng2FileSelect [uploader]="uploader" style="display:none">
...
your.component.ts:
import {FileUploader} from 'ng2-file-upload';
...
uploader: FileUploader;
...
constructor() {
this.uploader = new FileUploader({url: "/your-api/some-endpoint"});
this.uploader.onErrorItem = item => {
console.error("Failed to upload");
this.clearUploadField();
};
this.uploader.onCompleteItem = (item, response) => {
console.info("Successfully uploaded");
this.clearUploadField();
// (Optional) Parsing of response
let responseObject = JSON.parse(response) as MyCustomClass;
};
// Asks uploader to start upload file automatically after selecting file
this.uploader.onAfterAddingFile = fileItem => this.uploader.uploadAll();
}
private clearUploadField(): void {
(<HTMLInputElement>window.document.getElementById('myFileInputField'))
.value = "";
}
Alternative lib, works in Angular 4.2.4, but requires some workarounds to adopt to Angular 5.0.0
You should look here: https://stackoverflow.com/questions/159025/jquery-grid-recommendations
Update
The link above takes to a question that was closed and then deleted. Here are the original suggestions that were on the most voted answer:
new FileOutputStream(f)
will create a file in most cases, but unfortunately you will get a FileNotFoundException
if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason
I other word there might be plenty of cases where you would get FileNotFoundException meaning "Could not create your file", but you would not be able to find the reason of why the file creation failed.
A solution is to remove any call to the File API and use the Files API instead as it provides much better error handling. Typically replace any new FileOutputStream(f)
with Files.newOutputStream(p)
.
In cases where you do need to use the File API (because you use an external interface using File for example), using Files.createFile(p)
is a good way to make sure your file is created properly and if not you would know why it didn't work. Some people commented above that this is redundant. It is true, but you get better error handling which might be necessary in some cases.
I needed to correct the privileges.REVOKE ALL PRIVILEGES ON
logs.* FROM 'root'@'root'; GRANT ALL PRIVILEGES ON
logs.* TO 'root'@'root'WITH GRANT OPTION;
U can use this Edittext....This will help you.
<EditText
android:id="@+id/EditText02"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:lines="5"
android:gravity="top|left"
android:inputType="textMultiLine" />
To use Glassfish tools with Eclipse Luna you need Java 8. I also faced this problem because I had Java 7. If you have Java 7 in your environment then download eclipse Kepler. It will work fine.
Make the exception happen like this:
when(obj.someMethod()).thenThrow(new AnException());
Verify it has happened either by asserting that your test will throw such an exception:
@Test(expected = AnException.class)
Or by normal mock verification:
verify(obj).someMethod();
The latter option is required if your test is designed to prove intermediate code handles the exception (i.e. the exception won't be thrown from your test method).
I wanted to be able to access my application with the HTML5 mode and a fixed token and then switch to the hashbang method (to keep the token so the user can refresh his page).
URL for accessing my app:
http://myapp.com/amazing_url?token=super_token
Then when the user loads the page:
http://myapp.com/amazing_url?token=super_token#/amazing_url
Then when the user navigates:
http://myapp.com/amazing_url?token=super_token#/another_url
With this I keep the token in the URL and keep the state when the user is browsing. I lost a bit of visibility of the URL, but there is no perfect way of doing it.
So don't enable the HTML5 mode and then add this controller:
.config ($stateProvider)->
$stateProvider.state('home-loading', {
url: '/',
controller: 'homeController'
})
.controller 'homeController', ($state, $location)->
if window.location.pathname != '/'
$location.url(window.location.pathname+window.location.search).replace()
else
$state.go('home', {}, { location: 'replace' })
This is a simple example.
SELECT HEX(some_col) h
FROM some_table
ORDER BY h
When you open a folder in VSCode, it will automatically scan the folder for typical project artifacts like project.json or solution files. From the status bar in the lower left side you can switch between solutions and projects.
There is no need to destroy current instance, just refresh.
$('#datepicker')
.datepicker('option', 'minDate', new Date)
.datepicker('refresh');
You could just use a margin-left with a percentage.
HTML
<div class="goleft">Left Div</div>
<div class="goright">Right Div</div>
CSS
.goright{
margin-left:20%;
}
.goleft{
margin-right:20%;
}
(goleft would be the same as default, but can reverse if needed)
text-align doesn't always work as intended for layout options, it's mainly just for text. (But is often used for form elements too).
The end result of doing this will have a similar effect to a div with float:right; and width:80% set. Except, it won't clump together like a float will. (Saving the default display properties for the elements that come after).
Working syntax for multiple optional params:
<Route path="/section/(page)?/:page?/(sort)?/:sort?" component={Section} />
Now, url can be:
be careful using isinstance
isinstance(True, bool)
True
>>> isinstance(True, int)
True
but type
type(True) == bool
True
>>> type(True) == int
False
Why "Accepted Answer" works... but it wasn't enough for me
This works in the specification. At least swagger-tools
(version 0.10.1) validates it as a valid.
But if you are using other tools like swagger-codegen
(version 2.1.6) you will find some difficulties, even if the client generated contains the Authentication definition, like this:
this.authentications = {
'Bearer': {type: 'apiKey', 'in': 'header', name: 'Authorization'}
};
There is no way to pass the token into the header before method(endpoint) is called. Look into this function signature:
this.rootGet = function(callback) { ... }
This means that, I only pass the callback (in other cases query parameters, etc) without a token, which leads to a incorrect build of the request to server.
My alternative
Unfortunately, it's not "pretty" but it works until I get JWT Tokens support on Swagger.
Note: which is being discussed in
So, it's handle authentication like a standard header. On path
object append an header paremeter:
swagger: '2.0'
info:
version: 1.0.0
title: Based on "Basic Auth Example"
description: >
An example for how to use Auth with Swagger.
host: localhost
schemes:
- http
- https
paths:
/:
get:
parameters:
-
name: authorization
in: header
type: string
required: true
responses:
'200':
description: 'Will send `Authenticated`'
'403':
description: 'You do not have necessary permissions for the resource'
This will generate a client with a new parameter on method signature:
this.rootGet = function(authorization, callback) {
// ...
var headerParams = {
'authorization': authorization
};
// ...
}
To use this method in the right way, just pass the "full string"
// 'token' and 'cb' comes from elsewhere
var header = 'Bearer ' + token;
sdk.rootGet(header, cb);
And works.
You can do a reverse DNS lookup with host
, too. Just give it the IP address as an argument:
$ host 192.168.0.10
server10 has address 192.168.0.10
The various provided answers are wrong for numerous reasons, primarily from misunderstanding what a palindrome is. The majority only properly identify a subset of palindromes.
From Merriam-Webster
A word, verse, or sentence (such as "Able was I ere I saw Elba")
And from Wordnik
A word, phrase, verse, or sentence that reads the same backward or forward. For example: A man, a plan, a canal, Panama!
Consider non-trivial palindromes such as "Malayalam" (it's a proper language, so naming rules apply, and it should be capitalized), or palindromic sentences such as "Was it a car or a cat I saw?" or "No 'X' in Nixon".
These are recognized palindromes in any literature.
I'm lifting the thorough solution from a library providing this kind of stuff that I'm the primary author of, so the solution works for both String
and ReadOnlySpan<Char>
because that's a requirement I've imposed on the library. The solution for purely String
will be easy to determine from this, however.
public static Boolean IsPalindrome(this String @string) =>
!(@string is null) && @string.AsSpan().IsPalindrome();
public static Boolean IsPalindrome(this ReadOnlySpan<Char> span) {
// First we need to build the string without any punctuation or whitespace or any other
// unrelated-to-reading characters.
StringBuilder builder = new StringBuilder(span.Length);
foreach (Char s in span) {
if (!(s.IsControl()
|| s.IsPunctuation()
|| s.IsSeparator()
|| s.IsWhiteSpace()) {
_ = builder.Append(s);
}
}
String prepped = builder.ToString();
String reversed = prepped.Reverse().Join();
// Now actually check it's a palindrome
return String.Equals(prepped, reversed, StringComparison.CurrentCultureIgnoreCase);
}
You're going to want variants of this that accept a CultureInfo
parameter as well, when you're testing a specific language rather than your own language, by instead calling .ToUpper(cultureInfo)
on prepped
.
And here's proof from the projects unit tests that it works.
The color you are using is white "#ffffff" is white so try a different one change in the values if you want until you get your need from this link Color Codes and it should go fine
git-pull - Fetch from and integrate with another repository or a local branch GIT PULL
Basically you are pulling remote branch to your local, example:
git pull origin master
Will pull master branch into your local repository
git-rebase - Forward-port local commits to the updated upstream head GIT REBASE
This one is putting your local changes on top of changes done remotely by other users. For example:
SOME-FEATURE
Now you want to see his and your changes on your local branch.
So then you checkout master
branch:
git checkout master
then you can pull:
git pull origin master
and then you go to your branch:
git checkout SOME-FEATURE
and you can do rebase master
to get lastest changes from it and put your branch commits on top:
git rebase master
I hope now it's a bit more clear for you.
A simple way using std::next_permutation
:
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
int n, r;
std::cin >> n;
std::cin >> r;
std::vector<bool> v(n);
std::fill(v.end() - r, v.end(), true);
do {
for (int i = 0; i < n; ++i) {
if (v[i]) {
std::cout << (i + 1) << " ";
}
}
std::cout << "\n";
} while (std::next_permutation(v.begin(), v.end()));
return 0;
}
or a slight variation that outputs the results in an easier to follow order:
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
int n, r;
std::cin >> n;
std::cin >> r;
std::vector<bool> v(n);
std::fill(v.begin(), v.begin() + r, true);
do {
for (int i = 0; i < n; ++i) {
if (v[i]) {
std::cout << (i + 1) << " ";
}
}
std::cout << "\n";
} while (std::prev_permutation(v.begin(), v.end()));
return 0;
}
A bit of explanation:
It works by creating a "selection array" (v
), where we place r
selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v
.
You can implement it if you note that for each level r you select a number from 1 to n.
In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance
#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>
using namespace std;
struct combinations
{
typedef vector<int> combination_t;
// initialize status
combinations(int N, int R) :
completed(N < 1 || R > N),
generated(0),
N(N), R(R)
{
for (int c = 1; c <= R; ++c)
curr.push_back(c);
}
// true while there are more solutions
bool completed;
// count how many generated
int generated;
// get current and compute next combination
combination_t next()
{
combination_t ret = curr;
// find what to increment
completed = true;
for (int i = R - 1; i >= 0; --i)
if (curr[i] < N - R + i + 1)
{
int j = curr[i] + 1;
while (i <= R-1)
curr[i++] = j++;
completed = false;
++generated;
break;
}
return ret;
}
private:
int N, R;
combination_t curr;
};
int main(int argc, char **argv)
{
int N = argc >= 2 ? atoi(argv[1]) : 5;
int R = argc >= 3 ? atoi(argv[2]) : 2;
combinations cs(N, R);
while (!cs.completed)
{
combinations::combination_t c = cs.next();
copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
cout << endl;
}
return cs.generated;
}
test output:
1,2,
1,3,
1,4,
1,5,
2,3,
2,4,
2,5,
3,4,
3,5,
4,5,
Simply call InetAddress.getByName(String host)
passing in your textual IP address.
From the javadoc: The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address.
I had the same problem under Windows and could solve it by running cmd.exe as administrator (right-click in start menu, then "Run as administrator).
All these answers around here, as well as the answers in this question, suggest that loading absolute URLs, like "/foo/bar.properties" treated the same by class.getResourceAsStream(String)
and class.getClassLoader().getResourceAsStream(String)
. This is NOT the case, at least not in my Tomcat configuration/version (currently 7.0.40).
MyClass.class.getResourceAsStream("/foo/bar.properties"); // works!
MyClass.class.getClassLoader().getResourceAsStream("/foo/bar.properties"); // does NOT work!
Sorry, I have absolutely no satisfying explanation, but I guess that tomcat does dirty tricks and his black magic with the classloaders and cause the difference. I always used class.getResourceAsStream(String)
in the past and haven't had any problems.
PS: I also posted this over here
array_slice() is best thing to try, following are the examples:
<?php
$input = array("a", "b", "c", "d", "e");
$output = array_slice($input, 2); // returns "c", "d", and "e"
$output = array_slice($input, -2, 1); // returns "d"
$output = array_slice($input, 0, 3); // returns "a", "b", and "c"
// note the differences in the array keys
print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));
?>
If you have a small number of values to auto complete, you can simply add them in xaml. Typing will invoke auto-complete, plus you have dropdowns too.
<ComboBox Text="{Binding CheckSeconds, UpdateSourceTrigger=PropertyChanged}"
IsEditable="True">
<ComboBoxItem Content="60"/>
<ComboBoxItem Content="120"/>
<ComboBoxItem Content="180"/>
<ComboBoxItem Content="300"/>
<ComboBoxItem Content="900"/>
</ComboBox>
Or you could nest the data in cols 4 and 5 into a single row with tidyr
:
library(tidyr)
df %>% nest(V4:V5)
# A tibble: 1 × 4
# V1 V2 V3 data
# <fctr> <int> <int> <list>
#1 platform_external_dbus 202 16 <tibble [5 × 2]>
The col 2 and 3 duplicates are now removed for statistical analysis, but you have kept the col 4 and 5 data in a tibble and can go back to the original data frame at any point with unnest()
.
There's not a good way to convert it to foreach, because mysql_fetch_array()
just fetches the next result from $result_select
. If you really wanted to foreach, you could do pull all the results into an array first, doing something like the following:
$result_list = array();
while($row = mysql_fetch_array($result_select)) {
result_list[] = $row;
}
foreach($result_list as $row) {
...
}
But there's no good reason I can see to do that - and you still have to use the while loop, which is unavoidable due to how mysql_fetch_array()
works. Why is it so important to use a foreach()?
EDIT: If this is just for learning purposes: you can't convert this to a foreach
. You have to have a pre-existing array to use a foreach()
instead of a while()
, and mysql_fetch_array()
fetches one result per call - there's no pre-existing array for foreach()
to iterate through.
If you mean VBA, then you can use FullName, for example:
strFileFullName = ThisWorkbook.FullName
(updated as considered by the comments: the former used ActiveWorkbook.FullName
could more likely be wrong, if other office files may be open(ed) and active. But in case you stored the macro in another file, as mentioned by user @user7296559 here, and really want the file name of the macro-using file, ActiveWorkbook
could be the correct choice, if it is guaranteed to be active at execution time.)
The problem is that the evaluation of Click()
times out on your build env.. you might want to dig into what happens on Click()
.
Also, try adding Retrys for the Click()
because occssionally the evaluations take longer time depending on network speeds, etc
You can use arrows
:
arrows(x,y-sd,x,y+sd, code=3, length=0.02, angle = 90)
<?php
if (isset($_POST['birthdate'])) {
$timestamp = strtotime($_POST['birthdate']);
$date=date('d',$timestamp);
$month=date('m',$timestamp);
$year=date('Y',$timestamp);
}
?>
All you need to do is:
Build the mainjava class using the class path if any (optional)
javac *.java [ -cp "wb.jar;"]
Create Manifest.txt file with content is:
Main-Class: mainjava
Package the jar file for mainjava class
jar cfm mainjava.jar Manifest.txt *.class
Then you can run this .jar file from cmd with class path (optional) and put arguments for it.
java [-cp "wb.jar;"] mainjava arg0 arg1
HTH.
In addition to the existing answers, Overridden functions are in different scopes; whereas overloaded functions are in same scope.
What are you doing: (I am using bytes instead of in for better reading)
You start with int *ap
and so on, so your (your computers) memory looks like this:
-------------- memory used by some one else --------
000: ?
001: ?
...
098: ?
099: ?
-------------- your memory --------
100: something <- here is *ap
101: 41 <- here starts a[]
102: 42
103: 43
104: 44
105: 45
106: something <- here waits x
lets take a look waht happens when (print short cut for ...print("$d", ...)
print a[0] -> 41 //no surprise
print a -> 101 // because a points to the start of the array
print *a -> 41 // again the first element of array
print a+1 -> guess? 102
print *(a+1) -> whats behind 102? 42 (we all love this number)
and so on, so a[0] is the same as *a, a[1] = *(a+1), ....
a[n] just reads easier.
now, what happens at line 9?
ap=a[4] // we know a[4]=*(a+4) somehow *105 ==> 45
// warning! converting int to pointer!
-------------- your memory --------
100: 45 <- here is *ap now 45
x = *ap; // wow ap is 45 -> where is 45 pointing to?
-------------- memory used by some one else --------
bang! // dont touch neighbours garden
So the "warning" is not just a warning it's a severe error.
There are a lot of good answers here but I noticed something was missing. Most answers seem to be implying that the reason why people use Big O over Big Theta is a difficulty issue, and in some cases this may be true. Often a proof that leads to a Big Theta result is far more involved than one that results in Big O. This usually holds true, but I do not believe this has a large relation to using one analysis over the other.
When talking about complexity we can say many things. Big O time complexity is just telling us what an algorithm is guarantied to run within, an upper bound. Big Omega is far less often discussed and tells us the minimum time an algorithm is guarantied to run, a lower bound. Now Big Theta tells us that both of these numbers are in fact the same for a given analysis. This tells us that the application has a very strict run time, that can only deviate by a value asymptoticly less than our complexity. Many algorithms simply do not have upper and lower bounds that happen to be asymptoticly equivalent.
So as to your question using Big O in place of Big Theta would technically always be valid, while using Big Theta in place of Big O would only be valid when Big O and Big Omega happened to be equal. For instance insertion sort has a time complexity of Big ? at n^2, but its best case scenario puts its Big Omega at n. In this case it would not be correct to say that its time complexity is Big Theta of n or n^2 as they are two different bounds and should be treated as such.
You can use RETURN
to stop execution of a stored procedure immediately. Quote taken from Books Online:
Exits unconditionally from a query or procedure. RETURN is immediate and complete and can be used at any point to exit from a procedure, batch, or statement block. Statements that follow RETURN are not executed.
Out of paranoia, I tried yor example and it does output the PRINTs and does stop execution immediately.
I got the same error. In the terminal when I typed "python filename.py", with this command, python2 was tring to run python3 code, because the is written python3. It runs correctly when I type "python3 filename.py" in the terminal. I hope this works for you too.
The textPath may be good for some case.
<svg width="200" height="200"
xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<!-- define lines for text lies on -->
<path id="path1" d="M10,30 H190 M10,60 H190 M10,90 H190 M10,120 H190"></path>
</defs>
<use xlink:href="#path1" x="0" y="35" stroke="blue" stroke-width="1" />
<text transform="translate(0,35)" fill="red" font-size="20">
<textPath xlink:href="#path1">This is a long long long text ......</textPath>
</text>
</svg>
There's no built-in JavaScript function to do this, but you can write your own fairly easily:
function pad(n) {
return (n < 10) ? ("0" + n) : n;
}
Meanwhile there is a native JS function that does that. See String#padStart
console.log(String(5).padStart(2, '0'));
_x000D_
var idPost=document.getElementById("status").innerHTML;
The 'status' element does not exist in your webpage.
So document.getElementById("status") return null. While you can not use innerHTML property of NULL.
You should add a condition like this:
if(document.getElementById("status") != null){
var idPost=document.getElementById("status").innerHTML;
}
Hope this answer can help you. :)
From the answer here, spark.sql.shuffle.partitions
configures the number of partitions that are used when shuffling data for joins or aggregations.
spark.default.parallelism
is the default number of partitions in RDD
s returned by transformations like join
, reduceByKey
, and parallelize
when not set explicitly by the user. Note that spark.default.parallelism
seems to only be working for raw RDD
and is ignored when working with dataframes.
If the task you are performing is not a join or aggregation and you are working with dataframes then setting these will not have any effect. You could, however, set the number of partitions yourself by calling df.repartition(numOfPartitions)
(don't forget to assign it to a new val
) in your code.
To change the settings in your code you can simply do:
sqlContext.setConf("spark.sql.shuffle.partitions", "300")
sqlContext.setConf("spark.default.parallelism", "300")
Alternatively, you can make the change when submitting the job to a cluster with spark-submit
:
./bin/spark-submit --conf spark.sql.shuffle.partitions=300 --conf spark.default.parallelism=300
I had the same problem. I solve it when I convert string to factor. In your case, check the class of variable and check if they are numeric and 'train and test' should be factor.
Quite an old question, but might be helpful to somebody in need.
If you know the url, 1. open the chrome browser, 2. open developer tools in chrome , 3. Put the url in search bar and hit enter 4. look in network tab, you will see the ip and port both
I couldn't get your method to work @Damien-at-SF...
So I resorted to my old knowledge.
By encasing the input type="button" within a hyperlink element, you can simply declare the target property as so:
<a href="http://www.site.org" target="_blank">
<input type="button" class="button" value="Open" />
</a>
The 'target="_blank"' is the property which makes the browser open the link within a new tab. This attribute has other properties, See: http://www.w3schools.com/tags/att_a_target.asp for further details.
Since the 'value=""' attribute on buttons will write the contained string to the button, a span is not necessary.
Instead of writing:
<element></element>
for most HTML elements you can simply close them with a trailing slash, like so:
<element />
Oh, and finally... a 'button' element has a refresh trigger within it, so I use an 'input type[button]' to avoid triggering the form.
Good Luck Programmers.
Due to StackOverflow's policy I had to change the domain in the example: https://meta.stackexchange.com/questions/208963/why-are-certain-example-urls-like-http-site-com-and-http-mysite-com-blocke
To do POST you'll need to have a form.
<form action="employee.action" method="post">
<input type="submit" value="Employee1" />
</form>
There are some ways to post data with hyperlinks, but you'll need some javascript, and a form.
Some tricks: Make a link use POST instead of GET and How do you post data with a link
Edit: to load response on a frame you can target your form to your frame:
<form action="employee.action" method="post" target="myFrame">
After trying for several hours, I finally did it.
Make sure that you added the <MONGODB_PATH>\bin
directory to the system variable PATH
First I executed this command:
D:\mongodb\bin>mongod --remove
Then I executed this command after opening command prompt as administrator:
D:\mongodb\bin>mongod --dbpath=D:\mongodb --logpath=D:\mongodb\log.txt --install
After that right there in the command prompt execute:
services.msc
And look for MongoDB service and click start.
If you don't do this, your log file (D:\mongodb\log.txt
in the above example) will contain lines like these:
2016-11-11T15:24:54.618-0800 I CONTROL [main] Trying to install Windows service 'MongoDB'
2016-11-11T15:24:54.618-0800 I CONTROL [main] Error connecting to the Service Control Manager: Access is denied. (5)
and if you try to start the service from a non-admin console, (i.e. net start MongoDB
or Start-Service MongoDB
in PowerShell), you'll get a response like this:
System error 5 has occurred.
Access is denied.
or this:
Start-Service : Service 'MongoDB (MongoDB)' cannot be started due to the following error: Cannot open MongoDB service
on computer '.'.
At line:1 char:1
+ Start-Service MongoDB
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.ServiceProcess.ServiceController:ServiceController) [Start-Service],
ServiceCommandException
+ FullyQualifiedErrorId : CouldNotStartService,Microsoft.PowerShell.Commands.StartServiceComman
use Object.keys:
Object.keys(this.formErrors).map(key => {
this.formErrors[key] = '';
const control = form.get(key);
if(control && control.dirty && !control.valid) {
const messages = this.validationMessages[key];
Object.keys(control.errors).map(key2 => {
this.formErrors[key] += messages[key2] + ' ';
});
}
});
Doxygen or Sandcastle help file builder are the primary tools that will extract XML documentation into HTML (and other forms) of external documentation.
Note that you can combine these documentation exporters with documentation generators - as you've discovered, Resharper has some rudimentary helpers, but there are also much more advanced tools to do this specific task, such as GhostDoc (for C#/VB code with XML documentation) or my addin Atomineer Pro Documentation (for C#, C++/CLI, C++, C, VB, Java, JavaScript, TypeScript, JScript, PHP, Unrealscript code containing XML, Doxygen, JavaDoc or Qt documentation).
try this....
SELECT FORMAT(CAST(DOB AS DATE),'yyyyMMdd') FROM Employees;
I encountered similar issue. The missing artifacts (jar files) exists in ~/.m2 directory and somehow eclipse is unable to find it.
For example: Missing artifact org.jdom:jdom:jar:1.1:compile
I looked through this directory ~/.m2/repository/org/jdom/jdom/1.1 and I noticed there is this file _maven.repositories. I opened it using text editor and saw the following entry:
#NOTE: This is an internal implementation file, its format can be changed without prior notice.
#Wed Feb 13 17:12:29 SGT 2013
jdom-1.1.jar>central=
jdom-1.1.pom>central=
I simply removed the "central" word from the file:
#NOTE: This is an internal implementation file, its format can be changed without prior notice.
#Wed Feb 13 17:12:29 SGT 2013
jdom-1.1.jar>=
jdom-1.1.pom>=
and run Maven > Update Project from eclipse and it just worked :) Note that your file may contain other keyword instead of "central".
If using Datatable > 1.1.0 then lengthChange
option is what you need as below :
$('#example').dataTable( {
"lengthChange": false
});
If you are using a client like MySQL Workbench, right click the desired table from where a foreign key is to be deleted, then select the foreign key tab and delete the indexes.
Then you can run the query like this:
alter table table_name drop foreign_key_col_name;
It sounds to me like you want to be able to easily pass a string created using printf-style formatting to the function you already have that takes a simple string. You can create a wrapper function using stdarg.h
facilities and vsnprintf()
(which may not be readily available, depending on your compiler/platform):
#include <stdarg.h>
#include <stdio.h>
// a function that accepts a string:
void foo( char* s);
// You'd like to call a function that takes a format string
// and then calls foo():
void foofmt( char* fmt, ...)
{
char buf[100]; // this should really be sized appropriately
// possibly in response to a call to vsnprintf()
va_list vl;
va_start(vl, fmt);
vsnprintf( buf, sizeof( buf), fmt, vl);
va_end( vl);
foo( buf);
}
int main()
{
int val = 42;
foofmt( "Some value: %d\n", val);
return 0;
}
For platforms that don't provide a good implementation (or any implementation) of the snprintf()
family of routines, I've successfully used a nearly public domain snprintf()
from Holger Weiss.
npx nodemon (app.js) worked for me and nodemon (app.js) did not.
I updated node.js to the latest version and now both are working.
It's not a better idea to override the core.common file of codeigniter. Because that's the more tested and system files....
I make a solution for this problem. In your ckeditor_helper.php file line- 65
if($k !== end (array_keys($data['config']))) {
$return .= ",";
}
Change this to-->
$segment = array_keys($data['config']);
if($k !== end($segment)) {
$return .= ",";
}
I think this is the best solution and then your problem notice will dissappear.
By using sscanf we can convert string to float.
#include<stdio.h>
#include<string.h>
int main()
{
char str[100] ="4.0800" ;
const char s[2] = "-";
char *token;
double x;
/* get the first token */
token = strtok(str, s);
sscanf(token,"%f",&x);
printf( " %f",x );
return 0;
}
I don't use the same version, but uninstall actions are the same: Looking for file uninstall-postgresql inside directory
/Library/PostgreSQL/9.6
then run it.
(Screenshot in macOS 10.13)
then
sudo rm -rf /Library/PostgreSQL/
to delete all unnecessary directory.
In addition to the anwser of Bill the Lizard:
Most of the backends parse the raw post data. In PHP for example, you will have an array $_POST
in which individual variables within the post data will be stored. In this case you have to use an additional header "Content-type: application/x-www-form-urlencoded"
:
Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
URL = "http://www.somedomain.com"
objHTTP.Open "POST", URL, False
objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
objHTTP.send ("var1=value1&var2=value2&var3=value3")
Otherwise you have to read the raw post data on the variable "$HTTP_RAW_POST_DATA"
.
In your project parent directory, run:
git submodule update --init
Or if you have recursive submodules run:
git submodule update --init --recursive
Sometimes this still doesn't work, because somehow you have local changes in the local submodule directory while the submodule is being updated.
Most of the time the local change might not be the one you want to commit. It can happen due to a file deletion in your submodule, etc. If so, do a reset in your local submodule directory and in your project parent directory, run again:
git submodule update --init --recursive
$string = "233718_This_is_a_string";
$withCharacter = strstr($string, '_'); // "_This_is_a_string"
echo substr($withCharacter, 1); // "This_is_a_string"
In a single statement it would be.
echo substr(strstr("233718_This_is_a_string", '_'), 1); // "This_is_a_string"
SELECT *,
ROW_NUMBER()OVER(ORDER BY CASE WHEN ISNUMERIC (ID)=1 THEN CONVERT(NUMERIC(20,2),SUBSTRING(Id, PATINDEX('%[0-9]%', Id), LEN(Id)))END DESC)Rn ---- numerical
FROM
(
SELECT '1'Id UNION ALL
SELECT '25.20' Id UNION ALL
SELECT 'A115' Id UNION ALL
SELECT '2541' Id UNION ALL
SELECT '571.50' Id UNION ALL
SELECT '67' Id UNION ALL
SELECT 'B48' Id UNION ALL
SELECT '500' Id UNION ALL
SELECT '147.54' Id UNION ALL
SELECT 'A-100' Id
)A
ORDER BY
CASE WHEN ISNUMERIC (ID)=0 /* alphabetical sort */
THEN CASE WHEN PATINDEX('%[0-9]%', Id)=0
THEN LEFT(Id,PATINDEX('%[0-9]%',Id))
ELSE LEFT(Id,PATINDEX('%[0-9]%',Id)-1)
END
END DESC
"project property - CUDA Runtime API - GPU - NVCC Compilation Type"
Set the 64 bit compile option -m64 -cubin
The hint is at compile log. Like this:
nvcc.exe ~~~~~~ -machine 32 -ccbin ~~~~~
That "-machine 32"
is problem.
First set 64bit compile option, next re setting hybrid compile option. Then u can see the succeed.
In Android some permissions <uses-permission>
will imply <uses-feature>
requirements to the app.
For example <uses-permission android:name="android.permission.BLUETOOTH" />
Will imply <uses-feature android:name="android.hardware.bluetooth"/>
You can check the whole list here https://developer.android.com/guide/topics/manifest/uses-feature-element#permissions
As @Nakilon said, their is a comparing tool built in github if that's what you use.
To use it, append the url of the repo with "/compare".
The first value is the precision and the second is the scale, so 18,0
is essentially 18 digits with 0 digits after the decimal place. If you had 18,2
for example, you would have 18 digits, two of which would come after the decimal...
example of 18,2: 1234567890123456.12
There is no functional difference between numeric
and decimal
, other that the name and I think I recall that numeric came first, as in an earlier version.
And to answer, "can I add (-10) in that column?" - Yes, you can.
In your jQuery code there is a comma after the backgroundPosition portion:
backgroundPosition: '-20px 0px',
However, when listing the various properties you want to change in the .animate() method (and similar methods), the last argument listed between curly braces should not have a comma after it. I can't say if that's why the background position isn't getting changed, but it is an error and one I'd suggest fixing.
UPDATE: In the limited testing I've done just now, entering purely numerical values (without "px") works for backgroundPosition in the .animate() method. In other words, this works:
backgroundPosition: '-20 0'
However, this does not:
backgroundPosition: '-20px 0'
Hope this helps.
For example here is a element like button for adding item to basket and appropriate attributes for saving in localStorage.
'<a href="#" cartBtn pr_id='+e.id+' pr_name_en="'+e.nameEn+'" pr_price="'+e.price+'" pr_image="'+e.image+'" class="btn btn-primary"><i class="fa fa-shopping-cart"></i>Add to cart</a>'
var productArray=[];
$(document).on('click','[cartBtn]',function(e){
e.preventDefault();
$(this).html('<i class="fa fa-check"></i>Added to cart');
console.log('Item added ');
var productJSON={"id":$(this).attr('pr_id'), "nameEn":$(this).attr('pr_name_en'), "price":$(this).attr('pr_price'), "image":$(this).attr('pr_image')};
if(localStorage.getObj('product')!==null){
productArray=localStorage.getObj('product');
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
else{
productArray.push(productJSON);
localStorage.setObj('product', productArray);
}
});
Storage.prototype.setObj = function(key, value) {
this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObj = function(key) {
var value = this.getItem(key);
return value && JSON.parse(value);
}
After adding JSON object to Array result is (in LocalStorage):
[{"id":"99","nameEn":"Product Name1","price":"767","image":"1462012597217.jpeg"},{"id":"93","nameEn":"Product Name2","price":"76","image":"1461449637106.jpeg"},{"id":"94","nameEn":"Product Name3","price":"87","image":"1461449679506.jpeg"}]
after this action you can easily send data to server as List in Java
Full code example is here
I solved this error by uninstalling two older SDK build tools versions, leaving only the most recent one.
For xlsx I like the solution posted earlier as https://web.archive.org/web/20180216070531/https://stackoverflow.com/questions/4371163/reading-xlsx-files-using-python. I uses modules from the standard library only.
def xlsx(fname):
import zipfile
from xml.etree.ElementTree import iterparse
z = zipfile.ZipFile(fname)
strings = [el.text for e, el in iterparse(z.open('xl/sharedStrings.xml')) if el.tag.endswith('}t')]
rows = []
row = {}
value = ''
for e, el in iterparse(z.open('xl/worksheets/sheet1.xml')):
if el.tag.endswith('}v'): # Example: <v>84</v>
value = el.text
if el.tag.endswith('}c'): # Example: <c r="A3" t="s"><v>84</v></c>
if el.attrib.get('t') == 's':
value = strings[int(value)]
letter = el.attrib['r'] # Example: AZ22
while letter[-1].isdigit():
letter = letter[:-1]
row[letter] = value
value = ''
if el.tag.endswith('}row'):
rows.append(row)
row = {}
return rows
Improvements added are fetching content by sheet name, using re to get the column and checking if sharedstrings are used.
def xlsx(fname,sheet):
import zipfile
from xml.etree.ElementTree import iterparse
import re
z = zipfile.ZipFile(fname)
if 'xl/sharedStrings.xml' in z.namelist():
# Get shared strings
strings = [element.text for event, element
in iterparse(z.open('xl/sharedStrings.xml'))
if element.tag.endswith('}t')]
sheetdict = { element.attrib['name']:element.attrib['sheetId'] for event,element in iterparse(z.open('xl/workbook.xml'))
if element.tag.endswith('}sheet') }
rows = []
row = {}
value = ''
if sheet in sheets:
sheetfile = 'xl/worksheets/sheet'+sheets[sheet]+'.xml'
#print(sheet,sheetfile)
for event, element in iterparse(z.open(sheetfile)):
# get value or index to shared strings
if element.tag.endswith('}v') or element.tag.endswith('}t'):
value = element.text
# If value is a shared string, use value as an index
if element.tag.endswith('}c'):
if element.attrib.get('t') == 's':
value = strings[int(value)]
# split the row/col information so that the row leter(s) can be separate
letter = re.sub('\d','',element.attrib['r'])
row[letter] = value
value = ''
if element.tag.endswith('}row'):
rows.append(row)
row = {}
return rows
Put this in the App.java:
public static void main(String[] args) throws UnknownHostException {
SpringApplication app = new SpringApplication(App.class);
SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args);
if (!source.containsProperty("spring.profiles.active") &&
!System.getenv().containsKey("SPRING_PROFILES_ACTIVE")) {
app.setAdditionalProfiles("production");
}
...
}
This is how it is done in JHipster
SELECT distinct idCustomer FROM reservations
WHERE DATEPART ( hour, insertDate) < 2
and idCustomer is not null
Make sure your list parameter does not contain null values.
Here's an explanation:
WHERE field1 NOT IN (1, 2, 3, null)
is the same as:
WHERE NOT (field1 = 1 OR field1 = 2 OR field1 = 3 OR field1 = null)
(*) Edit: this explanation is pretty good, but I wish to address one thing to stave off future nit-picking. (TRUE OR NULL) would evaluate to TRUE. This is relevant if field1 = 3, for example. That TRUE value would be negated to FALSE and the row would be filtered.
I don't know of Google voice, but using the javaScript speech SpeechSynthesisUtterance, you can add a click event to the element you are reference to. eg:
const listenBtn = document.getElementById('myvoice');
listenBtn.addEventListener('click', (e) => {
e.preventDefault();
const msg = new SpeechSynthesisUtterance(
"Hello, hope my code is helpful"
);
window.speechSynthesis.speak(msg);
});
_x000D_
<button type="button" id='myvoice'>Listen to me</button>
_x000D_
In your for loop you need to multiply the units * price. That gives you the total for that particular item. Also in the for loop you should add that to a counter that keeps track of the grand total. Your code would look something like
float total;
total += theItem.getUnits() * theItem.getPrice();
total should be scoped so it's accessible from within main unless you want to pass it around between function calls. Then you can either just print out the total or create a method that prints it out for you.
You have to use the FormulaEvaluator, as shown here. This will return a value that is either the value present in the cell or the result of the formula if the cell contains such a formula :
FileInputStream fis = new FileInputStream("/somepath/test.xls");
Workbook wb = new HSSFWorkbook(fis); //or new XSSFWorkbook("/somepath/test.xls")
Sheet sheet = wb.getSheetAt(0);
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
// suppose your formula is in B3
CellReference cellReference = new CellReference("B3");
Row row = sheet.getRow(cellReference.getRow());
Cell cell = row.getCell(cellReference.getCol());
if (cell!=null) {
switch (evaluator.evaluateFormulaCell(cell)) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.println(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
System.out.println(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BLANK:
break;
case Cell.CELL_TYPE_ERROR:
System.out.println(cell.getErrorCellValue());
break;
// CELL_TYPE_FORMULA will never occur
case Cell.CELL_TYPE_FORMULA:
break;
}
}
if you need the exact contant (ie the formla if the cell contains a formula), then this is shown here.
Edit : Added a few example to help you.
first you get the cell (just an example)
Row row = sheet.getRow(rowIndex+2);
Cell cell = row.getCell(1);
If you just want to set the value into the cell using the formula (without knowing the result) :
String formula ="ABS((1-E"+(rowIndex + 2)+"/D"+(rowIndex + 2)+")*100)";
cell.setCellFormula(formula);
cell.setCellStyle(this.valueRightAlignStyleLightBlueBackground);
if you want to change the message if there is an error in the cell, you have to change the formula to do so, something like
IF(ISERR(ABS((1-E3/D3)*100));"N/A"; ABS((1-E3/D3)*100))
(this formula check if the evaluation return an error and then display the string "N/A", or the evaluation if this is not an error).
if you want to get the value corresponding to the formula, then you have to use the evaluator.
Hope this help,
Guillaume
If you also want to match newlines, then you might want to use "^[\s\S]{1,35}$"
(depending on the regex engine). Otherwise, as others have said, you should used "^.{1,35}$"
These methods work, if you already have a .vimrc file:
:scriptnames
list all the .vim files that Vim loaded for you, including your .vimrc
file.
:e $MYVIMRC
open & edit the current .vimrc that you are using, then use Ctrl + G to view the path in status bar.
Use this query to create the new table with the values from existing table
CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name;
Now you can get all the values from existing table into newly created table.
Use the Twitter Intent resource https://dev.twitter.com/web/tweet-button/web-intent
Try this to check
$('#captureImage').attr("checked",true).checkboxradio("refresh");
and uncheck
$('#captureImage').attr("checked",false).checkboxradio("refresh");
delete
or delete[]
would probably both free the memory allocated (memory pointed), but the big difference is that delete
on an array won't call the destructor of each element of the array.
Anyway, mixing new/new[]
and delete/delete[]
is probably UB.
The default schema for the user could be changed with the following query and avoids changing the property every time a table is to be created.
USE [DBName]
GO
ALTER USER [YourUserName] WITH DEFAULT_SCHEMA = [YourSchema]
GO
I got the same error when I just copied the complete line but when I rewrite the code again i.e. instead of copy-paste, writing it completely then the error was no longer present.
Conclusion: There might be some unacceptable words to the language got copied giving rise to this error.
In slim markdown use this:
markdown:
{:.cool-heading}
#Some Title
Translates to:
<h1 class="cool-heading">Some Title</h1>
I have implemented MultipartReader NuGet package for ASP.NET 4 for reading multipart form data. It is based on Multipart Form Data Parser, but it supports more than one file.
I think you've misunderstood some python syntax, the following does two assignments:
In [11]: a = b = 1
In [12]: a
Out[12]: 1
In [13]: b
Out[13]: 1
So in your code it was as if you were doing:
sum = df['budget'] + df['actual'] # a Series
# and
df['variance'] = df['budget'] + df['actual'] # assigned to a column
The latter creates a new column for df:
In [21]: df
Out[21]:
cluster date budget actual
0 a 2014-01-01 00:00:00 11000 10000
1 a 2014-02-01 00:00:00 1200 1000
2 a 2014-03-01 00:00:00 200 100
3 b 2014-04-01 00:00:00 200 300
4 b 2014-05-01 00:00:00 400 450
5 c 2014-06-01 00:00:00 700 1000
6 c 2014-07-01 00:00:00 1200 1000
7 c 2014-08-01 00:00:00 200 100
8 c 2014-09-01 00:00:00 200 300
In [22]: df['variance'] = df['budget'] + df['actual']
In [23]: df
Out[23]:
cluster date budget actual variance
0 a 2014-01-01 00:00:00 11000 10000 21000
1 a 2014-02-01 00:00:00 1200 1000 2200
2 a 2014-03-01 00:00:00 200 100 300
3 b 2014-04-01 00:00:00 200 300 500
4 b 2014-05-01 00:00:00 400 450 850
5 c 2014-06-01 00:00:00 700 1000 1700
6 c 2014-07-01 00:00:00 1200 1000 2200
7 c 2014-08-01 00:00:00 200 100 300
8 c 2014-09-01 00:00:00 200 300 500
As an aside, you shouldn't use sum
as a variable name as the overrides the built-in sum function.
What type of sql database are using (MSSQL, Oracle etc)? I believe what you have written is correct.
You could also write the first query like this:
SELECT s.sid, s.name
FROM Supplier s
WHERE (SELECT COUNT(DISTINCT pr.jid)
FROM Supplies su, Projects pr
WHERE su.sid = s.sid
AND pr.jid = su.jid) >= 2
It's a little more readable, and less mind-bending than trying to do it with GROUP BY. Performance may differ though.
It seems that you've omitted the value attribute in HTML markup.
Add it there as <input value="" ... >
.
Avro is a row-based storage format for Hadoop.
Parquet is a column-based storage format for Hadoop.
If your use case typically scans or retrieves all of the fields in a row in each query, Avro is usually the best choice.
If your dataset has many columns, and your use case typically involves working with a subset of those columns rather than entire records, Parquet is optimized for that kind of work.
Remove mb4 from charset and collation from config/database.php, then it will execute successfully.
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
This answer complements the many great existing answers in the following ways:
The existing answers are packaged into flexible shell functions:
stdin
input, but alternatively also filename argumentsSIGPIPE
in the usual way (quiet termination with exit code 141
), as opposed to breaking noisily. This is important when piping the function output to a pipe that is closed early, such as when piping to head
.A performance comparison is made.
awk
, sort
, and cut
, adapted from the OP's own answer:shuf() { awk 'BEGIN {srand(); OFMT="%.17f"} {print rand(), $0}' "$@" |
sort -k1,1n | cut -d ' ' -f2-; }
shuf() { perl -MList::Util=shuffle -e 'print shuffle(<>);' "$@"; }
shuf() { python -c '
import sys, random, fileinput; from signal import signal, SIGPIPE, SIG_DFL;
signal(SIGPIPE, SIG_DFL); lines=[line for line in fileinput.input()];
random.shuffle(lines); sys.stdout.write("".join(lines))
' "$@"; }
See the bottom section for a Windows version of this function.
shuf() { ruby -e 'Signal.trap("SIGPIPE", "SYSTEM_DEFAULT");
puts ARGF.readlines.shuffle' "$@"; }
Performance comparison:
Note: These numbers were obtained on a late-2012 iMac with 3.2 GHz Intel Core i5 and a Fusion Drive, running OSX 10.10.3. While timings will vary with OS used, machine specs, awk
implementation used (e.g., the BSD awk
version used on OSX is usually slower than GNU awk
and especially mawk
), this should provide a general sense of relative performance.
Input file is a 1-million-lines file produced with seq -f 'line %.0f' 1000000
.
Times are listed in ascending order (fastest first):
shuf
0.090s
0.289s
0.589s
1.342s
with Python 2.7.6; 2.407s
(!) with Python 3.4.2awk
+ sort
+ cut
3.003s
with BSD awk
; 2.388s
with GNU awk
(4.1.1); 1.811s
with mawk
(1.3.4); For further comparison, the solutions not packaged as functions above:
sort -R
(not a true shuffle if there are duplicate input lines)
10.661s
- allocating more memory doesn't seem to make a difference24.229s
bash
loops + sort
32.593s
Conclusions:
shuf
, if you can - it's the fastest by far.awk
+ sort
+ cut
combo as a last resort; which awk
implementation you use matters (mawk
is faster than GNU awk
, BSD awk
is slowest).sort -R
, bash
loops, and Scala.Windows versions of the Python solution (the Python code is identical, except for variations in quoting and the removal of the signal-related statements, which aren't supported on Windows):
$OutputEncoding
if you want to send non-ASCII characters via the pipeline):# Call as `shuf someFile.txt` or `Get-Content someFile.txt | shuf`
function shuf {
$Input | python -c @'
import sys, random, fileinput;
lines=[line for line in fileinput.input()];
random.shuffle(lines); sys.stdout.write(''.join(lines))
'@ $args
}
Note that PowerShell can natively shuffle via its Get-Random
cmdlet (though performance may be a problem); e.g.:
Get-Content someFile.txt | Get-Random -Count ([int]::MaxValue)
cmd.exe
(a batch file):Save to file shuf.cmd
, for instance:
@echo off
python -c "import sys, random, fileinput; lines=[line for line in fileinput.input()]; random.shuffle(lines); sys.stdout.write(''.join(lines))" %*