The inverse, as the name says, but sometimes "close enough" is "close enough"; an interesting read anyway.
my_list = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
my_list.sort(lambda x,y : cmp(x['name'], y['name']))
my_list
will now be what you want.
Or better:
Since Python 2.4, there's a key
argument is both more efficient and neater:
my_list = sorted(my_list, key=lambda k: k['name'])
...the lambda is, IMO, easier to understand than operator.itemgetter
, but your mileage may vary.
stdlib will hook you up son!
#!/usr/local/bin/python2.7
from collections import deque
a = deque('Monday Tuesday Wednesday Thursday Friday Saturday Sunday'.split(' '))
a.rotate(3)
deque(['Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday'])
You could use the SQL%ROWCOUNT
Oracle variable:
UPDATE table1
SET field2 = value2,
field3 = value3
WHERE field1 = value1;
IF (SQL%ROWCOUNT = 0) THEN
INSERT INTO table (field1, field2, field3)
VALUES (value1, value2, value3);
END IF;
It would be easier just to determine if your primary key (i.e. field1
) has a value and then perform an insert or update accordingly. That is, if you use said values as parameters for a stored procedure.
Font-awesome provides a great solution out of the box:
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" />_x000D_
_x000D_
<ul class='fa-ul'>_x000D_
<li><i class="fa-li fa fa-plus"></i> Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam</li>_x000D_
<li><i class="fa-li fa fa-plus"></i> Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam</li>_x000D_
</ul>
_x000D_
i would solve that by doing something like this
public function rules()
{
return [
'name' =>
'required|min:2|max:255|unique:courses,name,'.\Request::get('id'),
];
}
Where you get the id from the request and pass it on the rule
class String
def bye_felicia()
felicia = self.strip[0] #first char, not first space.
self.sub(felicia, '')
end
end
I think to add timestamp to every record and get the latest. In this situation you can get any ids, pack rows and other ops.
From the horse's mouth: Explicit line joining
Two or more physical lines may be joined into logical lines using backslash characters (
\
), as follows: when a physical line ends in a backslash that is not part of a string literal or comment, it is joined with the following forming a single logical line, deleting the backslash and the following end-of-line character. For example:if 1900 < year < 2100 and 1 <= month <= 12 \ and 1 <= day <= 31 and 0 <= hour < 24 \ and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date return 1
A line ending in a backslash cannot carry a comment. A backslash does not continue a comment. A backslash does not continue a token except for string literals (i.e., tokens other than string literals cannot be split across physical lines using a backslash). A backslash is illegal elsewhere on a line outside a string literal.
CSS
.achievements-wrapper { height: 300px; overflow: auto; }
HTML
<div class="span3 achievements-wrapper">
<h2>Achievements left</h2>
<table class="table table-striped">
...
</table>
</div>
I'm amazed by everyone else's MUCH more complicated answers.
You can very simply define the alpha in the color definition of the button (or any other view) in your xml:
android:color="#66FF0000" // Partially transparent red
In the above example, the color would be a partially transparent red.
When defining the color of a view, the format can be either #RRGGBB
or #AARRGGBB
, where AA
is the hex alpha value. FF
would be fully opaque and 00
would be full transparent.
If you need to dynamically alter the opacity in your code, use
myButton.getBackground().setAlpha(128); // 50% transparent
Where the INT ranges from 0
(fully transparent) to 255
(fully opaque).
Just execute
sudo npm i --save
That's all
DateTime.Now.ToString("dd/MM/yyyy");
Trying http://0.0.0.0:3000/routes
on a Rails 5 API app (i.e.: JSON-only oriented) will (as of Rails beta 3) return
{"status":404,"error":"Not Found","exception":"#>
<ActionController::RoutingError:...
However, http://0.0.0.0:3000/rails/info/routes
will render a nice, simple HTML page with routes.
I would also highly recommend Adminer - http://www.adminer.org/
It is much faster than phpMyAdmin, does less funky iframe stuff, and supports both MySQL and PostgreSQL.
std::less<>
when using custom classes with operator<
If you are dealing with a set of your custom class that has operator<
defined, then you can just use std::less<>
.
As mentioned at http://en.cppreference.com/w/cpp/container/set/find C++14 has added two new find
APIs:
template< class K > iterator find( const K& x );
template< class K > const_iterator find( const K& x ) const;
which allow you to do:
main.cpp
#include <cassert>
#include <set>
class Point {
public:
// Note that there is _no_ conversion constructor,
// everything is done at the template level without
// intermediate object creation.
//Point(int x) : x(x) {}
Point(int x, int y) : x(x), y(y) {}
int x;
int y;
};
bool operator<(const Point& c, int x) { return c.x < x; }
bool operator<(int x, const Point& c) { return x < c.x; }
bool operator<(const Point& c, const Point& d) {
return c.x < d;
}
int main() {
std::set<Point, std::less<>> s;
s.insert(Point(1, -1));
s.insert(Point(2, -2));
s.insert(Point(0, 0));
s.insert(Point(3, -3));
assert(s.find(0)->y == 0);
assert(s.find(1)->y == -1);
assert(s.find(2)->y == -2);
assert(s.find(3)->y == -3);
// Ignore 1234, find 1.
assert(s.find(Point(1, 1234))->y == -1);
}
Compile and run:
g++ -std=c++14 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out
More info about std::less<>
can be found at: What are transparent comparators?
Tested on Ubuntu 16.10, g++
6.2.0.
As per the docs select, the following piece of code worked for me.
<div ng-controller="ExampleController">
<form name="myForm">
<label for="mySelect">Make a choice:</label>
<select name="mySelect" id="mySelect"
ng-options="option.name for option in data.availableOptions track by option.id"
ng-model="data.selectedOption"></select>
</form>
<hr>
<tt>option = {{data.selectedOption}}</tt><br/>
</div>
The JIT Compiler is probably going to make this pretty fast since it's just branches and basic tests. You could probably make it more elegant with a HashMap lookup to a callback but I doubt it would be any faster. As to memory, this is pretty slim as is.
Somehow I doubt this code is actually a critical bottle neck for memory or performance. Do you have any real reason to try to optimize it?
Use the Unicode Character 'BLACK CIRCLE' (U+25CF) http://www.fileformat.info/info/unicode/char/25CF/index.htm
To copy and paste: ?
These are all good answers, however many forget to close the cursor and database. If you don't close the cursor or database you may run in to memory leaks.
Additionally:
You can get an error when searching by String
that contains non alpha/numeric characters. For example: "1a5f9ea3-ec4b-406b-a567-e6927640db40
". Those dashes (-
) will cause an unrecognized token
error. You can overcome this by putting the string in an array. So make it a habit to query like this:
public boolean hasObject(String id) {
SQLiteDatabase db = getWritableDatabase();
String selectString = "SELECT * FROM " + _TABLE + " WHERE " + _ID + " =?";
// Add the String you are searching by here.
// Put it in an array to avoid an unrecognized token error
Cursor cursor = db.rawQuery(selectString, new String[] {id});
boolean hasObject = false;
if(cursor.moveToFirst()){
hasObject = true;
//region if you had multiple records to check for, use this region.
int count = 0;
while(cursor.moveToNext()){
count++;
}
//here, count is records found
Log.d(TAG, String.format("%d records found", count));
//endregion
}
cursor.close(); // Dont forget to close your cursor
db.close(); //AND your Database!
return hasObject;
}
Inf
is infinity, it's a "bigger than all the other numbers" number. Try subtracting anything you want from it, it doesn't get any smaller. All numbers are < Inf
. -Inf
is similar, but smaller than everything.
NaN
means not-a-number. If you try to do a computation that just doesn't make sense, you get NaN
. Inf - Inf
is one such computation. Usually NaN
is used to just mean that some data is missing.
The problem is that your ui
property uses a forward declaration of class Ui::MainWindowClass
, hence the "incomplete type" error.
Including the header file in which this class is declared will fix the problem.
EDIT
Based on your comment, the following code:
namespace Ui
{
class MainWindowClass;
}
does NOT declare a class. It's a forward declaration, meaning that the class will exist at some point, at link time.
Basically, it just tells the compiler that the type will exist, and that it shouldn't warn about it.
But the class has to be defined somewhere.
Note this can only work if you have a pointer to such a type.
You can't have a statically allocated instance of an incomplete type.
So either you actually want an incomplete type, and then you should declare your ui
member as a pointer:
namespace Ui
{
// Forward declaration - Class will have to exist at link time
class MainWindowClass;
}
class MainWindow : public QMainWindow
{
private:
// Member needs to be a pointer, as it's an incomplete type
Ui::MainWindowClass * ui;
};
Or you want a statically allocated instance of Ui::MainWindowClass
, and then it needs to be declared.
You can do it in another header file (usually, there's one header file per class).
But simply changing the code to:
namespace Ui
{
// Real class declaration - May/Should be in a specific header file
class MainWindowClass
{};
}
class MainWindow : public QMainWindow
{
private:
// Member can be statically allocated, as the type is complete
Ui::MainWindowClass ui;
};
will also work.
Note the difference between the two declarations. First uses a forward declaration, while the second one actually declares the class (here with no properties nor methods).
For simple usage I made a function that encodes the input string (binary data):
/* Encodes string to hexadecimal string reprsentation
Allocates a new memory for supplied lpszOut that needs to be deleted after use
Fills the supplied lpszOut with hexadecimal representation of the input
*/
void StringToHex(unsigned char *szInput, size_t size_szInput, char **lpszOut)
{
unsigned char *pin = szInput;
const char *hex = "0123456789ABCDEF";
size_t outSize = size_szInput * 2 + 2;
*lpszOut = new char[outSize];
char *pout = *lpszOut;
for (; pin < szInput + size_szInput; pout += 2, pin++)
{
pout[0] = hex[(*pin >> 4) & 0xF];
pout[1] = hex[*pin & 0xF];
}
pout[0] = 0;
}
Usage:
unsigned char input[] = "This is a very long string that I want to encode";
char *szHexEncoded = NULL;
StringToHex(input, strlen((const char *)input), &szHexEncoded);
printf(szHexEncoded);
// The allocated memory needs to be deleted after usage
delete[] szHexEncoded;
For Git GUI users it couldn't be much simpler. In Git GUI, choose the branch name from the drop down list in the "Rename Branch" dialog box created from the menu item Branch:Rename, type a New Name, and click "Rename". I have highlighted where to find the drop down list.
You can also use jQuery('.class-name').attr("href")
, in my case it works better.
Here more information: "jQuery(...)" instead of "$(...)"
JPA's behaviour is correct (meaning as per the specification): objects aren't deleted simply because you've removed them from a OneToMany collection. There are vendor-specific extensions that do that but native JPA doesn't cater for it.
In part this is because JPA doesn't actually know if it should delete something removed from the collection. In object modeling terms, this is the difference between composition and "aggregation*.
In composition, the child entity has no existence without the parent. A classic example is between House and Room. Delete the House and the Rooms go too.
Aggregation is a looser kind of association and is typified by Course and Student. Delete the Course and the Student still exists (probably in other Courses).
So you need to either use vendor-specific extensions to force this behaviour (if available) or explicitly delete the child AND remove it from the parent's collection.
I'm aware of:
As he didn't specify which version of SQL server he uses (date
type isn't available in 2005), one could also use
SELECT CONVERT(VARCHAR(10),date_column,112),SUM(num_col) AS summed
FROM table_name
GROUP BY CONVERT(VARCHAR(10),date_column,112)
Use an on onkeypress event. Example for a zip code box. It allows a maximum of 5 characters, and checks to make sure input is only numbers.
Nothing beats a server side validation of course, but this is a nifty way to go.
function validInput(e) {_x000D_
e = (e) ? e : window.event;_x000D_
a = document.getElementById('zip-code');_x000D_
cPress = (e.which) ? e.which : e.keyCode;_x000D_
_x000D_
if (cPress > 31 && (cPress < 48 || cPress > 57)) {_x000D_
return false;_x000D_
} else if (a.value.length >= 5) {_x000D_
return false;_x000D_
}_x000D_
_x000D_
return true;_x000D_
}
_x000D_
#zip-code {_x000D_
overflow: hidden;_x000D_
width: 60px;_x000D_
}
_x000D_
<label for="zip-code">Zip Code:</label>_x000D_
<input type="number" id="zip-code" name="zip-code" onkeypress="return validInput(event);" required="required">
_x000D_
If you're running on Passenger, then the default is to run in production, in your apache conf:
<VirtualHost *:80>
ServerName application_name.rails.local
DocumentRoot "/Users/rails/application_name/public"
RailsEnv production ## This is the default
</VirtualHost>
If you're just running a local server with mongrel or webrick, you can do:
./script/server -e production
or in bash:
RAILS_ENV=production ./script/server
actually overriding the RAILS_ENV constant in the enviornment.rb should probably be your last resort, as it's probably not going to stay set (see another answer I gave on that)
There are many methods that we can include javascript, css into your Yii App. Today I will demonstrate three simple and helpul methods.
A simple way to add js, css by editing config/main.php
// application components
'components'=>array(
// ...
'clientScript'=>array(
'packages'=>array(
'jquery'=>array(
'baseUrl'=>'//ajax.googleapis.com/ajax/libs/jquery/1/',
'js'=>array('jquery.min.js'),
)
),
),
// ...
),
Using getClientScript
Usually, We add in block of code into Controller or layout of your theme
$baseUrl = Yii::app()->baseUrl;
$cs = Yii::app()->getClientScript();
$cs->registerScriptFile($baseUrl.'/js/yourscript.js');
$cs->registerCssFile($baseUrl.'/css/yourcss.css');
Or shorter:
Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/path/to/your/javascript/file',CClientScript::POS_END);
Yii::app()->clientScript->registerCssFile(Yii::app()->baseUrl.'/path/to/css/file');
Include core js files
Yii::app()->clientScript->registerCoreScript('jquery');
Yii::app()->clientScript->registerCoreScript('jquery.ui');
Faster Yii API Document: http://yii.codexamples.com/
^\d+(()|(\.\d+)?)$
Came up with this. Allows both integer and decimal, but forces a complete decimal (leading and trailing numbers) if you decide to enter a decimal.
If statement is used for checking just one condition quickly.
When you have multiple options, use <xsl:choose>
as illustrated below:
<xsl:choose>
<xsl:when test="$CreatedDate > $IDAppendedDate">
<h2>mooooooooooooo</h2>
</xsl:when>
<xsl:otherwise>
<h2>dooooooooooooo</h2>
</xsl:otherwise>
</xsl:choose>
Also, you can use multiple <xsl:when>
tags to express If .. Else If
or Switch
patterns as illustrated below:
<xsl:choose>
<xsl:when test="$CreatedDate > $IDAppendedDate">
<h2>mooooooooooooo</h2>
</xsl:when>
<xsl:when test="$CreatedDate = $IDAppendedDate">
<h2>booooooooooooo</h2>
</xsl:when>
<xsl:otherwise>
<h2>dooooooooooooo</h2>
</xsl:otherwise>
</xsl:choose>
The previous example would be equivalent to the pseudocode below:
if ($CreatedDate > $IDAppendedDate)
{
output: <h2>mooooooooooooo</h2>
}
else if ($CreatedDate = $IDAppendedDate)
{
output: <h2>booooooooooooo</h2>
}
else
{
output: <h2>dooooooooooooo</h2>
}
As the statement executed is not actually DML (eg UPDATE
, INSERT
or EXECUTE
), but a piece of T-SQL which contains DML, I suspect it is not treated as an update-query.
Section 13.1.2.3 of the JDBC 4.1 specification states something (rather hard to interpret btw):
When the method
execute
returns true, the methodgetResultSet
is called to retrieve the ResultSet object. Whenexecute
returns false, the methodgetUpdateCount
returns an int. If this number is greater than or equal to zero, it indicates the update count returned by the statement. If it is -1, it indicates that there are no more results.
Given this information, I guess that executeUpdate()
internally does an execute()
, and then - as execute()
will return false
- it will return the value of getUpdateCount()
, which in this case - in accordance with the JDBC spec - will return -1
.
This is further corroborated by the fact 1) that the Javadoc for Statement.executeUpdate()
says:
Returns: either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing
And 2) that the Javadoc for Statement.getUpdateCount() specifies:
the current result as an update count; -1 if the current result is a ResultSet object or there are no more results
Just to clarify: given the Javadoc for executeUpdate()
the behavior is probably wrong, but it can be explained.
Also as I commented elsewhere, the -1 might just indicate: maybe something was changed, but we simply don't know, or we can't give an accurate number of changes (eg because in this example it is a piece of T-SQL that is executed).
Socket are characterized by their domain, type and transport protocol. Common domains are:
AF_UNIX: address format is UNIX pathname
AF_INET: address format is host and port number
(there are actually many other options which can be used here for specialized purposes).usually we use AF_INET for socket programming
Reference: http://www.cs.uic.edu/~troy/fall99/eecs471/sockets.html
Existing good jQuery plugin Purl (A JavaScript URL parser).This utility can be used in two ways - with jQuery or without...
You can opt to create your own custom events so you'll still have a clear separation of logic.
Bind to a custom event:
$('#laneconfigdisplay').bind('contentchanged', function() {
// do something after the div content has changed
alert('woo');
});
In your function that updates the div:
// all logic for grabbing xml and updating the div here ..
// and then send a message/event that we have updated the div
$('#laneconfigdisplay').trigger('contentchanged'); // this will call the function above
One way is to use the jQuery offset
method to translate the event.pageX
and event.pageY
coordinates from the event into a mouse position relative to the parent. Here's an example for future reference:
$("#something").click(function(e){
var parentOffset = $(this).parent().offset();
//or $(this).offset(); if you really just want the current element's offset
var relX = e.pageX - parentOffset.left;
var relY = e.pageY - parentOffset.top;
});
With your example:
<input type="checkbox" id="c2" name="c2" value="DE039230952"/>
Replace $$ with document.querySelectorAll in the examples:
$$('input') //Every input
$$('[id]') //Every element with id
$$('[id="c2"]') //Every element with id="c2"
$$('input,[id]') //Every input + every element with id
$$('input[id]') //Every input including id
$$('input[id="c2"]') //Every input including id="c2"
$$('input#c2') //Every input including id="c2" (same as above)
$$('input#c2[value="DE039230952"]') //Every input including id="c2" and value="DE039230952"
$$('input#c2[value^="DE039"]') //Every input including id="c2" and value has content starting with DE039
$$('input#c2[value$="0952"]') //Every input including id="c2" and value has content ending with 0952
$$('input#c2[value*="39230"]') //Every input including id="c2" and value has content including 39230
Use the examples directly with:
const $$ = document.querySelectorAll.bind(document);
Some additions:
$$(.) //The same as $([class])
$$(div > input) //div is parent tag to input
document.querySelector() //equals to $$()[0] or $()
Had this problem in vs2017, I already got MVC via nuget but System.Web.Mvc didn't appear in the "Assemblies" list under "Add Reference".
The solution was to select "Extensions" under "Assemblies" in the "Add Reference" dialog.
You could write a JavaScript wto find the window height and width and make it to half to find the centre point.
Add you stuff inside a tag, and set the div top and left from the javascript to the centre coordinates you have found using Javascript.
Let me know if you need the code.
Check your OpenCV version
import cv2
cv2.__version__
If your are running Python v3.x and OpenCV v4 and above:
pip install opencv-contrib-python
Try running your program again. This should now work.
We may need more information. Here is what I did to reproduce on SQL Server 2008:
CREATE DATABASE [Test] ON PRIMARY
(
NAME = N'Test'
, FILENAME = N'...Test.mdf'
, SIZE = 3072KB
, FILEGROWTH = 1024KB
)
LOG ON
(
NAME = N'Test_log'
, FILENAME = N'...Test_log.ldf'
, SIZE = 1024KB
, FILEGROWTH = 10%
)
COLLATE SQL_Latin1_General_CP850_BIN2
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[MyTable]
(
[SomeCol] [varchar](50) NULL
) ON [PRIMARY]
GO
Insert MyTable( SomeCol )
Select '±' Collate SQL_Latin1_General_CP1_CI_AS
GO
Select SomeCol, SomeCol Collate SQL_Latin1_General_CP1_CI_AS
From MyTable
Results show the original character. Declaring collation in the query should return the proper character from SQL Server's perspective however it may be the case that the presentation layer is then converting to something yet different like UTF-8.
I do post an answer here for the question here that was closed even though the asnwers here helped, but were not sufficient.
So, this is in order to get a json array to a String[]
using jsonsimple.
According to the (marvelous) decode examples and docs, JSONArrays are java List, so we can access List methods.
From there, is it possible to transform it to a String[]
with the following:
JSONObject assemblingTags = (JSONObject) obj.get("assembling-tags");
JSONArray aTagsList = (JSONArray) assemblingTags.get("list");
String[] tagsList = (String[]) aTagsList.stream().toArray(String[]::new);
Safely returned default value via generics and LINQ.
public T ReadAppSetting<T>(string searchKey, T defaultValue, StringComparison compare = StringComparison.Ordinal)
{
if (ConfigurationManager.AppSettings.AllKeys.Any(key => string.Compare(key, searchKey, compare) == 0)) {
try
{ // see if it can be converted.
var converter = TypeDescriptor.GetConverter(typeof(T));
if (converter != null) defaultValue = (T)converter.ConvertFromString(ConfigurationManager.AppSettings.GetValues(searchKey).First());
}
catch { } // nothing to do just return the defaultValue
}
return defaultValue;
}
Used as follows:
string LogFileName = ReadAppSetting("LogFile","LogFile");
double DefaultWidth = ReadAppSetting("Width",1280.0);
double DefaultHeight = ReadAppSetting("Height",1024.0);
Color DefaultColor = ReadAppSetting("Color",Colors.Black);
Add an item and set its "Selected" property to true, you will probably want to set "appenddatabounditems" property to true also so your initial value isn't deleted when databound.
If you are talking about setting an initial value that is in your databound items then hook into your ondatabound event and set which index you want to selected=true you will want to wrap it in "if not page.isPostBack then ...." though
Protected Sub DepartmentDropDownList_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles DepartmentDropDownList.DataBound
If Not Page.IsPostBack Then
DepartmentDropDownList.SelectedValue = "somevalue"
End If
End Sub
As you have mentioned it doesn't change anything.
First, you should redirect both standard input and standard error from the crontab execution like below:
*/2 * * * * /usr/bin/python /home/souza/Documets/Listener/listener.py > /tmp/listener.log 2>&1
Then you can view the file /tmp/listener.log
to see if the script executed as you expected.
Second, I guess what you mean by change anything is by watching the files created by your program:
f = file('counter', 'r+w')
json_file = file('json_file_create_server.json', 'r+w')
The crontab job above won't create these file in directory /home/souza/Documets/Listener
, as the cron job is not executed in this directory, and you use relative path in the program. So to create this file in directory /home/souza/Documets/Listener
, the following cron job will do the trick:
*/2 * * * * cd /home/souza/Documets/Listener && /usr/bin/python listener.py > /tmp/listener.log 2>&1
Change to the working directory and execute the script from there, and then you can view the files created in place.
In my case it was a simple case of removing IIS because Windows 10 comes with IIS (Internet Information Service) pre installed - that conflicts with XAMPP because these both servers try to use the port 80. If you don't want to use IIS and keep using XAMPP
Then restart.
To implement you need use Typeface go through with sample below
Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/Roboto/Roboto-Regular.ttf");
for (View view : allViews)
{
if (view instanceof TextView)
{
TextView textView = (TextView) view;
textView.setTypeface(typeface);
}
}
}
You can also use an oracle defined collection
DECLARE
arrayvalues sys.odcivarchar2list;
BEGIN
arrayvalues := sys.odcivarchar2list('Matt','Joanne','Robert');
FOR x IN ( SELECT m.column_value m_value
FROM table(arrayvalues) m )
LOOP
dbms_output.put_line (x.m_value||' is a good pal');
END LOOP;
END;
I would use in-memory array. But with the .COUNT
improvement suggested by uziberia:
DECLARE
TYPE t_people IS TABLE OF varchar2(10) INDEX BY PLS_INTEGER;
arrayvalues t_people;
BEGIN
SELECT *
BULK COLLECT INTO arrayvalues
FROM (select 'Matt' m_value from dual union all
select 'Joanne' from dual union all
select 'Robert' from dual
)
;
--
FOR i IN 1 .. arrayvalues.COUNT
LOOP
dbms_output.put_line(arrayvalues(i)||' is my friend');
END LOOP;
END;
Another solution would be to use a Hashmap like @Jchomel did here.
NB:
With Oracle 12c you can even query arrays directly now!
Instead of using EXISTS
and COUNT
just use @@ROWCOUNT
:
select product, price from table1 where project = 1
IF @@ROWCOUNT = 0
BEGIN
select product, price from table1 where customer = 2
IF @@ROWCOUNT = 0
select product, price from table1 where company = 3
END
I know this isn't a direct answer to your question, but you could also consider using clip-path, as in this question: https://stackoverflow.com/a/18208889/23341.
The same idea as Tatu(thanks I'll need it soon in our project), but with a regular expression.
Which may be quicker for large dataset.
<html>
<head>
<title>excelToTable</title>
<script src="../libs/jquery.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<textarea>a1 a2 a3
b1 b2 b3</textarea>
<div></div>
<input type="button" onclick="convert()" value="convert"/>
<script>
function convert(){
var xl = $('textarea').val();
$('div').html(
'<table><tr><td>' +
xl.replace(/\n+$/i, '').replace(/\n/g, '</tr><tr><td>').replace(/\t/g, '</td><td>') +
'</tr></table>'
)
}
</script>
</body>
</html>
Using aggregate
is the right approach, but you need to $unwind
the list
array before applying the $match
so that you can filter individual elements and then use $group
to put it back together:
db.test.aggregate([
{ $match: {_id: ObjectId("512e28984815cbfcb21646a7")}},
{ $unwind: '$list'},
{ $match: {'list.a': {$gt: 3}}},
{ $group: {_id: '$_id', list: {$push: '$list.a'}}}
])
outputs:
{
"result": [
{
"_id": ObjectId("512e28984815cbfcb21646a7"),
"list": [
4,
5
]
}
],
"ok": 1
}
MongoDB 3.2 Update
Starting with the 3.2 release, you can use the new $filter
aggregation operator to do this more efficiently by only including the list
elements you want during a $project
:
db.test.aggregate([
{ $match: {_id: ObjectId("512e28984815cbfcb21646a7")}},
{ $project: {
list: {$filter: {
input: '$list',
as: 'item',
cond: {$gt: ['$$item.a', 3]}
}}
}}
])
You need to deserialize the JSON once before returning it as response. Please refer below code. This works for me:
JavaScriptSerializer jss = new JavaScriptSerializer();
Object finalData = jss.DeserializeObject(str);
Try this with the + after [0-9]:
input type="text" pattern="[0-9]+" title="number only"
public boolean onKeyDown(int keycode, KeyEvent event) {
if (keycode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keycode, event);
}
My app closed with above code.
implementation androidx.recyclerview:recyclerview:.... It is advised to update to the androidx libraries which are here:
https://developer.android.com/jetpack/androidx/releases/recyclerview
The layout file Widget XML tag then must be updated to: androidx.recyclerview.widget.RecyclerView
Waqas Raja's answer with some LINQ lambda fun:
List<int> listValues = new List<int>();
Request.Form.AllKeys
.Where(n => n.StartsWith("List"))
.ToList()
.ForEach(x => listValues.Add(int.Parse(Request.Form[x])));
I faced the similar problem. In my case I had created the new virtual device and had enabled the snapshot. I just unchecked the checkbox Go to AVD Manager
-> Select the device
-> click Edit
and uncheck the Enabled
checkbox.
I hope this works.
Since the question didn't specify .NET, this should work in VBScript or VB6.
Dim objFSO, strFolder
strFolder = "C:\Temp"
Set objFSO = CreateObject("Scripting.FileSystemObject")
If Not objFSO.FolderExists(strFolder) Then
objFSO.CreateFolder(strFolder)
End If
In my particular case, this error error was happening because the file which I've added wasn't referenced at .vcproj
file.
It's not a standard lib of python 2.7. So in order for these to work properly and if you're using Python 2.7 you should download the PIL library first: Direct download link: http://effbot.org/downloads/PIL-1.1.7.win32-py2.7.exe After installing it, follow these steps:
Edit your script.py
from Tkinter import *
from PIL import ImageTk, Image
app_root = Tk()
#Setting it up
img = ImageTk.PhotoImage(Image.open("app.png"))
#Displaying it
imglabel = Label(app_root, image=img).grid(row=1, column=1)
app_root.mainloop()
Hope that helps!
You can use the built-in pathlib
module (requires Python 3.4+, but there are backports for older versions on PyPI: pathlib
, pathlib2
).
To remove a file there is the unlink
method:
import pathlib
path = pathlib.Path(name_of_file)
path.unlink()
Or the rmdir
method to remove an empty folder:
import pathlib
path = pathlib.Path(name_of_folder)
path.rmdir()
I dont know if this useful for you when you resize your page:
$(window).resize(function() {
if(screen.width == window.innerWidth){
alert("you are on normal page with 100% zoom");
} else if(screen.width > window.innerWidth){
alert("you have zoomed in the page i.e more than 100%");
} else {
alert("you have zoomed out i.e less than 100%");
}
});
I have Spring 4.2 in my project and many SockJS Stomp implementations usually work well with Spring Boot implementations. This implementation from Baeldung worked(for me without changing from Spring 4.2 to 5). After Using the dependencies mentioned in his blog, it still gave me ClassNotFoundError. I added the below dependency to fix it.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.3.RELEASE</version>
</dependency>
By just entering swift command in the terminal, it will show the version, while logging to Swift console.(something like below)
System-IOSs-MacBook-Air:~ system$ swift
Welcome to Apple Swift version 5.1 (swiftlang-1100.0.270.13 clang-1100.0.33.7).
Type :help for assistance.
The first way
Needs root
Use kill
:
adb shell ps
=> Will list all running processes on the device and their process ids
adb shell kill <PID>
=> Instead of <PID>
use process id of your application
The second way
In Eclipse open DDMS
perspective.
In Devices
view you will find all running processes.
Choose the process and click on Stop
.
The third way
It will kill only background process of an application.
adb shell am kill [options] <PACKAGE>
=> Kill all processes associated with (the app's package name). This command kills only processes that are safe to kill and that will not impact the user experience.
Options are:
--user | all | current: Specify user whose processes to kill; all users if not specified.
The fourth way
Needs root
adb shell pm disable <PACKAGE>
=> Disable the given package or component (written as "package/class").
The fifth way
Note that run-as is only supported for apps that are signed with debug keys.
run-as <package-name> kill <pid>
The sixth way
Introduced in Honeycomb
adb shell am force-stop <PACKAGE>
=> Force stop everything associated with (the app's package name).
P.S.: I know that the sixth method didn't work for you, but I think that it's important to add this method to the list, so everyone will know it.
private void fillTextView (int id, String text) {
TextView tv = (TextView) findViewById(id);
tv.setText(text);
}
If this is where you're getting the null pointer exception, there was no view found for the id that you passed into findViewById()
, and the actual exception is thrown when you try to call a function setText()
on null
. You should post your XML for R.layout.activity_main
, as it's hard to tell where things went wrong just by looking at your code.
More reading on null pointers: What is a NullPointerException, and how do I fix it?
$('img.conversation_img[alt="example"]')
.each(function(){
alert($(this).attr('src'))
});
This will display src attributes of all images of class 'conversation_img' with alt='example'
works in rails 4.1 and support symbols without quotes {:a => 'b'}
just add this to initializers folder:
class String
def to_hash_object
JSON.parse(self.gsub(/:([a-zA-z]+)/,'"\\1"').gsub('=>', ': ')).symbolize_keys
end
end
It must be synchronized, using an object lock, stateless, or immutable.
link: http://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html
Instead of document or $(document) to avoid JQuery, you can add a TimeOut to validate the objects. TimeOut is executed after loading all objects within the page and other events...
setTimeout(function () {
var str = document.getElementById("cal_preview").value;
var str1 = document.getElementById("year").value;
....
....
....
}, 0);
The code you have is a white with low opacity.
If something white with a low opacity is above something black, you end up with a lighter shade of gray. Above red? Lighter red, etc. That is how opacity works.
Here is a simple demo.
If you want it to look 'more white', make it less opaque:
background:rgba(255,255,255, 0.9);
You can't do window.history.back(); and location.reload(); in the same function.
window.history.back() breaks the javascript flow and redirects to previous page, location.reload() is never processed.
location.reload() has to be called on the page you redirect to when using window.history.back().
I would used an url to redirect instead of history.back, that gives you both a redirect and refresh.
I know there's an answer already, but if you want your input to behave exactly like the maxlength
attribute or as close as you can, use the following code:
(function($) {
methods = {
/*
* addMax will take the applied element and add a javascript behavior
* that will set the max length
*/
addMax: function() {
// set variables
var
maxlAttr = $(this).attr("maxlength"),
maxAttR = $(this).attr("max"),
x = 0,
max = "";
// If the element has maxlength apply the code.
if (typeof maxlAttr !== typeof undefined && maxlAttr !== false) {
// create a max equivelant
if (typeof maxlAttr !== typeof undefined && maxlAttr !== false){
while (x < maxlAttr) {
max += "9";
x++;
}
maxAttR = max;
}
// Permissible Keys that can be used while the input has reached maxlength
var keys = [
8, // backspace
9, // tab
13, // enter
46, // delete
37, 39, 38, 40 // arrow keys<^>v
]
// Apply changes to element
$(this)
.attr("max", maxAttR) //add existing max or new max
.keydown(function(event) {
// restrict key press on length reached unless key being used is in keys array or there is highlighted text
if ($(this).val().length == maxlAttr && $.inArray(event.which, keys) == -1 && methods.isTextSelected() == false) return false;
});;
}
},
/*
* isTextSelected returns true if there is a selection on the page.
* This is so that if the user selects text and then presses a number
* it will behave as normal by replacing the selection with the value
* of the key pressed.
*/
isTextSelected: function() {
// set text variable
text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
return (text.length > 0);
}
};
$.maxlengthNumber = function(){
// Get all number inputs that have maxlength
methods.addMax.call($("input[type=number]"));
}
})($)
// Apply it:
$.maxlengthNumber();
What you want to do is a combination of part of 1 and all of 2.
You need to use the PowerMockito.mockStatic to enable static mocking for all static methods of a class. This means make it possible to stub them using the when-thenReturn syntax.
But the 2-argument overload of mockStatic you are using supplies a default strategy for what Mockito/PowerMock should do when you call a method you haven't explicitly stubbed on the mock instance.
From the javadoc:
Creates class mock with a specified strategy for its answers to interactions. It's quite advanced feature and typically you don't need it to write decent tests. However it can be helpful when working with legacy systems. It is the default answer so it will be used only when you don't stub the method call.
The default default stubbing strategy is to just return null, 0 or false for object, number and boolean valued methods. By using the 2-arg overload, you're saying "No, no, no, by default use this Answer subclass' answer method to get a default value. It returns a Long, so if you have static methods which return something incompatible with Long, there is a problem.
Instead, use the 1-arg version of mockStatic to enable stubbing of static methods, then use when-thenReturn to specify what to do for a particular method. For example:
import static org.mockito.Mockito.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
class ClassWithStatics {
public static String getString() {
return "String";
}
public static int getInt() {
return 1;
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStatics.class)
public class StubJustOneStatic {
@Test
public void test() {
PowerMockito.mockStatic(ClassWithStatics.class);
when(ClassWithStatics.getString()).thenReturn("Hello!");
System.out.println("String: " + ClassWithStatics.getString());
System.out.println("Int: " + ClassWithStatics.getInt());
}
}
The String-valued static method is stubbed to return "Hello!", while the int-valued static method uses the default stubbing, returning 0.
You should use built-in bootstrap4 spacing classes for customizing the spacing of elements, that's more convenient method .
Yes, a struct
is identical to a class
except for the default access level (member-wise and inheritance-wise). (and the extra meaning class
carries when used with a template)
Every functionality supported by a class is consequently supported by a struct. You'd use methods the same as you'd use them for a class.
struct foo {
int bar;
foo() : bar(3) {} //look, a constructor
int getBar()
{
return bar;
}
};
foo f;
int y = f.getBar(); // y is 3
The parseInt()
function parses a string
and returns an integer
,10 is the Radix or Base
[DOC]
var number = parseInt(id.substring(indexPos) , 10 ) + 1;
Sometimes getBoundingClientRect()
object's property value shows 0 for IE. In that case you have to set display = 'block'
for the element. You can use below code for all browser to get offset.
Extend jQuery functionality :
(function($) {
jQuery.fn.weOffset = function () {
var de = document.documentElement;
$(this).css("display", "block");
var box = $(this).get(0).getBoundingClientRect();
var top = box.top + window.pageYOffset - de.clientTop;
var left = box.left + window.pageXOffset - de.clientLeft;
return { top: top, left: left };
};
}(jQuery));
Use :
var elementOffset = $("#" + elementId).weOffset();
None of the answers to date mention the effect of the innodb_page_size parameter. Possibly because changing this parameter was not a supported operation prior to MySQL 5.7.6. From the documentation:
The maximum row length, except for variable-length columns (VARBINARY, VARCHAR, BLOB and TEXT), is slightly less than half of a database page for 4KB, 8KB, 16KB, and 32KB page sizes. For example, the maximum row length for the default innodb_page_size of 16KB is about 8000 bytes. For an InnoDB page size of 64KB, the maximum row length is about 16000 bytes. LONGBLOB and LONGTEXT columns must be less than 4GB, and the total row length, including BLOB and TEXT columns, must be less than 4GB.
Note that increasing the page size is not without its drawbacks. Again from the documentation:
As of MySQL 5.7.6, 32KB and 64KB page sizes are supported but ROW_FORMAT=COMPRESSED is still unsupported for page sizes greater than 16KB. For both 32KB and 64KB page sizes, the maximum record size is 16KB. For innodb_page_size=32k, extent size is 2MB. For innodb_page_size=64k, extent size is 4MB.
A MySQL instance using a particular InnoDB page size cannot use data files or log files from an instance that uses a different page size. This limitation could affect restore or downgrade operations using data from MySQL 5.6, which does support page sizes other than 16KB.
Give your body
tag an overflow: scroll;
body {
overflow: scroll;
}
or if you only want a vertical scrollbar use overflow-y
body {
overflow-y: scroll;
}
I've found an answer to this problem :)
SET @update_id := 0;
UPDATE some_table SET column_name = 'value', id = (SELECT @update_id := id)
WHERE some_other_column = 'blah' LIMIT 1;
SELECT @update_id;
EDIT by aefxx
This technique can be further expanded to retrieve the ID of every row affected by an update statement:
SET @uids := null;
UPDATE footable
SET foo = 'bar'
WHERE fooid > 5
AND ( SELECT @uids := CONCAT_WS(',', fooid, @uids) );
SELECT @uids;
This will return a string with all the IDs concatenated by a comma.
How about this one.
ArrayList<String> names = new ArrayList<String>();
Collections.addAll(names, "Ryan", "Julie", "Bob");
There are 2 main kinds of transactions; connection transactions and ambient transactions. A connection transaction (such as SqlTransaction) is tied directly to the db connection (such as SqlConnection), which means that you have to keep passing the connection around - OK in some cases, but doesn't allow "create/use/release" usage, and doesn't allow cross-db work. An example (formatted for space):
using (IDbTransaction tran = conn.BeginTransaction()) {
try {
// your code
tran.Commit();
} catch {
tran.Rollback();
throw;
}
}
Not too messy, but limited to our connection "conn". If we want to call out to different methods, we now need to pass "conn" around.
The alternative is an ambient transaction; new in .NET 2.0, the TransactionScope object (System.Transactions.dll) allows use over a range of operations (suitable providers will automatically enlist in the ambient transaction). This makes it easy to retro-fit into existing (non-transactional) code, and to talk to multiple providers (although DTC will get involved if you talk to more than one).
For example:
using(TransactionScope tran = new TransactionScope()) {
CallAMethodThatDoesSomeWork();
CallAMethodThatDoesSomeMoreWork();
tran.Complete();
}
Note here that the two methods can handle their own connections (open/use/close/dispose), yet they will silently become part of the ambient transaction without us having to pass anything in.
If your code errors, Dispose() will be called without Complete(), so it will be rolled back. The expected nesting etc is supported, although you can't roll-back an inner transaction yet complete the outer transaction: if anybody is unhappy, the transaction is aborted.
The other advantage of TransactionScope is that it isn't tied just to databases; any transaction-aware provider can use it. WCF, for example. Or there are even some TransactionScope-compatible object models around (i.e. .NET classes with rollback capability - perhaps easier than a memento, although I've never used this approach myself).
All in all, a very, very useful object.
Some caveats:
Running as administrator then following other comments fixed the problem for me :)
IF they are both UTC date-time values you can do TimeSpan diff = dateTime1 - dateTime2;
Otherwise your chance of getting the correct answer in every single possible case is zero.
head
section of your html page paste: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
and then the reference to your script eg: <script src="uploadfuntion.js"> </script>
4.Lastly you should ensure there are elements that match the selectors in the code.
When the first characters in a script are #!
, that is called the shebang. If your file starts with
#!/path/to/something
the standard is to run something
and pass the rest of the file to that program as an input.
With that said, the difference between #!/bin/bash
, #!/bin/sh
, or even #!/bin/zsh
is whether the bash, sh, or zsh programs are used to interpret the rest of the file. bash
and sh
are just different programs, traditionally. On some Linux systems they are two copies of the same program. On other Linux systems, sh
is a link to dash
, and on traditional Unix systems (Solaris, Irix, etc) bash
is usually a completely different program from sh
.
Of course, the rest of the line doesn't have to end in sh. It could just as well be #!/usr/bin/python
, #!/usr/bin/perl
, or even #!/usr/local/bin/my_own_scripting_language
.
As hinted at in yatima2975's answer, there is an additional difference:
substr()
accepts a negative starting position as an offset from the end of the string. substring()
does not.
From MDN:
If start is negative, substr() uses it as a character index from the end of the string.
So to sum up the functional differences:
substring(begin-offset, end-offset-exclusive)
where begin-offset is 0
or greater
substr(begin-offset, length)
where begin-offset may also be negative
net stop <your service> && net start <your service>
No net restart
, unfortunately.
While Loop:
while(test-condition)
{
statements;
increment/decrement;
}
Do While Loop:
do
{
statements;
increment/decrement;
}while(test-condition);
Find out more on this topic here: Difference Between While and Do While Loop
This is valid for C programming, Java programming and other languages as well because the concepts remain the same, only the syntax changes.
Also, another small but a differentiating factor to note is that the do while loop consists of a semicolon at the end of the while condition.
If this is just a one-off exercise, as an easier alternative, you could apply filters to your source data, and then copy and paste the filtered rows into your new worksheet?
This an example from my project for rating using radio
buttons and its label
s
<div class="rating">
<%= form.radio_button :star, '1' %>
<%= form.label :star, '?', value: '1' %>
<%= form.radio_button :star, '2' %>
<%= form.label :star, '?', value: '2' %>
<%= form.radio_button :star, '3' %>
<%= form.label :star, '?', value: '3' %>
<%= form.radio_button :star, '4' %>
<%= form.label :star, '?', value: '4' %>
<%= form.radio_button :star, '5' %>
<%= form.label :star, '?', value: '5' %>
</div>
You can also use the jquery prop() method for this.
$(function(){
$('yourselector').prop('target', '_blank');
});
Historically in C, if you omitted a datatype "int" was assumed. So "unsigned" is a shorthand for "unsigned int". This has been considered bad practice for a long time, but there is still a fair amount of code out there that uses it.
All other unswers require to run your code inside a new thread. In some simple use cases you may just want to wait a bit and continue execution within the same thread/flow.
Code below demonstrates that technique. Keep in mind this is similar to what java.util.Timer does under the hood but more lightweight.
import java.util.concurrent.TimeUnit;
public class DelaySample {
public static void main(String[] args) {
DelayUtil d = new DelayUtil();
System.out.println("started:"+ new Date());
d.delay(500);
System.out.println("half second after:"+ new Date());
d.delay(1, TimeUnit.MINUTES);
System.out.println("1 minute after:"+ new Date());
}
}
DelayUtil Implementation
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class DelayUtil {
/**
* Delays the current thread execution.
* The thread loses ownership of any monitors.
* Quits immediately if the thread is interrupted
*
* @param duration the time duration in milliseconds
*/
public void delay(final long durationInMillis) {
delay(durationInMillis, TimeUnit.MILLISECONDS);
}
/**
* @param duration the time duration in the given {@code sourceUnit}
* @param unit
*/
public void delay(final long duration, final TimeUnit unit) {
long currentTime = System.currentTimeMillis();
long deadline = currentTime+unit.toMillis(duration);
ReentrantLock lock = new ReentrantLock();
Condition waitCondition = lock.newCondition();
while ((deadline-currentTime)>0) {
try {
lock.lockInterruptibly();
waitCondition.await(deadline-currentTime, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
} finally {
lock.unlock();
}
currentTime = System.currentTimeMillis();
}
}
}
dictionary's setdefault is a good way to update an existing dict entry if it's there, or create a new one if it's not all in one go:
Looping style:
# This is our sample data
data = [("Milter", "Miller", 4), ("Milter", "Miler", 4), ("Milter", "Malter", 2)]
# dictionary we want for the result
dictionary = {}
# loop that makes it work
for realName, falseName, position in data:
dictionary.setdefault(realName, {})[falseName] = position
dictionary now equals:
{'Milter': {'Malter': 2, 'Miler': 4, 'Miller': 4}}
ArrayList.clear(From Java Doc):
Removes all of the elements from this list. The list will be empty after this call returns
One more note, for our web application, I found that we had huge performance issues due to contention between threads over locks... so the moral was to think over the locking scheme very carefully. We ended up having worker threads to throttle too many requests using an asynchronous http handler, otherwise the application would just get overwhelmed and crash and burn. It meant a huge backlog could pile up, but at least the site would stay up.
My version of the loop ;)
var lowEnd = 1;
var highEnd = 25;
var arr = [];
while(lowEnd <= highEnd){
arr.push(lowEnd++);
}
Sorry this isn't complete because I can't test it here, but it may get you off in the right direction. I'm translating from something I use that makes a similar query:
select mt.section, mt1.count as Active, mt2.count as Inactive
from mytable mt
left join (select section, count from mytable where status='Active')mt1
on mt.section = mt1.section
left join (select section, count from mytable where status='Inactive')mt2
on mt.section = mt2.section
group by mt.section,
mt1.count,
mt2.count
order by mt.section asc;
The code I'm working from is:
select m.typeID, m1.highBid, m2.lowAsk, m1.highBid - m2.lowAsk as diff, 100*(m1.highBid - m2.lowAsk)/m2.lowAsk as diffPercent
from mktTrades m
left join (select typeID,MAX(price) as highBid from mktTrades where bid=1 group by typeID)m1
on m.typeID = m1.typeID
left join (select typeID,MIN(price) as lowAsk from mktTrades where bid=0 group by typeID)m2
on m1.typeID = m2.typeID
group by m.typeID,
m1.highBid,
m2.lowAsk
order by diffPercent desc;
which will return a typeID, the highest price bid and the lowest price asked and the difference between the two (a positive difference would mean something could be bought for less than it can be sold).
I can recommend interesting solution for Linux fans. After I explored this solution, I've switched from DependencyWalker to this.
You can use your favorite ldd
over Windows-related exe
, dll
.
To do this you need to install Cygwin (basic installation, without additional packages required) on your Windows and then just start Cygwin Terminal
. Now you can run your favorite Linux commands, including:
$ ldd your_dll_file.dll
UPD: You can use ldd
also through git bash terminal on Windows. No need to install cygwin in case if you have git already installed.
Before doing
git clone https://example.com/root/test.git
make sure that you have added ssh key in your system. Follow this : https://gitlab.com/profile/keys .
Once added run the above command. It will prompt for your gitlab username and password and on authentication, it will be cloned.
You need to use javascript to show the name of the choosed file, as written in the documentation: https://getbootstrap.com/docs/4.5/components/forms/#file-browser
Here you can find the solution: Bootstrap 4 File Input
That's the code for your example:
<html lang="en">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
</head>
<body>
<div class="input-group mb-3">
<div class="custom-file">
<input type="file" class="custom-file-input" id="inputGroupFile02"/>
<label class="custom-file-label" for="inputGroupFile02">Choose file</label>
</div>
<div class="input-group-append">
<button class="btn btn-primary">Upload</button>
</div>
</div>
<script>
$('#inputGroupFile02').on('change',function(){
//get the file name
var fileName = $(this).val();
//replace the "Choose a file" label
$(this).next('.custom-file-label').html(fileName);
})
</script>
</body>
</html>
You can try using AppDomain.UnhandledException and see if that lets you catch it.
**EDIT*
Here is some more information that might be useful (it's a long read).
In IE11 Windows 7 this worked for me,
background-size: 100% 100%;
I was running a PowerShell script into the task scheduller but i forgot to enable the execution-policy to unrestricted, in an elevated PowerShell console:
Set-ExecutionPolicy Unrestricted
After that, the error disappeared (0x1).
Here's a fairly generic version; I haven't compiled it, so there are probably typos, but you should get the idea,
void SwapBytes(void *pv, size_t n)
{
assert(n > 0);
char *p = pv;
size_t lo, hi;
for(lo=0, hi=n-1; hi>lo; lo++, hi--)
{
char tmp=p[lo];
p[lo] = p[hi];
p[hi] = tmp;
}
}
#define SWAP(x) SwapBytes(&x, sizeof(x));
NB: This is not optimised for speed or space. It is intended to be clear (easy to debug) and portable.
Update 2018-04-04 Added the assert() to trap the invalid case of n == 0, as spotted by commenter @chux.
Yes, that should work. But if you need to see the absolute path, this is all you need:
(Get-Item .).FullName
I just found this quite impressive tutorial about jquery to javascript conversion from Jeffrey Way on Jan 19th 2012 *Copyright © 2014 Envato*
:
http://net.tutsplus.com/tutorials/javascript-ajax/from-jquery-to-javascript-a-reference/
Whether we like it or not, more and more developers are being introduced to the world of JavaScript through jQuery first. In many ways, these newcomers are the lucky ones. They have access to a plethora of new JavaScript APIs, which make the process of DOM traversal (something that many folks depend on jQuery for) considerably easier. Unfortunately, they don’t know about these APIs!
In this article, we’ll take a variety of common jQuery tasks, and convert them to both modern and legacy JavaScript.
I proposed it in a comment to OP, and after his suggestion, i publish it has an answer for everyone to refer to.
Also, Jeffrey Way mentioned about his inspiration witch seems to be a good primer for understanding : http://sharedfil.es/js-48hIfQE4XK.html
Has a teaser, this document comparison of jQuery to javascript :
$(document).ready(function() {
// code…
});
document.addEventListener("DOMContentLoaded", function() {
// code…
});
$("a").click(function() {
// code…
})
[].forEach.call(document.querySelectorAll("a"), function(el) {
el.addEventListener("click", function() {
// code…
});
});
You should take a look.
I have faced the same issue. I am on a AWS Free Microinstance which has less memory. I always try one of the below options and it always works (Before all this please check if you have the latest version of composer installed)
sudo php -dmemory_limit=750M composer.phar update
or remove the contents of the vendor folder and try composer update.
sudo rm -rf vendor
sudo php -dmemory_limit=750M composer.phar update --no-scripts --prefer-dist
sudo php artisan --dump-autoload
The second option tries to update all the components, if there is no update, it picks up the package from the cache else picks up from the dist
Note: Please change the memory limit as per your choice.
or
Create a swap partition and try. Swap partition is the portion of the hard drive that linux uses as virtual memory when it runs out of physical memory. It's similar to the windows swap file only instead of using an actual file, linux uses a partition on the hard drive instead.
Hope this helps
Both attributes have been added to Bootstrap CDN to implement Subresource Integrity.
Subresource Integrity defines a mechanism by which user agents may verify that a fetched resource has been delivered without unexpected manipulation Reference
Integrity attribute is to allow the browser to check the file source to ensure that the code is never loaded if the source has been manipulated.
Crossorigin attribute is present when a request is loaded using 'CORS' which is now a requirement of SRI checking when not loaded from the 'same-origin'. More info on crossorigin
J.F. Sebastian's answer is most elegant but requires python 2.6 as fortran pointed out.
For Python version < 2.6, here's the best I can come up with:
from itertools import repeat,ifilter,chain
chain(ifilter(predicate,seq),repeat(None)).next()
Alternatively if you needed a list later (list handles the StopIteration), or you needed more than just the first but still not all, you can do it with islice:
from itertools import islice,ifilter
list(islice(ifilter(predicate,seq),1))
UPDATE: Although I am personally using a predefined function called first() that catches a StopIteration and returns None, Here's a possible improvement over the above example: avoid using filter / ifilter:
from itertools import islice,chain
chain((x for x in seq if predicate(x)),repeat(None)).next()
Just add attribute runAllManagedModulesForAllRequests="true"
to system.webServer\modules
in web.config.
This attribute is enabled by default in MVC and Dynamic Data projects.
There's an related question to which I answered:
#pragma once
does have one drawback (other than being non-standard) and that is if you have the same file in different locations (we have this because our build system copies files around) then the compiler will think these are different files.
I'm adding the answer here too in case someone stumbles over this question and not the other.
Solution for people who prefer clicking:
Install sourcetree (it is free)
Check how your commits look like. Most likely you have something similar to this
Right click on parent commit. In our case it is master branch.
You can squash commit with previous one by clicking a button. In our case we have to click 2 times. You can also change commit message
Side note: If you were pushing your partial commits to remote you have to use force push after squash
I faced the same 415
http error when sending objects, serialized into JSON, via PUT/PUSH requests to my JAX-rs services, in other words my server was not able to de-serialize the objects from JSON.
In my case, the server was able to serialize successfully the same objects in JSON when sending them into its responses.
As mentioned in the other responses I have correctly set the Accept
and Content-Type
headers to application/json
, but it doesn't suffice.
Solution
I simply forgot a default constructor with no parameters for my DTO objects. Yes this is the same reasoning behind @Entity objects, you need a constructor with no parameters for the ORM to instantiate objects and populate the fields later.
Adding the constructor with no parameters to my DTO objects solved my issue. Here follows an example that resembles my code:
Wrong
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class NumberDTO {
public NumberDTO(Number number) {
this.number = number;
}
private Number number;
public Number getNumber() {
return number;
}
public void setNumber(Number string) {
this.number = string;
}
}
Right
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class NumberDTO {
public NumberDTO() {
}
public NumberDTO(Number number) {
this.number = number;
}
private Number number;
public Number getNumber() {
return number;
}
public void setNumber(Number string) {
this.number = string;
}
}
I lost hours, I hope this'll save yours ;-)
This is a simple way to get a byte[]
, but part of the point of using a ByteBuffer
is avoiding having to create a byte[]
. Perhaps you can get whatever you wanted to get from the byte[]
directly from the ByteBuffer
.
FWIW, here's what I used:
expr "${arr[*]}" : ".*\<$item\>"
This works where there are no delimiters in any of the array items or in the search target. I didn't need to solve the general case for my applicaiton.
$("#btnSubmit").click(function(){
alert("button");
});
Something like this should do the trick (However, read after the snippet for more info)
CREATE PROCEDURE GetFilteredData()
BEGIN
DECLARE bDone INT;
DECLARE var1 CHAR(16); -- or approriate type
DECLARE Var2 INT;
DECLARE Var3 VARCHAR(50);
DECLARE curs CURSOR FOR SELECT something FROM somewhere WHERE some stuff;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET bDone = 1;
DROP TEMPORARY TABLE IF EXISTS tblResults;
CREATE TEMPORARY TABLE IF NOT EXISTS tblResults (
--Fld1 type,
--Fld2 type,
--...
);
OPEN curs;
SET bDone = 0;
REPEAT
FETCH curs INTO var1,, b;
IF whatever_filtering_desired
-- here for whatever_transformation_may_be_desired
INSERT INTO tblResults VALUES (var1, var2, var3 ...);
END IF;
UNTIL bDone END REPEAT;
CLOSE curs;
SELECT * FROM tblResults;
END
A few things to consider...
Concerning the snippet above:
More generally: trying to avoid needing a cursor.
I purposely named the cursor variable curs[e], because cursors are a mixed blessing. They can help us implement complicated business rules that may be difficult to express in the declarative form of SQL, but it then brings us to use the procedural (imperative) form of SQL, which is a general feature of SQL which is neither very friendly/expressive, programming-wise, and often less efficient performance-wise.
Maybe you can look into expressing the transformation and filtering desired in the context of a "plain" (declarative) SQL query.
In my opinion the article written in Hibernate Pitfall: Why Relationships Should Be Lazy is exactly opposite of real N+1 issue is.
If you need correct explanation please refer Hibernate - Chapter 19: Improving Performance - Fetching Strategies
Select fetching (the default) is extremely vulnerable to N+1 selects problems, so we might want to enable join fetching
Theta(n): A function f(n)
belongs to Theta(g(n))
, if there exists positive constants c1
and c2
such that f(n)
can be sandwiched between c1(g(n))
and c2(g(n))
. i.e it gives both upper and as well as lower bound.
Theta(g(n)) = { f(n) : there exists positive constants c1,c2 and n1 such that 0<=c1(g(n))<=f(n)<=c2(g(n)) for all n>=n1 }
when we say f(n)=c2(g(n))
or f(n)=c1(g(n))
it represents asymptotically tight bound.
O(n): It gives only upper bound (may or may not be tight)
O(g(n)) = { f(n) : there exists positive constants c and n1 such that 0<=f(n)<=cg(n) for all n>=n1}
ex: The bound 2*(n^2) = O(n^2)
is asymptotically tight, whereas the bound 2*n = O(n^2)
is not asymptotically tight.
o(n): It gives only upper bound (never a tight bound)
the notable difference between O(n) & o(n) is f(n) is less than cg(n) for all n>=n1 but not equal as in O(n).
ex: 2*n = o(n^2)
, but 2*(n^2) != o(n^2)
Should you want to clear the array with something other than a value, std::file wont cut it; instead I found std::generate useful. e.g. I had a vector of lists I wanted to initialize
std::generate(v.begin(), v.end(), [] () { return std::list<X>(); });
You can do ints too e.g.
std::generate(v.begin(), v.end(), [n = 0] () mutable { return n++; });
or just
std::generate(v.begin(), v.end(), [] (){ return 0; });
but I imagine std::fill is faster for the simplest case
Given a predefined m-by-n
matrix size and the target value val
, in your example:
m = 1;
n = 10;
val = 5;
there are currently 7
different approaches that come to my mind:
1) Using the repmat function (0.094066 seconds)
A = repmat(val,m,n)
2) Indexing on the undefined matrix with assignment (0.091561 seconds)
A(1:m,1:n) = val
3) Indexing on the target value using the ones function (0.151357 seconds)
A = val(ones(m,n))
4) Default initialization with full assignment (0.104292 seconds)
A = zeros(m,n);
A(:) = val
5) Using the ones function with multiplication (0.069601 seconds)
A = ones(m,n) * val
6) Using the zeros function with addition (0.057883 seconds)
A = zeros(m,n) + val
7) Using the repelem function (0.168396 seconds)
A = repelem(val,m,n)
After the description of each approach, between parentheses, its corresponding benchmark performed under Matlab 2017a
and with 100000
iterations. The winner is the 6th
approach, and this doesn't surprise me.
The explaination is simple: allocation generally produces zero-filled slots of memory... hence no other operations are performed except the addition of val
to every member of the matrix, and on the top of that, input arguments sanitization is very short.
The same cannot be said for the 5th
approach, which is the second fastest one because, despite the input arguments sanitization process being basically the same, on memory side three operations are being performed instead of two:
1
val
This was the order I got everything working. The second point is the most important one. Scipy needs Numpy+MKL
, not just vanilla Numpy
.
pip install "file path"
(download Numpy+MKL wheel from here http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy)pip install scipy
My issue was (as OP suggested) a corrupt .gitignore file. I didn't believe that it was and ignored the possibility until everything else failed. The corruption didn't show up in vi
, but there were two bytes on the start of the file that caused the .gitignore file to be ignored. For me, these only showed up when I typed cat .gitignore
, which showed:
??# Built application files
*.apk
*.ap_
# ...
I have no idea how these ended up there, but recreating the file fixed the issue. A hex analysis of the corrupt file showed the following:
user@dev ~/project/myproject $ xxd -b .gitignore
00000000: 11111111 11111110 00100011 00000000 00100000 00000000 ..#. .
00000006: 01000010 00000000 01110101 00000000 01101001 00000000 B.u.i.
Simplest solution:
Just add quotes, I really don't know why it's not auto-implemented by Spring boot when response type defined as application/json, but it works great.
@PostMapping("/create")
public String foo()
{
String result = "something"
return "\"" + result + "\"";
}
Real-Time Object-Oriented Modeling was fantastic (published in 1994 and now selling for as little as 81 cents, plus $3.99 shipping).
On many devices (such as the iPhone), it prevents the user from using the browser's zoom. If you have a map and the browser does the zooming, then the user will see a big ol' pixelated image with huge pixelated labels. The idea is that the user should use the zooming provided by Google Maps. Not sure about any interaction with your plugin, but that's what it's there for.
More recently, as @ehfeng notes in his answer, Chrome for Android (and perhaps others) have taken advantage of the fact that there's no native browser zooming on pages with a viewport tag set like that. This allows them to get rid of the dreaded 300ms delay on touch events that the browser takes to wait and see if your single touch will end up being a double touch. (Think "single click" and "double click".) However, when this question was originally asked (in 2011), this wasn't true in any mobile browser. It's just added awesomeness that fortuitously arose more recently.
merge into x as target using y as Source on target.ID = Source.ID
when not matched by target then insert
when matched then update
when not matched by source and target.ID is not null then
update whatevercolumn = 'isdeleted' ;
Open in new Tab Solution:
"workbench.editor.showTabs": true
If I am not mistaken, this is what tells the JVM how much successive calls it will accept before issuing a StackOverflowError. Not something you wish to change generally.
In case if someone returns with the same question for Android platform, you cannot use the inbuilt remove()
method if you are targeting for Android API-18 or less. The remove()
method is added on API level 19. Thus, the best possible thing to do is to extend the JSONArray
to create a compatible override for the remove()
method.
public class MJSONArray extends JSONArray {
@Override
public Object remove(int index) {
JSONArray output = new JSONArray();
int len = this.length();
for (int i = 0; i < len; i++) {
if (i != index) {
try {
output.put(this.get(i));
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
}
return output;
//return this; If you need the input array in case of a failed attempt to remove an item.
}
}
EDIT As Daniel pointed out, handling an error silently is bad style. Code improved.
void main(){
var x = "4";
int number = int.parse(x);//STRING to INT
var y = "4.6";
double doubleNum = double.parse(y);//STRING to DOUBLE
var z = 55;
String myStr = z.toString();//INT to STRING
}
int.parse() and double.parse() can throw an error when it couldn't parse the String
You have to install a Selenium Server (a Hub) and register your remote WebDriver to it. Then, your client will talk to the Hub which will find a matching WebDriver to execute your test.
You can have a look at here for more information.
I had window 7 (64 bit) and Python 2.7.12,
I uninstalled it by clicking the python installer from the "download" directory then I selected remove python then I clicked “ finish”.
I also removed the remaining python associated directory & files from the c: drive and also from “my documents” folder, since I created some files there.
In my case, my running php version is 7.1.x on mac OSX . I installed intl command using brew install php71-intl. Placing extension=intl.so inside php.ini was no effect at all. Finally i looked for extension installed directory and there i saw intl.so and placed that path (extension=/usr/local/Cellar/php71-intl/7.1.11_20/intl.so) to my php.ini file and it solved my problem.
Had a similar issue, it turned out the listening port printed was different from what it actually was. Typos in the request string or listening function might make the target server appear to not exist.
Suposse you have
Class1
public class Class1 {
//Your class code above
}
Class2
public class Class2 {
}
and then you can use Class2 in different ways.
Class Field
public class Class1{
private Class2 class2 = new Class2();
}
Method field
public class Class1 {
public void loginAs(String username, String password)
{
Class2 class2 = new Class2();
class2.invokeSomeMethod();
//your actual code
}
}
Static methods from Class2 Imagine this is your class2.
public class Class2 {
public static void doSomething(){
}
}
from class1 you can use doSomething from Class2 whenever you want
public class Class1 {
public void loginAs(String username, String password)
{
Class2.doSomething();
//your actual code
}
}
You can easily validate an XML file or tree against an XML Schema (XSD) with the xmlschema Python package. It's pure Python, available on PyPi and doesn't have many dependencies.
Example - validate a file:
import xmlschema
xmlschema.validate('doc.xml', 'some.xsd')
The method raises an exception if the file doesn't validate against the XSD. That exception then contains some violation details.
If you want to validate many files you only have to load the XSD once:
xsd = xmlschema.XMLSchema('some.xsd')
for filename in filenames:
xsd.validate(filename)
If you don't need the exception you can validate like this:
if xsd.is_valid('doc.xml'):
print('do something useful')
Alternatively, xmlschema directly works on file objects and in memory XML trees (either created with xml.etree.ElementTree or lxml). Example:
import xml.etree.ElementTree as ET
t = ET.parse('doc.xml')
result = xsd.is_valid(t)
print('Document is valid? {}'.format(result))
func Ternary(statement bool, a, b interface{}) interface{} {
if statement {
return a
}
return b
}
func Abs(n int) int {
return Ternary(n >= 0, n, -n).(int)
}
This will not outperform if/else and requires cast but works. FYI:
BenchmarkAbsTernary-8 100000000 18.8 ns/op
BenchmarkAbsIfElse-8 2000000000 0.27 ns/op
My open source application BugTracker.NET includes a POP3 client that can parse MIME. Both the POP3 code and the MIME code are from other authors, but you can see how it all fits together in my app.
For the MIME parsing, I use http://anmar.eu.org/projects/sharpmimetools/.
See the file POP3Main.cs, POP3Client.cs, and insert_bug.aspx
while working on a security app which needed to get the phone number of who so ever my phone might get into their hands, I had to do this; 1. receive Boot completed and then try getting Line1_Number from telephonyManager which returns a string result. 2. compare the String result with my own phone number and if they don't match or string returns null then, 3. secretly send an SMS containing the string result plus a special sign to my office number. 4. if message sending fails, start a service and keep trying after each hour until sent SMS pending intent returns successful. With this steps I could get the number of the person using my lost phone. it doesn't matter if the person is charged.
You can use exit method to quit an ios app :
exit(0);
You should say same alert message and ask him to quit
Another way is by using [[NSThread mainThread] exit]
However you should not do this way
According to Apple, your app should not terminate on its own. Since the user did not hit the Home button, any return to the Home screen gives the user the impression that your app crashed. This is confusing, non-standard behavior and should be avoided.
One more solution below,
If the entire folder is removed and SVNis throwing the error "admin file .svn is missing", the following will be used to resolve the conflict to working state.
svn resolve --accept working "file / directory name "
<%if (System.Configuration.ConfigurationManager.AppSettings["OperationalMode"] != "live") {%>
[<%=System.Environment.MachineName%>]
<%}%>
Please see the below code:
if(dataset.select_dtypes(include=[np.number]).shape[1] > 0):
display(dataset.select_dtypes(include=[np.number]).describe())
if(dataset.select_dtypes(include=[np.object]).shape[1] > 0):
display(dataset.select_dtypes(include=[np.object]).describe())
This way you can check whether the value are numeric such as float and int or the srting values. the second if statement is used for checking the string values which is referred by the object.
Simple, one liner:
import datetime as dt
previous_month = (dt.date.today().replace(day=1) - dt.timedelta(days=1)).month
Your syntax is incorrect. The var
keyword in your for
loop must be followed by a variable name, in this case its propName
var propValue;
for(var propName in nyc) {
propValue = nyc[propName]
console.log(propName,propValue);
}
I suggest you have a look here for some basics:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
Shelljs is a very handy solution.
command: mv([options ,] source, destination)
Available options:
-f: force (default behaviour)
-n: to prevent overwriting
const shell = require('shelljs');
const status = shell.mv('README.md', '/home/my-dir');
if(status.stderr) console.log(status.stderr);
else console.log('File moved!');
No there is no difference at all in functionality.
(The same is true for all other DBMS - most of them support both styles):
Here is the current SQL reference: https://docs.oracle.com/database/121/SQLRF/conditions002.htm#CJAGAABC
The SQL standard only defines a single operator for "not equals" and that is <>
The Header
field of the Request is public. You may do this :
req.Header.Set("name", "value")
This works for me https://www.nuget.org/packages/ASquare.WindowsTaskScheduler/
It is nicely designed Fluent API.
//This will create Daily trigger to run every 10 minutes for a duration of 18 hours
SchedulerResponse response = WindowTaskScheduler
.Configure()
.CreateTask("TaskName", "C:\\Test.bat")
.RunDaily()
.RunEveryXMinutes(10)
.RunDurationFor(new TimeSpan(18, 0, 0))
.SetStartDate(new DateTime(2015, 8, 8))
.SetStartTime(new TimeSpan(8, 0, 0))
.Execute();
Responsive meta tag
To ensure proper rendering and touch zooming for all devices, add the responsive viewport meta tag to your <head>
.
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
The simplest way to do this is with a list comprehension:
[s + mystring for s in mylist]
Notice that I avoided using builtin names like list
because that shadows or hides the builtin names, which is very much not good.
Also, if you do not actually need a list, but just need an iterator, a generator expression can be more efficient (although it does not likely matter on short lists):
(s + mystring for s in mylist)
These are very powerful, flexible, and concise. Every good python programmer should learn to wield them.
Yes, there's a command git commit --amend
which is used to "fix" last commit.
In your case it would be called as:
git add the_left_out_file
git commit --amend --no-edit
The --no-edit flag allow to make amendment to commit without changing commit message.
EDIT: Warning You should never amend public commits, that you already pushed to public repository, because what amend does is actually removing from history last commit and creating new commit with combined changes from that commit and new added when amending.
You can also try using apply
with get
method of dictionary
, seems to be little faster than replace
:
data['sex'] = data['sex'].apply({1:'Male', 0:'Female'}.get)
Testing with timeit
:
%%timeit
data['sex'].replace([0,1],['Female','Male'],inplace=True)
Result:
The slowest run took 5.83 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 510 µs per loop
Using apply
:
%%timeit
data['sex'] = data['sex'].apply({1:'Male', 0:'Female'}.get)
Result:
The slowest run took 5.92 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 331 µs per loop
Note: apply
with dictionary should be used if all the possible values of the columns in the dataframe are defined in the dictionary else, it will have empty for those not defined in dictionary.
Database memory usage is a complex topic. The MySQL Performance Blog does a good job of covering your question, and lists many reasons why it's hugely impractical to "reserve" memory.
If you really want to impose a hard limit, you could do so, but you'd have to do it at the OS level as there is no built-in setting. In linux, you could utilize ulimit, but you'd likely have to modify the way MySQL starts in order to impose this.
The best solution is to tune your server down, so that a combination of the usual MySQL memory settings will result in generally lower memory usage by your MySQL installation. This will of course have a negative impact on the performance of your database, but some of the settings you can tweak in my.ini
are:
key_buffer_size
query_cache_size
query_cache_limit
table_cache
max_connections
tmp_table_size
innodb_buffer_pool_size
I'd start there and see if you can get the results you want. There are many articles out there about adjusting MySQL memory settings.
Edit:
Note that some variable names have changed in the newer 5.1.x releases of MySQL.
For example:
table_cache
Is now:
table_open_cache
Simple! The folder named ..
is the parent folder, so you can make the path to the file you need as such
var foobar = require('../config/dev/foobar.json');
If you needed to go up two levels, you would write ../../
etc
Some more details about this in this SO answer and it's comments
To answer the question literally (since GitHub is not in the question title), also be aware of this post over on superuser. EDIT: Answer copied here in relevant part, slightly modified for clarity in square brackets:
You're getting rejected because you're trying to delete the branch that your origin has currently "checked out".
If you have direct access to the repo, you can just open up a shell [in the bare repo] directory and use good old
git branch
to see what branch origin is currently on. To change it to another branch, you have to usegit symbolic-ref HEAD refs/heads/another-branch
.
It's not doable with CSS2.1, but it is possible with CSS3 attribute substring-matching selectors (which are supported in IE7+):
div[class^="status-"], div[class*=" status-"]
Notice the space character in the second attribute selector. This picks up div
elements whose class
attribute meets either of these conditions:
[class^="status-"]
— starts with "status-"
[class*=" status-"]
— contains the substring "status-" occurring directly after a space character. Class names are separated by whitespace per the HTML spec, hence the significant space character. This checks any other classes after the first if multiple classes are specified, and adds a bonus of checking the first class in case the attribute value is space-padded (which can happen with some applications that output class
attributes dynamically).
Naturally, this also works in jQuery, as demonstrated here.
The reason you need to combine two attribute selectors as described above is because an attribute selector such as [class*="status-"]
will match the following element, which may be undesirable:
<div id='D' class='foo-class foo-status-bar bar-class'></div>
If you can ensure that such a scenario will never happen, then you are free to use such a selector for the sake of simplicity. However, the combination above is much more robust.
If you have control over the HTML source or the application generating the markup, it may be simpler to just make the status-
prefix its own status
class instead as Gumbo suggests.
A lot of great answers here. Below is a sample of the stored procedure that I wrote to accomplish this task for a Web App that I am developing:
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON
-- Create Temporary Table
SELECT * INTO #tempTable FROM <YourTable> WHERE Id = Id
--To trigger the auto increment
UPDATE #tempTable SET Id = NULL
--Update new data row in #tempTable here!
--Insert duplicate row with modified data back into your table
INSERT INTO <YourTable> SELECT * FROM #tempTable
-- Drop Temporary Table
DROP TABLE #tempTable
Are you talking about getchar
function?
In Mac OS X (tried with Android Studio), do the following in Terminal
cd /android/adt-bundle-mac-x86_64/sdk/tools
sudo ./android sdk
This launches SDK manager as admin. Now update/install the packages from SDK manager and it'll work.
Everything is great but none of you explained where to download the SDK build tools
Take a look at Arrays.sort()
For a specific folder I used:
git checkout -- FolderToClean/*
Look for this:
ANY page in your project that has a missing, or different Namespace...
If you have ANY page in your project with <NO Namespace
> , OR a
DIFFERENT Namespace than Default.aspx, you will get this
"Cannot load Default.aspx", or this: "Default.aspx does not belong here".
ALSO: If you have a Redirect to a page in your Solution/Project and the page which is to be Redirected To has a bad namespace -- you may not get a compiler error, until you try and run. If the Redirect is removed or commented-out, the error goes away...
BTW -- What the hell do these error messages mean? Is this MS.Access, with the "misdirection" -- ??
DGK
If you have a list of lists, you only needed to use ...
import numpy as np
...
npa = np.asarray(someListOfLists, dtype=np.float32)
per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.
$('nameofDropDownList').prop('selectedIndex', whateverNumberasInt);
Imagine the DDL as an array with indexes, you are selecting one index. Choose the one which you want to set it to with your JS.
As simple as joining lists in python itself.
ansible -m debug -a msg="{{ '-'.join(('list', 'joined', 'together')) }}" localhost
localhost | SUCCESS => {
"msg": "list-joined-together" }
Works the same way using variables:
ansible -m debug -a msg="{{ '-'.join((var1, var2, var3)) }}" localhost
This is from the Docker documentation itself, might be of help, simple and plain:
"The host directory is, by its nature, host-dependent. For this reason, you can’t mount a host directory from Dockerfile, the VOLUME instruction does not support passing a host-dir, because built images should be portable. A host directory wouldn’t be available on all potential hosts.".
There are two branches lets say
Being in branch A you can type
git diff --color B
then this will give you a output of
The important point about this is
Text in green is inside present in Branch A
Text in red is present in Branch B
Generate the query string in the PreparedStatement to have a number of ?'s matching the number of items in your list. Here's an example:
public void myQuery(List<String> items, int other) {
...
String q4in = generateQsForIn(items.size());
String sql = "select * from stuff where foo in ( " + q4in + " ) and bar = ?";
PreparedStatement ps = connection.prepareStatement(sql);
int i = 1;
for (String item : items) {
ps.setString(i++, item);
}
ps.setInt(i++, other);
ResultSet rs = ps.executeQuery();
...
}
private String generateQsForIn(int numQs) {
String items = "";
for (int i = 0; i < numQs; i++) {
if (i != 0) items += ", ";
items += "?";
}
return items;
}
I Solved the issue simply by ensuring that I had the correct git SSH url without any trailing spaces:
[email protected]:USERNAME/REPOSITORY.git
try:
git ls-files --error-unmatch <file name>
will exit with 1 if file is not tracked
@Nicolai is correct about casting and why the condition is false for any data. i guess you prefer the first form because you want to avoid date manipulation on the input string, correct? you don't need to be afraid:
SELECT *
FROM table
WHERE update_date >= '2013-05-03'::date
AND update_date < ('2013-05-03'::date + '1 day'::interval);
You can (should) declare it as extern
in a header file, and define it in exactly 1 .c file.
Note that that .c file should also use the header and that the standard pattern looks like:
// file.h
extern int x; // declaration
// file.c
#include "file.h"
int x = 1; // definition and re-declaration
function setPixel(imageData, x, y, r, g, b, a) {
var index = 4 * (x + y * imageData.width);
imageData.data[index+0] = r;
imageData.data[index+1] = g;
imageData.data[index+2] = b;
imageData.data[index+3] = a;
}
I have had the same problem as noted above. I could not get Eclipse to install because of Java incompatibilities. The sequence I followed goes like this:
This took hours of my time. I hope this proves useful.
You can simplify that line of code slightly in C# by using a collection initialiser.
var lst = new List<string> {"test1","test2","test3"};
No.
You can achieve the same behavior by passing an Object which has smart defaults. But again it depends what your case is at hand.
It's very easy to write that yourself, and that way you have more control over things.. As the other answers say, TypeScript is not aimed at adding runtime types or functionality.
Map:
class Map<T> {
private items: { [key: string]: T };
constructor() {
this.items = {};
}
add(key: string, value: T): void {
this.items[key] = value;
}
has(key: string): boolean {
return key in this.items;
}
get(key: string): T {
return this.items[key];
}
}
List:
class List<T> {
private items: Array<T>;
constructor() {
this.items = [];
}
size(): number {
return this.items.length;
}
add(value: T): void {
this.items.push(value);
}
get(index: number): T {
return this.items[index];
}
}
I haven't tested (or even tried to compile) this code, but it should give you a starting point.. you can of course then change what ever you want and add the functionality that YOU need...
As for your "special needs" from the List, I see no reason why to implement a linked list, since the javascript array lets you add and remove items.
Here's a modified version of the List to handle the get prev/next from the element itself:
class ListItem<T> {
private list: List<T>;
private index: number;
public value: T;
constructor(list: List<T>, value: T, index: number) {
this.list = list;
this.index = index;
this.value = value;
}
prev(): ListItem<T> {
return this.list.get(this.index - 1);
}
next(): ListItem<T> {
return this.list.get(this.index + 1);
}
}
class List<T> {
private items: Array<ListItem<T>>;
constructor() {
this.items = [];
}
size(): number {
return this.items.length;
}
add(value: T): void {
this.items.push(new ListItem<T>(this, value, this.size()));
}
get(index: number): ListItem<T> {
return this.items[index];
}
}
Here too you're looking at untested code..
Hope this helps.
Javascript has a native Map object so there's no need to create your own:
let map = new Map();
map.set("key1", "value1");
console.log(map.get("key1")); // value1
wait.until(ExpectedConditions)
won't return null, it will either meet the condition or throw TimeoutException
.
You can check if the element is displayed and enabled
WebElement element = driver.findElement(By.xpath);
if (element.isDisplayed() && element.isEnabled()) {
element.click();
}
public class Student
{
public string Name { set; get; }
public int ID { set; get; }
}
class Program
{
static void Main(string[] args)
{
Student[] students =
{
new Student { Name="zoyeb" , ID=1},
new Student { Name="Siddiq" , ID=2},
new Student { Name="sam" , ID=3},
new Student { Name="james" , ID=4},
new Student { Name="sonia" , ID=5}
};
var studentCollection = from s in students select new { s.ID , s.Name};
foreach (var student in studentCollection)
{
Console.WriteLine(student.Name);
Console.WriteLine(student.ID);
}
}
}
public mySentences:Array<any> = [
{id: 1, text: 'Sentence 1'},
{id: 2, text: 'Sentence 2'},
{id: 3, text: 'Sentence 3'},
{id: 4, text: 'Sentenc4 '},
];
OR
public mySentences:Array<object> = [
{id: 1, text: 'Sentence 1'},
{id: 2, text: 'Sentence 2'},
{id: 3, text: 'Sentence 3'},
{id: 4, text: 'Sentenc4 '},
];
Well, if you're really
always up for leaving my hands on the keyboard and away from the mouse!
Than you should go here
It's not really my favorite, it's just everything!
A shortcut a day will keep the mouse away.
As long as you go into the IIS configuration and change the default location from %SystemDrive%\InetPub to %SystemDrive%\www for each of the services (web, ftp) there shouldn't be any problems. Of course, you can't protect against other applications that might install stuff into that directory by default, instead of checking the configuration.
My recommendation? Don't change it -- it's not that hard to live with, and it reduces the confusion level for the next person who has to administrate the machine.
I made a quick project in visual studio 2008 for a .net 3.5 C# windows form application and was able to create the following code. I found events for both the enter and leave methods.
In the InitializeComponent() function. I added the event handler using the Visual Studio designer.
this.button1.MouseLeave += new System.EventHandler( this.button1_MouseLeave );
this.button1.MouseEnter += new System.EventHandler( this.button1_MouseEnter );
In the button event handler methods set the background images.
/// <summary>
/// Handles the MouseEnter event of the button1 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void button1_MouseEnter( object sender, EventArgs e )
{
this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img2));
}
/// <summary>
/// Handles the MouseLeave event of the button1 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void button1_MouseLeave( object sender, EventArgs e )
{
this.button1.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.img1));
}
This is exceedingly tricky in standard Unix, and most solutions run foul of newlines or some other character. However, if you are using the GNU tool set, then you can exploit the find
option -print0
and use xargs
with the corresponding option -0
(minus-zero). There are two characters that cannot appear in a simple filename; those are slash and NUL '\0'. Obviously, slash appears in pathnames, so the GNU solution of using a NUL '\0' to mark the end of the name is ingenious and fool-proof.
Instead of if-else condition use if in both conditions. it will work that way but not sure why.
http://docs.python.org/library/logging.html#logging.basicConfig
logging.basicConfig(filename='/path/to/your/log', level=....)
Here's a really nice and simple way of doing it with really easy to follow instructions using a custom MultiButtonAttribute:
To summarise, make your submit buttons like this:
<input type="submit" value="Cancel" name="action" />
<input type="submit" value="Create" name="action" />
Your actions like this:
[HttpPost]
[MultiButton(MatchFormKey="action", MatchFormValue="Cancel")]
public ActionResult Cancel()
{
return Content("Cancel clicked");
}
[HttpPost]
[MultiButton(MatchFormKey = "action", MatchFormValue = "Create")]
public ActionResult Create(Person person)
{
return Content("Create clicked");
}
And create this class:
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class MultiButtonAttribute : ActionNameSelectorAttribute
{
public string MatchFormKey { get; set; }
public string MatchFormValue { get; set; }
public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
{
return controllerContext.HttpContext.Request[MatchFormKey] != null &&
controllerContext.HttpContext.Request[MatchFormKey] == MatchFormValue;
}
}
My understanding is that, for example, you wrongly saved a file you had updated for testing purposes only. Then, when you run "git status" the file appears as "Modified" and you say some bad words. You just want the old version back and continue to work normally.
In that scenario you can just run the following command:
git checkout -- path/filename
The problem here is that the "on" is applied to all elements that exists AT THE TIME. When you create an element dynamically, you need to run the on again:
$('form').on('submit',doFormStuff);
createNewForm();
// re-attach to all forms
$('form').off('submit').on('submit',doFormStuff);
Since forms usually have names or IDs, you can just attach to the new form as well. If I'm creating a lot of dynamic stuff, I'll include a setup or bind function:
function bindItems(){
$('form').off('submit').on('submit',doFormStuff);
$('button').off('click').on('click',doButtonStuff);
}
So then whenever you create something (buttons usually in my case), I just call bindItems to update everything on the page.
createNewButton();
bindItems();
I don't like using 'body' or document elements because with tabs and modals they tend to hang around and do things you don't expect. I always try to be as specific as possible unless its a simple 1 page project.
If
$("#header").focus();
is not working then is there another element on your page with the id of header?
Use firebug to run $("#header")
and see what it returns.
use this xml change the color with your choice.
<item>
<layer-list>
<item>
<shape>
<solid android:color="@color/gray_500" />
</shape>
</item>
<!-- CONTENT LAYER -->
<item android:bottom="2dp" >
<shape>
<solid android:color="#ffffff" />
</shape>
</item>
</layer-list>
</item>
In Case if you want programmatically
public static Drawable getStorkLineDrawable(@ColorInt int colorStrok, int iSize, int left, int top, int right, int bottom)
{
GradientDrawable gradientDrawable = new GradientDrawable();
gradientDrawable.setShape(GradientDrawable.RECTANGLE);
gradientDrawable.setStroke(iSize, colorStrok);
LayerDrawable layerDrawable = new LayerDrawable(new Drawable[]{gradientDrawable});
layerDrawable.setLayerInset(0, left, top, right, bottom);
return layerDrawable;
}
call this method like
Drawable yourLineDrawable= getStorkLineDrawable(yourColor, iSize, -iSize, -iSize, -iSize, 0);
For other readers, the error can come from the fact that there is no brackets wrapping the async function:
Considering the async function initData
async function initData() {
}
This code will lead to your error:
useEffect(() => initData(), []);
But this one, won't:
useEffect(() => { initData(); }, []);
(Notice the brackets around initData()