Turns out string starting with a newline (or anything other than "<") is not considered HTML string in jQuery 1.9
http://stage.jquery.com/upgrade-guide/1.9/#jquery-htmlstring-versus-jquery-selectorstring
I have a simple and generic hack to perform key/value if statement instead of boolean-only in mustache (and in an extremely readable fashion!) :
function buildOptions (object) {
var validTypes = ['string', 'number', 'boolean'];
var value;
var key;
for (key in object) {
value = object[key];
if (object.hasOwnProperty(key) && validTypes.indexOf(typeof value) !== -1) {
object[key + '=' + value] = true;
}
}
return object;
}
With this hack, an object like this:
var contact = {
"id": 1364,
"author_name": "Mr Nobody",
"notified_type": "friendship",
"action": "create"
};
Will look like this before transformation:
var contact = {
"id": 1364,
"id=1364": true,
"author_name": "Mr Nobody",
"author_name=Mr Nobody": true,
"notified_type": "friendship",
"notified_type=friendship": true,
"action": "create",
"action=create": true
};
And your mustache template will look like this:
{{#notified_type=friendship}}
friendship…
{{/notified_type=friendship}}
{{#notified_type=invite}}
invite…
{{/notified_type=invite}}
Another difference between them is the size of the file:
To see the performance benefits of Handlebars.js we must use precompiled templates.
Your else statement should look like this (note the ^
):
{{^avatar}}
...
{{/avatar}}
In mustache this is called 'Inverted sections'.
Support for this functionality has been added to Handlebars.js, so there is no more need for external helpers.
For arrays:
{{#each myArray}}
Index: {{@index}} Value = {{this}}
{{/each}}
For objects:
{{#each myObject}}
Key: {{@key}} Value = {{this}}
{{/each}}
Note that only properties passing the hasOwnProperty
test will be enumerated.
If you need nested objects to be converted as well.
# @fn to_hash obj {{{
# @brief Convert object to hash
#
# @return [Hash] Hash representing converted object
#
def to_hash obj
Hash[obj.instance_variables.map { |key|
variable = obj.instance_variable_get key
[key.to_s[1..-1].to_sym,
if variable.respond_to? <:some_method> then
hashify variable
else
variable
end
]
}]
end # }}}
To the response of James I will only change the sorting function to make it more universal. This way it will sort text alphabetical and numbers like numbers.
if( $.text([a]) == $.text([b]) )
return 0;
if(isNaN($.text([a])) && isNaN($.text([b]))){
return $.text([a]) > $.text([b]) ?
inverse ? -1 : 1
: inverse ? 1 : -1;
}
else{
return parseInt($.text([a])) > parseInt($.text([b])) ?
inverse ? -1 : 1
: inverse ? 1 : -1;
}
It doesn't matter what your system uses as newlines if the content might be generated outside of the system.
I am amazed after receiving all of these answers, that no one has simply advised the use of the \R
escape sequence. There is only one way that I would ever consider implementing this in one of my own projects. \R
provides the most succinct and direct approach.
Code: (Demo)
$text = "one\ntwo\r\nthree\rfour\r\n\nfive";
var_export(preg_split('~\R~', $text));
Output:
array (
0 => 'one',
1 => 'two',
2 => 'three',
3 => 'four',
4 => '',
5 => 'five',
)
I've today made quite a few changes to my rails schema. I realised I needed an additional two models in a hierarchy and some others to be deleted. There were many little changes required to the models and controllers.
I added the two new models and created them, using:
rake db:migrate
Then I edited the schema.rb file. I manually removed the old models that were no longer required, changed the foreign key field as required and just reordered it a bit to make it clearer to me. I deleted all the migrations, and then re-ran the build via:
rake db:reset
It worked perfectly. All the data has to be reloaded, of course. Rails realised the migrations had been deleted and reset the high-water mark:
-- assume_migrated_upto_version(20121026094813, ["/Users/sean/rails/f4/db/migrate"])
You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.
References
add layout_gravity="center"
or "center_horizontal"
to the parent layout.
On a side note, your LinearLayout
inside your TableRow
seems un-necessary, as a TableRow
is already an horizontal LinearLayout
.
So interestingly enough this error "Transport endpoint is not connected" was caused by my having more than one Veracrypt device mounted. I closed the extra device and suddenly I had access to the drive. Hmm..
@MaxPython The answer above is missing ":"
try:
#do something
except:
# print 'error/exception'
def printError(e): print e
In IIS Manager, right click on the site and go to Manage Web Site -> Advanced Settings. Under Connection Limits option, you should see Connection Time-out.
You can and should have the users's password encrypted:
ALTER USER username WITH ENCRYPTED PASSWORD 'password';
The man page for checkout: http://git-scm.com/docs/git-checkout
The man page for clone: http://git-scm.com/docs/git-clone
To sum it up, clone is for fetching repositories you don't have, checkout is for switching between branches in a repository you already have.
Note: for those who have a SVN/CVS background and new to Git, the equivalent of git clone
in SVN/CVS is checkout
. The same wording of different terms is often confusing.
I came here because currently the WordPress table block doesn't support the colspan parameter and i thought i will replace it using CSS. This was my solution, assuming that the columns are the same width:
table {_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
table td {_x000D_
width: 50%;_x000D_
background: #dbdbdb;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
table tr:nth-child(2n+1) {_x000D_
position:relative;_x000D_
display:block;_x000D_
height:20px;_x000D_
background:green;_x000D_
}_x000D_
_x000D_
table tr:nth-child(2n+1) td {_x000D_
position:absolute;_x000D_
left:0;_x000D_
right:-100%;_x000D_
width: auto;_x000D_
top:0;_x000D_
bottom:0;_x000D_
background:red;_x000D_
text-align:center;_x000D_
}
_x000D_
<table>_x000D_
<tr>_x000D_
<td>row</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>cell</td>_x000D_
<td>cell</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>row</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>cell</td>_x000D_
<td>cell</td>_x000D_
</tr>_x000D_
</table>
_x000D_
following will show one table of dataset
DataGridView1.AutoGenerateColumns = true;
DataGridView1.DataSource = ds; // dataset
DataGridView1.DataMember = "TableName"; // table name you need to show
if you want to show multiple tables, you need to create one datatable or custom object collection out of all tables.
if two tables with same table schema
dtAll = dtOne.Copy(); // dtOne = ds.Tables[0]
dtAll.Merge(dtTwo); // dtTwo = dtOne = ds.Tables[1]
DataGridView1.AutoGenerateColumns = true;
DataGridView1.DataSource = dtAll ; // datatable
sample code to mode all tables
DataTable dtAll = ds.Tables[0].Copy();
for (var i = 1; i < ds.Tables.Count; i++)
{
dtAll.Merge(ds.Tables[i]);
}
DataGridView1.AutoGenerateColumns = true;
DataGridView1.DataSource = dtAll ;
The provided solutions do resolve the issue. However, they also impact all other textarea
elements with the same styling. I had to solve this and just created a more specific selector. Here is what I came up with to prevent invasive changes.
.modal-content textarea.form-control {
max-width: 100%;
}
While this selector may seem aggressive. It helps restrain the textarea
into the content area of the modal itself.
Additionally, the min-width
solution presented, above, works with basic bootstrap modals, though I had issues when using it with angular-ui-bootstrap modals.
Unlike stated previously 'preceding-sibling' is really the axis to use, not 'preceding' which does something completely different, it selects everything in the document that is before the start tag of the current node. (see http://www.w3schools.com/xpath/xpath_axes.asp)
Use print("use this bracket -sample text")
In Python 3 print "Hello world"
gives invalid syntax error.
To display string content in Python3 have to use this ("Hello world")
brackets.
If using VueJS, import all the js dependencies for jQuery extensions first, then import $ second...
import "../assets/js/jquery-2.2.3.min.js"
import "../assets/js/jquery-ui-1.12.1.min.js"
import "../assets/js/jquery.validate.min.js"
import $ from "jquery";
You then need to use jquery from a javascript function called from a custom wrapper defined globally in the VueJS prototype method.
This safeguards use of jQuery and jQuery UI from fighting with VueJS.
Vue.prototype.$fValidateTag = function( sTag, rRules )
{
return ValidateTag( sTag, rRules );
};
function ValidateTag( sTag, rRules )
{
Var rTagT = $( sTag );
return rParentTag.validate( sTag, rRules );
}
It looks like ByRef needs to know the size of the parameter. A declaration of Dim last_name as string doesn't specify the size of the string so it takes it as an error. Before using Worksheets(data_sheet).Range("C2").Value = ProcessString(last_name) The last_name has to be declared as Dim last_name as string *10 ' size of string is up to you but must be a fix length
No need to change the function. Function doesn't take a fix length declaration.
I know this has already been answered, but seeing so many visits here I'd like to add one version that uses the SAMPLE clause but still allows to filter the rows first:
with cte1 as (
select *
from t_your_table
where your_column = 'ABC'
)
select * from cte1 sample (5)
Note however that the base select needs a ROWID
column, which means it may not work for some views for example.
childform = new Child();
childform.Show(this);
In event childform load
this.CenterToParent();
look at this url Android adb devices unauthorized else briefly do the following:
C:\Users\*username*\.android
) and delete adbkeyC:\Windows\System32\config\systemprofile\.android
and delete adbkeyYou may find it in one of the directories above. Or just search adbkey in the Parent folders above then locate and delete.
If you simply want to set/use default profile at the time of making build through maven then, pass the argument
-Dspring.profiles.active=test
Just like
mvn clean install -Dspring.profiles.active=dev
Just don't anchor your pattern:
/Test/
The above regex will check for the literal string "Test" being found somewhere within it.
public static String getMd5OfFile(String filePath)
{
String returnVal = "";
try
{
InputStream input = new FileInputStream(filePath);
byte[] buffer = new byte[1024];
MessageDigest md5Hash = MessageDigest.getInstance("MD5");
int numRead = 0;
while (numRead != -1)
{
numRead = input.read(buffer);
if (numRead > 0)
{
md5Hash.update(buffer, 0, numRead);
}
}
input.close();
byte [] md5Bytes = md5Hash.digest();
for (int i=0; i < md5Bytes.length; i++)
{
returnVal += Integer.toString( ( md5Bytes[i] & 0xff ) + 0x100, 16).substring( 1 );
}
}
catch(Throwable t) {t.printStackTrace();}
return returnVal.toUpperCase();
}
Personally, I like this much better (which, granted, is just a different way of writing the currently selected "best answer"):
money = float(1234.5)
print('$' + format(money, ',.2f'))
Or, if you REALLY don't like "adding" multiple strings to combine them, you could do this instead:
money = float(1234.5)
print('${0}'.format(format(money, ',.2f')))
I just think both of these styles are a bit easier to read. :-)
(of course, you can still incorporate an If-Else to handle negative values as Eric suggests too)
/*link*/
$q.when(scope.regions).then(function(result) {
console.log(result);
});
var Regions = $resource('mocks/regions.json');
$scope.regions = Regions.query().$promise.then(function(response) {
return response;
});
You just need to initialize your view in onCreate() method and then in onCreateDialog() again before setView() and it should be work!
val error = JSONObject(callApi.errorBody()?.string() as String)
CustomResult.OnError(CustomNotFoundError(userMessage = error["userMessage"] as String))
open class CustomError (
val traceId: String? = null,
val errorCode: String? = null,
val systemMessage: String? = null,
val userMessage: String? = null,
val cause: Throwable? = null
)
open class ErrorThrowable(
private val traceId: String? = null,
private val errorCode: String? = null,
private val systemMessage: String? = null,
private val userMessage: String? = null,
override val cause: Throwable? = null
) : Throwable(userMessage, cause) {
fun toError(): CustomError = CustomError(traceId, errorCode, systemMessage, userMessage, cause)
}
class NetworkError(traceId: String? = null, errorCode: String? = null, systemMessage: String? = null, userMessage: String? = null, cause: Throwable? = null):
CustomError(traceId, errorCode, systemMessage, userMessage?: "Usted no tiene conexión a internet, active los datos", cause)
class HttpError(traceId: String? = null, errorCode: String? = null, systemMessage: String? = null, userMessage: String? = null, cause: Throwable? = null):
CustomError(traceId, errorCode, systemMessage, userMessage, cause)
class UnknownError(traceId: String? = null, errorCode: String? = null, systemMessage: String? = null, userMessage: String? = null, cause: Throwable? = null):
CustomError(traceId, errorCode, systemMessage, userMessage?: "Unknown error", cause)
class CustomNotFoundError(traceId: String? = null, errorCode: String? = null, systemMessage: String? = null, userMessage: String? = null, cause: Throwable? = null):
CustomError(traceId, errorCode, systemMessage, userMessage?: "Data not found", cause)`
The SetEnv.cmd
script that the "SDK command prompt" shortcut runs checks for cl.exe
in various places before setting up entries to add to PATH
. So it fails to add anything if a native C compiler is not installed.
To fix that, apply the following patch to <SDK install dir>\Bin\SetEnv.cmd
. This will also fix missing paths to other tools located in <SDK install dir>\Bin
and subfolders. Of course, you can install the C compiler instead to work around this bug.
--- SetEnv.Cmd_ 2010-04-27 19:52:00.000000000 +0400
+++ SetEnv.Cmd 2013-12-02 15:05:30.834400000 +0400
@@ -228,10 +228,10 @@
IF "%CURRENT_CPU%" =="x64" (
IF "%TARGET_CPU%" == "x64" (
+ SET "FxTools=%FrameworkDir64%\%FrameworkVersion%;%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework64\v3.5;%windir%\Microsoft.NET\Framework\v3.5;"
+ SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools\x64;%WindowsSdkDir%Bin\x64;%WindowsSdkDir%Bin;"
IF EXIST "%VCTools%\amd64\cl.exe" (
SET "VCTools=%VCTools%\amd64;%VCTools%\VCPackages;"
- SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools\x64;%WindowsSdkDir%Bin\x64;%WindowsSdkDir%Bin;"
- SET "FxTools=%FrameworkDir64%\%FrameworkVersion%;%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework64\v3.5;%windir%\Microsoft.NET\Framework\v3.5;"
) ELSE (
SET VCTools=
ECHO The x64 compilers are not currently installed.
@@ -239,10 +239,10 @@
ECHO .
)
) ELSE IF "%TARGET_CPU%" == "IA64" (
+ SET "FxTools=%FrameworkDir64%\%FrameworkVersion%;%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework64\v3.5;%windir%\Microsoft.NET\Framework\v3.5;"
+ SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools\x64;%WindowsSdkDir%Bin\x64;%WindowsSdkDir%Bin;"
IF EXIST "%VCTools%\x86_ia64\cl.exe" (
SET "VCTools=%VCTools%\x86_ia64;%VCTools%\VCPackages;"
- SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools\x64;%WindowsSdkDir%Bin\x64;%WindowsSdkDir%Bin;"
- SET "FxTools=%FrameworkDir64%\%FrameworkVersion%;%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework64\v3.5;%windir%\Microsoft.NET\Framework\v3.5;"
) ELSE (
SET VCTools=
ECHO The IA64 compilers are not currently installed.
@@ -250,10 +250,10 @@
ECHO .
)
) ELSE IF "%TARGET_CPU%" == "x86" (
+ SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
+ SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
IF EXIST "%VCTools%\cl.exe" (
SET "VCTools=%VCTools%;%VCTools%\VCPackages;"
- SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
- SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
) ELSE (
SET VCTools=
ECHO The x86 compilers are not currently installed.
@@ -263,10 +263,10 @@
)
) ELSE IF "%CURRENT_CPU%" =="IA64" (
IF "%TARGET_CPU%" == "IA64" (
+ SET "FxTools=%FrameworkDir64%\%FrameworkVersion%;%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework64\v3.5;%windir%\Microsoft.NET\Framework\v3.5;"
+ SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools\IA64;%WindowsSdkDir%Bin\IA64;%WindowsSdkDir%Bin;"
IF EXIST "%VCTools%\IA64\cl.exe" (
SET "VCTools=%VCTools%\IA64;%VCTools%;%VCTools%\VCPackages;"
- SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools\IA64;%WindowsSdkDir%Bin\IA64;%WindowsSdkDir%Bin;"
- SET "FxTools=%FrameworkDir64%\%FrameworkVersion%;%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework64\v3.5;%windir%\Microsoft.NET\Framework\v3.5;"
) ELSE (
SET VCTools=
ECHO The IA64 compilers are not currently installed.
@@ -274,10 +274,10 @@
ECHO .
)
) ELSE IF "%TARGET_CPU%" == "x64" (
+ SET "FxTools=%FrameworkDir64%\%FrameworkVersion%;%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework64\v3.5;%windir%\Microsoft.NET\Framework\v3.5;"
+ SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools\IA64;%WindowsSdkDir%Bin\IA64;%WindowsSdkDir%Bin;"
IF EXIST "%VCTools%\x86_amd64\cl.exe" (
SET "VCTools=%VCTools%\x86_amd64;%VCTools%\VCPackages;"
- SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools\IA64;%WindowsSdkDir%Bin\IA64;%WindowsSdkDir%Bin;"
- SET "FxTools=%FrameworkDir64%\%FrameworkVersion%;%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework64\v3.5;%windir%\Microsoft.NET\Framework\v3.5;"
) ELSE (
SET VCTools=
ECHO The VC compilers are not currently installed.
@@ -285,10 +285,10 @@
ECHO .
)
) ELSE IF "%TARGET_CPU%" == "x86" (
+ SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
+ SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
IF EXIST "%VCTools%\cl.exe" (
SET "VCTools=%VCTools%;%VCTools%\VCPackages;"
- SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
- SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
) ELSE (
SET VCTools=
ECHO The x86 compilers are not currently installed.
@@ -298,10 +298,10 @@
)
) ELSE IF "%CURRENT_CPU%"=="x86" (
IF "%TARGET_CPU%" == "x64" (
+ SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
+ SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
IF EXIST "%VCTools%\x86_amd64\cl.exe" (
SET "VCTools=%VCTools%\x86_amd64;%VCTools%\VCPackages;"
- SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
- SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
) ELSE (
SET VCTools=
ECHO The x64 cross compilers are not currently installed.
@@ -309,10 +309,10 @@
ECHO .
)
) ELSE IF "%TARGET_CPU%" == "IA64" (
+ SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
+ SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
IF EXIST "%VCTools%\x86_IA64\cl.exe" (
SET "VCTools=%VCTools%\x86_IA64;%VCTools%;%VCTools%\VCPackages;"
- SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
- SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
) ELSE (
SET VCTools=
ECHO The IA64 compilers are not currently installed.
@@ -320,10 +320,10 @@
ECHO .
)
) ELSE IF "%TARGET_CPU%" == "x86" (
+ SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
+ SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
IF EXIST "%VCTools%\cl.exe" (
SET "VCTools=%VCTools%;%VCTools%\VCPackages;"
- SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
- SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
) ELSE (
SET VCTools=
ECHO The x86 compilers are not currently installed. x86-x86
@@ -331,15 +331,17 @@
ECHO .
)
)
-) ELSE IF EXIST "%VCTools%\cl.exe" (
- SET "VCTools=%VCTools%;%VCTools%\VCPackages;"
- SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
- SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
) ELSE (
- SET VCTools=
- ECHO The x86 compilers are not currently installed. default
- ECHO Please go to Add/Remove Programs to update your installation.
- ECHO .
+ SET "FxTools=%FrameworkDir32%%FrameworkVersion%;%windir%\Microsoft.NET\Framework\v3.5;"
+ SET "SdkTools=%WindowsSdkDir%Bin\NETFX 4.0 Tools;%WindowsSdkDir%Bin;"
+ IF EXIST "%VCTools%\cl.exe" (
+ SET "VCTools=%VCTools%;%VCTools%\VCPackages;"
+ ) ELSE (
+ SET VCTools=
+ ECHO The x86 compilers are not currently installed. default
+ ECHO Please go to Add/Remove Programs to update your installation.
+ ECHO .
+ )
)
:: --------------------------------------------------------------------------------------------
Thread.currentThread().getStackTrace();
is available since JDK1.5.
For an older version, you can redirect exception.printStackTrace()
to a StringWriter()
:
StringWriter sw = new StringWriter();
new Throwable("").printStackTrace(new PrintWriter(sw));
String stackTrace = sw.toString();
If you set numberOfLines
to 0 (and the label to word wrap), the label will automatically wrap and use as many of lines as needed.
If you're editing a UILabel
in IB, you can enter multiple lines of text by pressing option+return to get a line break - return alone will finish editing.
You can use:
((count = FIRSTV - SECONDV))
to avoid invoking a separate process, as per the following transcript:
pax:~$ FIRSTV=7
pax:~$ SECONDV=2
pax:~$ ((count = FIRSTV - SECONDV))
pax:~$ echo $count
5
This generally happens only when you are not controlling the value of the filed when the application started and after some event or some function fired or the state changed, you are now trying to control the value in input field.
This transition of not having control over the input and then having control over it is what causes the issue to happen in the first place.
The best way to avoid this is by declaring some value for the input in the constructor of the component. So that the input element has value from the start of the application.
If you define custom CSS you must set font-weight: 900;
for some newer Font Awesome library (from version 5). Not setting this font-weight it may show squares.
Just for sake of completion, you can also do this:
array = []
array += [valueToBeInserted]
If it's a list of strings, this will also work:
array += 'string'
Here's how I do it, which I think is the most straightforward way to do it:
var x = 3.2;
int_part = Math.trunc(x); // returns 3
float_part = Number((x-int_part).toFixed(2)); // return 0.2
DF[:-n]
where n is the last number of rows to drop.
To drop the last row :
DF = DF[:-1]
Method that returns locale from string exists in commons-lang library:
LocaleUtils.toLocale(localeAsString)
I just got the same error message with a couple projects after installing Visual Studio 2015 Update 3. For me, the solution was to install .NET Core
(Q1) How can I find the socket file?
The default location for the socket file is /tmp/mysql.sock, to find the socket file for your system use this.
mysqladmin variables | grep socket
If you have just installed MySql the mysql.sock file will not be created until the server is started. Use this command to start it.
sudo launchctl load -F /Library/LaunchDaemons/com.oracle.oss.mysql.mysqld.plist
If prompted for a password you can pass the username root or other username like this. Terminal will prompt you for the password.
mysqladmin --user root --password variables | grep socket
(Q2) How can I refresh locate index
Refresh the locate db with this command.
sudo /usr/libexec/locate.updatedb
The running the impdp command to produce an sqlfile, you will need to run it as a user which has the DATAPUMP_IMP_FULL_DATABASE role.
Or... run it as a low privileged user and use the MASTER_ONLY=YES option, then inspect the master table. e.g.
select value_t
from SYS_IMPORT_TABLE_01
where name = 'CLIENT_COMMAND'
and process_order = -59;
col object_name for a30
col processing_status head STATUS for a6
col processing_state head STATE for a5
select distinct
object_schema,
object_name,
object_type,
object_tablespace,
process_order,
duplicate,
processing_status,
processing_state
from sys_import_table_01
where process_order > 0
and object_name is not null
order by object_schema, object_name
/
So, to be clear, it's a lazy coding style. I prefer native types, given the choice; I'll take that extra bit of "noise" to ensure I'm writing and reading exactly what I think I am at code/debug time. * shrug *
You can use the REST-API's "Item last modified". From the docs, it retuns something like this:
GET /api/storage/libs-release-local/org/acme?lastModified
{
"uri": "http://localhost:8081/artifactory/api/storage/libs-release-local/org/acme/foo/1.0-SNAPSHOT/foo-1.0-SNAPSHOT.pom",
"lastModified": ISO8601
}
Example:
# Figure out the URL of the last item modified in a given folder/repo combination
url=$(curl \
-H 'X-JFrog-Art-Api: XXXXXXXXXXXXXXXXXXXX' \
'http://<artifactory-base-url>/api/storage/<repo>/<folder>?lastModified' | jq -r '.uri')
# Figure out the name of the downloaded file
downloaded_filename=$(echo "${url}" | sed -e 's|[^/]*/||g')
# Download the file
curl -L -O "${url}"
I wrestled quite a while with the proper syntax for CREATE TEMPORARY TABLE SELECT. Having figured out a few things, I wanted to share the answers with the rest of the community.
Basic information about the statement is available at the following MySQL links:
CREATE TABLE SELECT and CREATE TABLE.
At times it can be daunting to interpret the spec. Since most people learn best from examples, I will share how I have created a working statement, and how you can modify it to work for you.
Add multiple indexes
This statement shows how to add multiple indexes (note that index names - in lower case - are optional):
CREATE TEMPORARY TABLE core.my_tmp_table
(INDEX my_index_name (tag, time), UNIQUE my_unique_index_name (order_number))
SELECT * FROM core.my_big_table
WHERE my_val = 1
Add a new primary key:
CREATE TEMPORARY TABLE core.my_tmp_table
(PRIMARY KEY my_pkey (order_number),
INDEX cmpd_key (user_id, time))
SELECT * FROM core.my_big_table
Create additional columns
You can create a new table with more columns than are specified in the SELECT statement. Specify the additional column in the table definition. Columns specified in the table definition and not found in select will be first columns in the new table, followed by the columns inserted by the SELECT statement.
CREATE TEMPORARY TABLE core.my_tmp_table
(my_new_id BIGINT NOT NULL AUTO_INCREMENT,
PRIMARY KEY my_pkey (my_new_id), INDEX my_unique_index_name (invoice_number))
SELECT * FROM core.my_big_table
Redefining data types for the columns from SELECT
You can redefine the data type of a column being SELECTed. In the example below, column tag is a MEDIUMINT in core.my_big_table and I am redefining it to a BIGINT in core.my_tmp_table.
CREATE TEMPORARY TABLE core.my_tmp_table
(tag BIGINT,
my_time DATETIME,
INDEX my_unique_index_name (tag) )
SELECT * FROM core.my_big_table
Advanced field definitions during create
All the usual column definitions are available as when you create a normal table. Example:
CREATE TEMPORARY TABLE core.my_tmp_table
(id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
value BIGINT UNSIGNED NOT NULL DEFAULT 0 UNIQUE,
location VARCHAR(20) DEFAULT "NEEDS TO BE SET",
country CHAR(2) DEFAULT "XX" COMMENT "Two-letter country code",
INDEX my_index_name (location))
ENGINE=MyISAM
SELECT * FROM core.my_big_table
I actually just wrote my own script for this purpose. It doesn't use Xcode. (It's based off a similar script in the Gambit Scheme project.)
Basically, it runs ./configure and make three times (for i386, armv7, and armv7s), and combines each of the resulting libraries into a fat lib.
This question is rooted in branch prediction models on CPUs. I'd recommend reading this paper:
Increasing the Instruction Fetch Rate via Multiple Branch Prediction and a Branch Address Cache
When you have sorted elements, the IR can not be bothered to fetch all CPU instructions, again and again. It fetches them from the cache.
You could also use the php native funcion get_browser()
IMPORTANT NOTE: You should have a browscap.ini file.
I had the same problem. My solution:
For Python 3
sudo apt-get install python3-pip
For Python 2
sudo apt-get install python-pip
No, JSFiddle doesn't have a download feature. However, it's not very difficult to get around that and save the contents of a fiddle anyway.
Since the time the accepted answer was posted, JSFiddle has made some recent UI and backend changes that affect the way a fiddle should be downloaded. Note the updated procedures below.
This method only downloads the fiddle's HTML, JavaScript, and CSS as a single file. The fiddle's external resources are not saved.
In the commandline shown below, fiddle_id
refers to the ID number of the fiddle. For a fiddle with the URL "http://jsfiddle.net/<fiddle_user>/<fiddle_id>
" or "http://jsfiddle.net/<fiddle_id>
", only the fiddle_id
is needed. The fiddle_user
is unimportant.
At a shell prompt, enter the single commandline:
fiddleId=fiddle_id; curl "http://fiddle.jshell.net/${fiddleId}/show/" -H "Referer: http://fiddle.jshell.net/${fiddleId}/" --output "${fiddleId}.html"
The fiddle will be saved to a file named "fiddle_id.html
".
This method downloads the fiddle as well as its external resources. The steps given are based on using Google Chrome. Using other web browsers should work as well, but they may use different filenames.
Share/Embed
" menu/link at the top of the JSFiddle edit page. In the dialog box that appears, copy the URL shown in the "Share full screen result
" field. It will be of the form "http://jsfiddle.net/<fiddle_user>/<fiddle_id>/embedded/result/
" or "http://jsfiddle.net/<fiddle_id>/embedded/result/
".Webpage, Complete
" in the "Format
" menu. Be sure to specify a name for the page. Let's say it's named "fiddle.html
" for this example.fiddle.html
" file and a directory named "fiddle_files
". The file "fiddle.html
" is the wrapper page that JSFiddle uses to display a header with a "Result" title and other links. It will load your fiddle in an iframe element. For the most part, this file can be ignored or even deleted. Your fiddle's HTML, JavaScript, and CSS content will all be saved in the "fiddle_files
" directory as a single file named "saved_resource.html
".fiddle_files/saved_resource.html
" to wherever you'd like to use it. If your fiddle included items under "External Resources
", those will also appear in the "fiddle_files
" directory. Be sure to copy those files to the same place to which you copied "saved_resource.html
", because the HTML file will refer to those resources using relative URLs.As mentioned earlier, other browsers may name the files differently when they are saved. For example, Firefox names the combined HTML/JS/CSS file "fiddle_files/a.html
".
is so easy You can use [phpy - library for php][1] php file
<?php
require_once "vendor/autoload.php";
use app\core\App;
$app = new App();
$python = $app->python;
$output = $python->set(your python path)->send(data..)->gen();
var_dump($ouput);
python file:
import include.library.phpy as phpy
print(phpy.get_data(number of data , first = 1 , two =2 ...))
you can see also example in github page [1]: https://github.com/Raeen123/phpy
Old post, but I thought I would share my solution because there aren't many solutions out there for this issue.
If you're running an old Windows Server 2003 machine, you likely need to install a hotfix (KB938397).
This problem occurs because the Cryptography API 2 (CAPI2) in Windows Server 2003 does not support the SHA2 family of hashing algorithms. CAPI2 is the part of the Cryptography API that handles certificates.
https://support.microsoft.com/en-us/kb/938397
For whatever reason, Microsoft wants to email you this hotfix instead of allowing you to download directly. Here's a direct link to the hotfix from the email:
http://hotfixv4.microsoft.com/Windows Server 2003/sp3/Fix200653/3790/free/315159_ENU_x64_zip.exe
This works everywhere including Safari 5 and Firefox 5 on OS X.
UPDATE: Fx Quantum (54) has no need for the replace, but Safari 11 is still not happy unless you convert as below
var date_test = new Date("2011-07-14 11:23:00".replace(/-/g,"/"));_x000D_
console.log(date_test);
_x000D_
You can only select columns that are in the group or used in an aggregate function. You can use a join to get this working
select s1.*
from sensorTable s1
inner join
(
SELECT sensorID, max(timestamp) as mts
FROM sensorTable
GROUP BY sensorID
) s2 on s2.sensorID = s1.sensorID and s1.timestamp = s2.mts
What Worked for me, while having I have more than 1 user on my computer.
Using terminal:
brew doctor
/usr/local/...
isn't writable error'ssudo chown -R $(whoami) /usr/local/*
brew doctor && brew upgrade && brew doctor
Running Macbook Pro OSX High Sierra (version 10.13.3.)
EDIT 1:
FYI - Please be Advised this causes an issue with running MySQL on your MAC.
To be able to start my local server, I had to run:
sudo chown -R mysql:mysql /usr/local/mysql/data
After you run this you can start your local MySQL Server.
You can also collect
with an appropriate summing collector like Collectors#summingInt(ToIntFunction)
Returns a
Collector
that produces the sum of a integer-valued function applied to the input elements. If no elements are present, the result is 0.
For example
Stream<Obj> filtered = list.stream().filter(o -> o.field > 10);
int sum = filtered.collect(Collectors.summingInt(o -> o.field));
My naive assumption was that the size of scroll pane will be determined automatically...
The only solution that actually worked for me was explicitly seeting bounds of JScrollPane:
import javax.swing.*;
public class MyFrame extends JFrame {
public MyFrame()
{
setBounds(100, 100, 491, 310);
getContentPane().setLayout(null);
JTextArea textField = new JTextArea();
textField.setEditable(false);
String str = "";
for (int i = 0; i < 50; ++i)
str += "Some text\n";
textField.setText(str);
JScrollPane scroll = new JScrollPane(textField);
scroll.setBounds(10, 11, 455, 249); // <-- THIS
getContentPane().add(scroll);
setLocationRelativeTo ( null );
}
}
Maybe it will help some future visitors :)
You can do the following:
bash -c "nano index.html"
The command above opens the index.html file with the nano editor within Powershell.
Alternatively, you can use the vim editor with the following command
bash -c "vi index.html"
Set the GroupName
property of both radio buttons to the same value. You could also try using a RadioButtonGroup
, which does this for you automatically.
I posted some code in answer to a related question on StackOverflow:
Sorting a multidimensionnal array in VBA
The code samples in that thread include:
Alain's optimised Quicksort is very shiny: I just did a basic split-and-recurse, but the code sample above has a 'gating' function that cuts down on redundant comparisons of duplicated values. On the other hand, I code for Excel, and there's a bit more in the way of defensive coding - be warned, you'll need it if your array contains the pernicious 'Empty()' variant, which will break your While... Wend comparison operators and trap your code in an infinite loop.
Note that quicksort algorthms - and any recursive algorithm - can fill the stack and crash Excel. If your array has fewer than 1024 members, I'd use a rudimentary BubbleSort.
Public Sub QuickSortArray(ByRef SortArray As Variant, _ Optional lngMin As Long = -1, _ Optional lngMax As Long = -1, _ Optional lngColumn As Long = 0) On Error Resume Next
'Sort a 2-Dimensional array
' Sample Usage: sort arrData by the contents of column 3 ' ' QuickSortArray arrData, , , 3
' 'Posted by Jim Rech 10/20/98 Excel.Programming
'Modifications, Nigel Heffernan:
' ' Escape failed comparison with empty variant ' ' Defensive coding: check inputs
Dim i As Long Dim j As Long Dim varMid As Variant Dim arrRowTemp As Variant Dim lngColTemp As Long
If IsEmpty(SortArray) Then Exit Sub End If
If InStr(TypeName(SortArray), "()") < 1 Then 'IsArray() is somewhat broken: Look for brackets in the type name Exit Sub End If
If lngMin = -1 Then lngMin = LBound(SortArray, 1) End If
If lngMax = -1 Then lngMax = UBound(SortArray, 1) End If
If lngMin >= lngMax Then ' no sorting required Exit Sub End If
i = lngMin j = lngMax
varMid = Empty varMid = SortArray((lngMin + lngMax) \ 2, lngColumn)
' We send 'Empty' and invalid data items to the end of the list: If IsObject(varMid) Then ' note that we don't check isObject(SortArray(n)) - varMid might pick up a valid default member or property i = lngMax j = lngMin ElseIf IsEmpty(varMid) Then i = lngMax j = lngMin ElseIf IsNull(varMid) Then i = lngMax j = lngMin ElseIf varMid = "" Then i = lngMax j = lngMin ElseIf varType(varMid) = vbError Then i = lngMax j = lngMin ElseIf varType(varMid) > 17 Then i = lngMax j = lngMin End If
While i <= j
While SortArray(i, lngColumn) < varMid And i < lngMax i = i + 1 Wend
While varMid < SortArray(j, lngColumn) And j > lngMin j = j - 1 Wend
If i <= j Then
' Swap the rows ReDim arrRowTemp(LBound(SortArray, 2) To UBound(SortArray, 2)) For lngColTemp = LBound(SortArray, 2) To UBound(SortArray, 2) arrRowTemp(lngColTemp) = SortArray(i, lngColTemp) SortArray(i, lngColTemp) = SortArray(j, lngColTemp) SortArray(j, lngColTemp) = arrRowTemp(lngColTemp) Next lngColTemp Erase arrRowTemp
i = i + 1 j = j - 1
End If
Wend
If (lngMin < j) Then Call QuickSortArray(SortArray, lngMin, j, lngColumn) If (i < lngMax) Then Call QuickSortArray(SortArray, i, lngMax, lngColumn)
End Sub
Move your image in the (hi-res) drawable to drawable-xxhdpi. But in app development, you do not need to use large image. It will increase your APK file size.
You can figure out which proxy server you're using by accessing some websites with a browser and then running the DOS command:
netstat
and you'll see some connections in the Foreign Address column on port 80 or 8080 (common proxy server ports). Ideally you will be able to identify the proxy server by its naming convention.
You can use this module which is easy to use: https://github.com/halilb/react-native-textinput-effects
After some thinking i came up with this solution:
LENGTHB(TO_CHAR(SUBSTR(<CLOB-Column>,1,4000)))
SUBSTR
returns only the first 4000 characters (max string size)
TO_CHAR
converts from CLOB
to VARCHAR2
LENGTHB
returns the length in Bytes used by the string.
The default iterator for the JObject is as a dictionary iterating over key/value pairs.
JObject obj = JObject.Parse(response);
foreach (var pair in obj) {
Console.WriteLine (pair.Key);
}
According to http://www.techotopia.com/index.php/Ruby_String_Concatenation_and_Comparison
Doing either
mystring == yourstring
or
mystring.eql? yourstring
Are equivalent.
from the command line: for /R /D %1 in (*) do rd "%1"
in a batch file for /R /D %%1 in (*) do rd "%%1"
I don't know if it's documented as such, but it works in W2K, XP, and Win 7. And I don't know if it will always work, but it won't ever delete files by accident.
Add the line below in application.properties file under resource folder and restart your application.
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
Set the iframe to the appropriate width and height and set the scrolling attribute to "no".
If the area you want is not in the top-left portion of the page, you can scroll the content to the appropriate area. Refer to this question:
Scrolling an iframe with javascript?
I believe you'll only be able to scroll it if both pages are on the same domain.
The zoo
package has the function of as.yearmon
can help to convert.
require(zoo)
df$ym<-as.yearmon(df$date, "%Y %m")
Why not using PixelRatio.getPixelSizeForLayoutSize(/* size in dp */);
, it's just the same as pd
units in Android.
UPDATED ANSWER:
Old answer, correct method nowadays is to use jQuery's .prop()
. IE, element.prop("selected", true)
OLD ANSWER:
Use this instead:
$("#routetype option[value='quietest']").attr("selected", "selected");
Fiddle'd: http://jsfiddle.net/x3UyB/4/
I have a dialog box that uses the datepicker on it. It was always hidden. When I adjusted the z-index, the field on the lower form always showed up on the dialog.
I used a combination of solutions that I saw to resolve the issue.
$('.ui-datepicker', $form).datepicker({
showButtonPanel: true,
changeMonth: true,
changeYear: true,
dateFormat: "yy-M-dd",
beforeShow: function (input) {
$(input).css({
"position": "relative",
"z-index": 999999
});
},
onClose: function () { $('.ui-datepicker').css({ 'z-index': 0 } ); }
});
The before show ensures that datepicker always is on top when selected, but the onClose ensures that the z-index of the field gets reset so that it doesn't overlap on any dialogs opened later with a different datepicker.
Actually you can do with VS Code the following:
This is a pretty good introductory video: http://vimeo.com/22685608
If you are looking for more on Rails and Backbone, Thoughtbot has this pretty good book (not free): https://workshops.thoughtbot.com/backbone-js-on-rails
Use CSS3 PIE, which emulates some CSS3 properties in older versions of IE.
It supports box-shadow
(except for the inset
keyword).
Convert Lists to Collection
and use removeAll
Collection<String> listOne = new ArrayList(Arrays.asList("a","b", "c", "d", "e", "f", "g"));
Collection<String> listTwo = new ArrayList(Arrays.asList("a","b", "d", "e", "f", "gg", "h"));
List<String> sourceList = new ArrayList<String>(listOne);
List<String> destinationList = new ArrayList<String>(listTwo);
sourceList.removeAll( listTwo );
destinationList.removeAll( listOne );
System.out.println( sourceList );
System.out.println( destinationList );
Output:
[c, g]
[gg, h]
[EDIT]
other way (more clear)
Collection<String> list = new ArrayList(Arrays.asList("a","b", "c", "d", "e", "f", "g"));
List<String> sourceList = new ArrayList<String>(list);
List<String> destinationList = new ArrayList<String>(list);
list.add("boo");
list.remove("b");
sourceList.removeAll( list );
list.removeAll( destinationList );
System.out.println( sourceList );
System.out.println( list );
Output:
[b]
[boo]
Create a *.bat
file beside of your windows service exe
file for installing with the following context:
CLS
ECHO Installing My Windows Service
START %windir%\Microsoft.NET\Framework\v4.0.30319\installutil.exe "%~d0%~p0\YourWindowsServiceExeName.exe"
Create a *.bat
file beside of your windows service exe
file for uninstalling with the following context:
CLS
ECHO Uninstalling My Windows Service
START %windir%\Microsoft.NET\Framework\v4.0.30319\installutil.exe -u "%~d0%~p0\YourWindowsServiceExeName.exe"
Run each of bat
file as Admin to install or uninstall your windows service.
For a new document: Settings -> Preferences -> New Document/Default Directory
-> New Document -> Format -> Windows/Mac/Unix
And for an already-open document: Edit -> EOL Conversion
In View Replace this:
@Html.DisplayFor(Model => Model.AuditDate.Value.ToShortDateString())
With:
@if(@Model.AuditDate.Value != null){@Model.AuditDate.Value.ToString("dd/MM/yyyy")}
else {@Html.DisplayFor(Model => Model.AuditDate)}
Explanation: If the AuditDate value is not null then it will format the date to dd/MM/yyyy, otherwise leave it as it is because it has no value.
One solution would be to create a Calendar
instance, and start a cycle, increasing it's Calendar.DATE
field until it reaches the desired date. Also, on each step you should create a Date
instance (with corresponding parameters), and put it to your list.
Some dirty code:
public List<Date> getDatesBetween(final Date date1, final Date date2) {
List<Date> dates = new ArrayList<Date>();
Calendar calendar = new GregorianCalendar() {{
set(Calendar.YEAR, date1.getYear());
set(Calendar.MONTH, date1.getMonth());
set(Calendar.DATE, date1.getDate());
}};
while (calendar.get(Calendar.YEAR) != date2.getYear() && calendar.get(Calendar.MONTH) != date2.getMonth() && calendar.get(Calendar.DATE) != date2.getDate()) {
calendar.add(Calendar.DATE, 1);
dates.add(new Date(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE)));
}
return dates;
}
In View use this:
form.field.errors|striptags
for getting validation messages without html
foreach ($Contents as $index=>$item) {
$item[$index];// if there are 15 $item[number] in this foreach, I want get the value : 15
}
Not very readable, but effective, has no dependencies and runs with any java version
byte[] buffer = new byte[1024];
for (int n; (n = inputStream.read(buffer)) != -1; outputStream.write(buffer, 0, n));
You must set the image rendering mode to UIImageRenderingModeAlwaysTemplate
in order to have the tintColor
affect the UIImage. Here is the solution in Swift:
let image = UIImage(named: "image-name")
let button = UIButton()
button.setImage(image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate), forState: .Normal)
button.tintColor = UIColor.whiteColor()
SWIFT 4x
button.setImage(image.withRenderingMode(UIImage.RenderingMode.alwaysTemplate), for: .normal)
button.tintColor = UIColor.blue
In the example above. For me, this if($response.success==false)
thing does not work. Here is correct PHP code:
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "--your_key--";
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if (isset($data->success) AND $data->success==true) {
// everything is ok!
} else {
// spam
}
var secondEmails = (from item in list2
select new { Email = item.Email }
).ToList();
var matches = from item in list1
where !secondEmails.Contains(item.Email)
select new {Email = item.Email};
I use MacTex, and my editor is TexShop. It probably has to do with what compiler you are using. When I use pdftex, the command:
\includegraphics[height=60mm, width=100mm]{number2.png}
works fine, but when I use "Tex and Ghostscript", I get the same error as you, about not being able to get the size information. Use pdftex.
Incidentally, you can change this in TexShop from the "Typeset" menu.
Hope this helps.
You need to add a vertical-align
property to your two child div's.
If .small
is always shorter, you need only apply the property to .small
.
However, if either could be tallest then you should apply the property to both .small
and .big
.
.container{
border: 1px black solid;
width: 320px;
height: 120px;
}
.small{
display: inline-block;
width: 40%;
height: 30%;
border: 1px black solid;
background: aliceblue;
vertical-align: top;
}
.big {
display: inline-block;
border: 1px black solid;
width: 40%;
height: 50%;
background: beige;
vertical-align: top;
}
Vertical align affects inline or table-cell box's, and there are a large nubmer of different values for this property. Please see https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align for more details.
I have found something that Actually works in both FireFox and IE, on Elizabeth Castro's site (thanks to the link on this site) - I have tried all other versions here, but could not make them work in both the browsers
<object classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6"
id="player" width="320" height="260">
<param name="url"
value="http://www.sarahsnotecards.com/catalunyalive/fishstore.wmv" />
<param name="src"
value="http://www.sarahsnotecards.com/catalunyalive/fishstore.wmv" />
<param name="showcontrols" value="true" />
<param name="autostart" value="true" />
<!--[if !IE]>-->
<object type="video/x-ms-wmv"
data="http://www.sarahsnotecards.com/catalunyalive/fishstore.wmv"
width="320" height="260">
<param name="src"
value="http://www.sarahsnotecards.com/catalunyalive/fishstore.wmv" />
<param name="autostart" value="true" />
<param name="controller" value="true" />
</object>
<!--<![endif]-->
</object>
Check her site out: http://www.alistapart.com/articles/byebyeembed/ and the version with the classid in the initial object tag
Another important consideration: The Elvis Operator breaks the Zend Opcache tokenization process. I found this the hard way! While this may have been fixed in later versions, I can confirm this problem exists in PHP 5.5.38 (with in-built Zend Opcache v7.0.6-dev).
If you find that some of your files 'refuse' to be cached in Zend Opcache, this may be one of the reasons... Hope this helps!
You have to do this:
class Bar : public Foo
{
// ...
}
The default inheritance type of a class
in C++ is private
, so any public
and protected
members from the base class are limited to private
. struct
inheritance on the other hand is public
by default.
It's the special table in Oracle. I often use it for calculations or checking system variables. For example:
Select 2*4 from dual
prints out the result of the calculationSelect sysdate from dual
prints the server current date. IE 7 on windows8 with bootstrap 3.0.0.
.navbar {
position: static;
}
.navbar .nav > li {
z-index: 1001;
}
fixed
I think one error in the original code might have been that it had:
$message = echo getRequestURI();
instead of:
$message = getRequestURI();
(The code has since been edited though.)
Using jQuery:
$(document).ready(function() {
$(".myElement").wrap( '<span class="myElement_container_new"></span>' ); // for IE6
$(".myElement_container_new").css({// for IE6
"display" : "block",
"position" : "relative",
"margin" : "0",
"padding" : "0",
"border" : "none",
"background-color" : "transparent",
"clear" : "both",
"text-align" : "center"
});
$(".myElement").css({
"display" : "block",
"position" : "relative",
"max-width" : "75%", // for example
"margin-left" : "auto",
"margin-right" : "auto",
"clear" : "both",
"text-align" : "left"
});
});
or, if you want to center every element with class ".myElement":
$(document).ready(function() {
$(".myElement").each(function() {
$(this).wrap( '<span class="myElement_container_new"></span>' ); // for IE6
$(".myElement_container_new").css({// for IE6
"display" : "block",
"position" : "relative",
"margin" : "0",
"padding" : "0",
"border" : "none",
"background-color" : "transparent",
"clear" : "both",
"text-align" : "center"
});
$(this).css({
"display" : "block",
"position" : "relative",
"max-width" : "75%",
"margin-left" : "auto",
"margin-right" : "auto",
"clear" : "both",
"text-align" : "left"
});
});
});
cat
can also be used following a |
to write to a file, i.e. pipe feeds cat a stream of data
I made this short example which also works.
#include <iostream>
#include <type_traits>
class foo;
class bar;
template<class T>
struct is_bar
{
template<class Q = T>
typename std::enable_if<std::is_same<Q, bar>::value, bool>::type check()
{
return true;
}
template<class Q = T>
typename std::enable_if<!std::is_same<Q, bar>::value, bool>::type check()
{
return false;
}
};
int main()
{
is_bar<foo> foo_is_bar;
is_bar<bar> bar_is_bar;
if (!foo_is_bar.check() && bar_is_bar.check())
std::cout << "It works!" << std::endl;
return 0;
}
Comment if you want me to elaborate. I think the code is more or less self-explanatory, but then again I made it so I might be wrong :)
You can see it in action here.
<div ng-app="" ng-controller="myCntrl">
<input type="radio" ng-model="people" value="1"/><label>1</label>
<input type="radio" ng-model="people" value="2"/><label>2</label>
<input type="radio" ng-model="people" value="3"/><label>3</label>
</div>
<script>
function myCntrl($scope){
$scope.people=1;
}
</script>
A convoluted way is to create your own Runner by subclassing org.junit.runners.BlockJUnit4ClassRunner.
You can then do something like this:
public class NameAwareRunner extends BlockJUnit4ClassRunner {
public NameAwareRunner(Class<?> aClass) throws InitializationError {
super(aClass);
}
@Override
protected Statement methodBlock(FrameworkMethod frameworkMethod) {
System.err.println(frameworkMethod.getName());
return super.methodBlock(frameworkMethod);
}
}
Then for each test class, you'll need to add a @RunWith(NameAwareRunner.class) annotation. Alternatively, you could put that annotation on a Test superclass if you don't want to remember it every time. This, of course, limits your selection of runners but that may be acceptable.
Also, it may take a little bit of kung fu to get the current test name out of the Runner and into your framework, but this at least gets you the name.
Native way to get the mimetype:
For PHP < 5.3 use mime_content_type()
For PHP >= 5.3 use finfo_open() or mime_content_type()
Alternatives to get the MimeType are exif_imagetype and getimagesize, but these rely on having the appropriate libs installed. In addition, they will likely just return image mimetypes, instead of the whole list given in magic.mime.
While mime_content_type
is available from PHP 4.3 and is part of the FileInfo extension (which is enabled by default since PHP 5.3, except for Windows platforms, where it must be enabled manually, for details see here).
If you don't want to bother about what is available on your system, just wrap all four functions into a proxy method that delegates the function call to whatever is available, e.g.
function getMimeType($filename)
{
$mimetype = false;
if(function_exists('finfo_open')) {
// open with FileInfo
} elseif(function_exists('getimagesize')) {
// open with GD
} elseif(function_exists('exif_imagetype')) {
// open with EXIF
} elseif(function_exists('mime_content_type')) {
$mimetype = mime_content_type($filename);
}
return $mimetype;
}
I fixed this issue by deleting the output file and running the command again. It turns out it does NOT overwrite the previous file. I had this issue when renewing a let's encrypt cert with tomcat
Install this package in Ubuntu
:
apt install sysv-rc-conf
its a substitute for chkconfig
cmd.
After install run this cmd:
sysv-rc-conf --list
It'll show all services in all the runlevels. You can also run this:
sysv-rc-conf --level (runlevel number ex:1 2 3 4 5 6 )
Now you can choose which service should be active in boot time.
Above answers are correct. This version is easy to follow:
Because "Schema export directory is not provided to the annotation processor", So we need to provide the directory for schema export:
Step [1] In your file which extends the RoomDatabase, change the line to:
`@Database(entities = ???.class,version = 1, exportSchema = true)`
Or
`@Database(entities = ???.class,version = 1)`
(because the default value is always true)
Step [2] In your build.gradle(project:????) file, inside the defaultConfig{ } (which is inside android{ } big section), add the javaCompileOptions{ } section, it will be like:
android{
defaultConfig{
//javaComplieOptions SECTION
javaCompileOptions {
annotationProcessorOptions {
arguments = ["room.schemaLocation":"$projectDir/schemas".toString()]
}
}
//Other SECTION
...
}
}
$projectDir:is a variable name, you cannot change it. it will get your own project directory
schemas:is a string, you can change it to any you like. For example:
"$projectDir/MyOwnSchemas".toString()
This is perhaps the best explanations on why to use lambda expressions -> https://youtu.be/j9nj5dTo54Q
In summary, it's to improve code readability, reduce chances of errors by reusing rather than replicating code, and leverage optimization happening behind the scenes.
adding to scotty's answer:
Option 1: Either include this in your JS file:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>
Option 2: or just use the URL to download 'angular-route.min.js' to your local.
and then (whatever option you choose) add this 'ngRoute' as dependency.
explained:
var app = angular.module('myapp', ['ngRoute']);
Cheers!!!
You could do it like this:
String s = "1234567890";
System.out.println(java.util.Arrays.toString(s.split("(?<=\\G...)")));
which produces:
[123, 456, 789, 0]
The regex (?<=\G...)
matches an empty string that has the last match (\G
) followed by three characters (...
) before it ((?<= )
)
A stateless system can be seen as a box [black? ;)] where at any point in time the value of the output(s) depends only on the value of the input(s) [after a certain processing time]
A stateful system instead can be seen as a box where at any point in time the value of the output(s) depends on the value of the input(s) and of an internal state, so basicaly a stateful system is like a state machine with "memory" as the same set of input(s) value can generate different output(s) depending on the previous input(s) received by the system.
From the parallel programming point of view, a stateless system, if properly implemented, can be executed by multiple threads/tasks at the same time without any concurrency issue [as an example think of a reentrant function] A stateful system will requires that multiple threads of execution access and update the internal state of the system in an exclusive way, hence there will be a need for a serialization [synchronization] point.
You can try something like this I guess:
new_str = ""
str_value = "rojbasr"
for i in str_value:
new_str += "0x%s " % (i.encode('hex'))
print new_str
Your output would be something like this:
0x72 0x6f 0x6a 0x62 0x61 0x73 0x72
I would recommend using the execute method which returns null if no match exists otherwise it returns a helpful object.
let case1 = /^([a-z0-9]{5,})$/.exec("abc1");
console.log(case1); //null
let case2 = /^([a-z0-9]{5,})$/.exec("pass3434");
console.log(case2); // ['pass3434', 'pass3434', index:0, input:'pass3434', groups: undefined]
My problem was not resolved with this procedure
FirebaseApp.initializeApp(this);
So I tried something else and now my firebase has been successfully initialized. Try adding following in app module.gradle
BuildScript{
dependencies {..
classpath : "com.google.firebase:firebase-plugins:1.1.5"
..}
}
dependencies {...
implementation : "com.google.firebase:firebase-perf:16.1.0"
implementation : "com.google.firebase:firebase-core:16.0.3"
..}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#commentForm").validate();
});
function addInput() {
var indexVal = $("#index").val();
var index = parseInt(indexVal) + 1
var obj = '<input id="list'+index+'" name=list['+index+'] class="required" />'
$("#parent").append(obj);
$("#list"+index).rules("add", "required");
$("#index").val(index)
}
</script>
<form id="commentForm" method="get" action="">
<input type="hidden" name="index" name="list[1]" id="index" value="1">
<p id="parent">
<input id="list1" class="required" />
</p>
<input class="submit" type="submit" value="Submit"/>
<input type="button" value="add" onClick="addInput()" />
</form>
This happened to me also, while i was reading text containing Hebrew from a .txt
file.
I clicked: file -> save as
and I saved this file as a UTF-8
encoding
dynamic_cast
can determine if the type contains the target type anywhere in the inheritance hierarchy (yes, it's a little-known feature that if B
inherits from A
and C
, it can turn an A*
directly into a C*
). typeid()
can determine the exact type of the object. However, these should both be used extremely sparingly. As has been mentioned already, you should always be avoiding dynamic type identification, because it indicates a design flaw. (also, if you know the object is for sure of the target type, you can do a downcast with a static_cast
. Boost offers a polymorphic_downcast
that will do a downcast with dynamic_cast
and assert
in debug mode, and in release mode it will just use a static_cast
).
vector<char> toVector( const std::string& s ) {
string s = "apple";
vector<char> v(s.size()+1);
memcpy( &v.front(), s.c_str(), s.size() + 1 );
return v;
}
vector<char> v = toVector(std::string("apple"));
// what you were looking for (mutable)
char* c = v.data();
.c_str() works for immutable. The vector will manage the memory for you.
Parts of the GCC runtime (the exception handling, in particular) are dependent on the threading model being used. So, if you're using the version of the runtime that was built with POSIX threads, but decide to create threads in your own code with the Win32 APIs, you're likely to have problems at some point.
Even if you're using the Win32 threading version of the runtime you probably shouldn't be calling the Win32 APIs directly. Quoting from the MinGW FAQ:
As MinGW uses the standard Microsoft C runtime library which comes with Windows, you should be careful and use the correct function to generate a new thread. In particular, the
CreateThread
function will not setup the stack correctly for the C runtime library. You should use_beginthreadex
instead, which is (almost) completely compatible withCreateThread
.
JavaScript encodes strings as UTF-16, just like C#'s UnicodeEncoding
, so the byte arrays should match exactly using charCodeAt()
, and splitting each returned byte pair into 2 separate bytes, as in:
function strToUtf16Bytes(str) {
const bytes = [];
for (ii = 0; ii < str.length; ii++) {
const code = str.charCodeAt(ii); // x00-xFFFF
bytes.push(code & 255, code >> 8); // low, high
}
return bytes;
}
For example:
strToUtf16Bytes('');
// [ 60, 216, 53, 223 ]
However, If you want to get a UTF-8 byte array, you must transcode the bytes.
The solution feels somewhat non-trivial, but I used the code below in a high-traffic production environment with great success (original source).
Also, for the interested reader, I published my unicode helpers that help me work with string lengths reported by other languages such as PHP.
/**
* Convert a string to a unicode byte array
* @param {string} str
* @return {Array} of bytes
*/
export function strToUtf8Bytes(str) {
const utf8 = [];
for (let ii = 0; ii < str.length; ii++) {
let charCode = str.charCodeAt(ii);
if (charCode < 0x80) utf8.push(charCode);
else if (charCode < 0x800) {
utf8.push(0xc0 | (charCode >> 6), 0x80 | (charCode & 0x3f));
} else if (charCode < 0xd800 || charCode >= 0xe000) {
utf8.push(0xe0 | (charCode >> 12), 0x80 | ((charCode >> 6) & 0x3f), 0x80 | (charCode & 0x3f));
} else {
ii++;
// Surrogate pair:
// UTF-16 encodes 0x10000-0x10FFFF by subtracting 0x10000 and
// splitting the 20 bits of 0x0-0xFFFFF into two halves
charCode = 0x10000 + (((charCode & 0x3ff) << 10) | (str.charCodeAt(ii) & 0x3ff));
utf8.push(
0xf0 | (charCode >> 18),
0x80 | ((charCode >> 12) & 0x3f),
0x80 | ((charCode >> 6) & 0x3f),
0x80 | (charCode & 0x3f),
);
}
}
return utf8;
}
Below query will provide exactly the same result as given in the desired response:
db.books.aggregate([
{
$group: {
_id: { addresses: "$addr", books: "$book" },
num: { $sum :1 }
}
},
{
$group: {
_id: "$_id.addresses",
bookCounts: { $push: { bookName: "$_id.books",count: "$num" } }
}
},
{
$project: {
_id: 1,
bookCounts:1,
"totalBookAtAddress": {
"$sum": "$bookCounts.count"
}
}
}
])
The response will be looking like below:
/* 1 */
{
"_id" : "address4",
"bookCounts" : [
{
"bookName" : "book3",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 2 */
{
"_id" : "address90",
"bookCounts" : [
{
"bookName" : "book33",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 3 */
{
"_id" : "address15",
"bookCounts" : [
{
"bookName" : "book1",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 4 */
{
"_id" : "address3",
"bookCounts" : [
{
"bookName" : "book9",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 5 */
{
"_id" : "address5",
"bookCounts" : [
{
"bookName" : "book1",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 6 */
{
"_id" : "address1",
"bookCounts" : [
{
"bookName" : "book1",
"count" : 3
},
{
"bookName" : "book5",
"count" : 1
}
],
"totalBookAtAddress" : 4
},
/* 7 */
{
"_id" : "address2",
"bookCounts" : [
{
"bookName" : "book1",
"count" : 2
},
{
"bookName" : "book5",
"count" : 1
}
],
"totalBookAtAddress" : 3
},
/* 8 */
{
"_id" : "address77",
"bookCounts" : [
{
"bookName" : "book11",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 9 */
{
"_id" : "address9",
"bookCounts" : [
{
"bookName" : "book99",
"count" : 1
}
],
"totalBookAtAddress" : 1
}
You have a dash in the middle of the character class, which will mean a character range. Put the dash at the end of the class like so:
[$&+,:;=?@#|'<>.^*()%!-]
Peachpie
https://github.com/iolevel/peachpie
Peachpie is PHP 7 compiler based on Roslyn by Microsoft and drawing from popular Phalanger. It allows PHP to be executed within the .NET/.NETCore by compiling the PHP code to pure MSIL.
Phalanger
http://wiki.php-compiler.net/Phalanger_Wiki
https://github.com/devsense/phalanger
Phalanger is a project which was started at Charles University in Prague and was supported by Microsoft. It compiles source code written in the PHP scripting language into CIL (Common Intermediate Language) byte-code. It handles the beginning of a compiling process which is completed by the JIT compiler component of the .NET Framework. It does not address native code generation nor optimization. Its purpose is to compile PHP scripts into .NET assemblies, logical units containing CIL code and meta-data.
Bambalam
https://github.com/xZero707/Bamcompile/
Bambalam PHP EXE Compiler/Embedder is a free command line tool to convert PHP applications to standalone Windows .exe applications. The exe files produced are totally standalone, no need for php dlls etc. The php code is encoded using the Turck MMCache Encode library so it's a perfect solution if you want to distribute your application while protecting your source code. The converter is also suitable for producing .exe files for windowed PHP applications (created using for example the WinBinder library). It's also good for making stand-alone PHP Socket servers/clients (using the php_sockets.dll extension). It's NOT really a compiler in the sense that it doesn't produce native machine code from PHP sources, but it works!
ZZEE PHPExe
ZZEE PHPExe compiles PHP, HTML, Javascript, Flash and other web files into Windows GUI exes. You can rapidly develop Windows GUI applications by employing the familiar PHP web paradigm. You can use the same code for online and Windows applications with little or no modification. It is a Commercial product.
phc-win
http://wiki.swiftlytilting.com/Phc-win
The PHP extension bcompiler is used to compile PHP script code into PHP bytecode. This bytecode can be included just like any php file as long as the bcompiler extension is loaded. Once all the bytecode files have been created, a modified Embeder is used to pack all of the project files into the program exe.
Requires
ExeOutput
Commercial
WinBinder
WinBinder is an open source extension to PHP, the script programming language. It allows PHP programmers to easily build native Windows applications, producing quick and rewarding results with minimum effort. Even short scripts with a few dozen lines can generate a useful program, thanks to the power and flexibility of PHP.
PHPDesktop
https://github.com/cztomczak/phpdesktop
PHP Desktop is an open source project founded by Czarek Tomczak in 2012 to provide a way for developing native desktop applications using web technologies such as PHP, HTML5, JavaScript & SQLite. This project is more than just a PHP to EXE compiler, it embeds a web-browser (Internet Explorer or Chrome embedded), a Mongoose web-server and a PHP interpreter. The development workflow you are used to remains the same, the step of turning an existing website into a desktop application is basically a matter of copying it to "www/" directory. Using SQLite database is optional, you could embed mysql/postgresql database in application's installer.
PHP Nightrain
https://github.com/kjellberg/nightrain
Using PHP Nightrain you will be able to deploy and run HTML, CSS, JavaScript and PHP web applications as a native desktop application on Windows, Mac and the Linux operating systems. Popular PHP Frameworks (e.g. CakePHP, Laravel, Drupal, etc…) are well supported!
phc-win "fork"
https://github.com/RDashINC/phc-win
A more-or-less forked version of phc-win, it uses the same techniques as phc-win but supports almost all modern PHP versions. (5.3, 5.4, 5.5, 5.6, etc) It also can use Enigma VB to combine the php5ts.dll with your exe, aswell as UPX compress it. Lastly, it has win32std and winbinder compilied statically into PHP.
EDIT
Another option is to use
http://www.appcelerator.com/products/titanium-cross-platform-application-development/
an online compiler that can build executables for a number of different platforms, from a number of different languages including PHP
TideSDK
TideSDK is actually the renamed Titanium Desktop project. Titanium remained focused on mobile, and abandoned the desktop version, which was taken over by some people who have open sourced it and dubbed it TideSDK.
Generally, TideSDK uses HTML, CSS and JS to render applications, but it supports scripted languages like PHP, as a plug-in module, as well as other scripting languages like Python and Ruby.
Note that there are two different types of equality in C#
1- Value Equality
(For value types like int, DateTime and struct)
2- Reference Equality
(For objects)
There are two basic standard protocols for implement equality checks.
1- The ==
and !=
operators.
2- The virtual
Equals
method.
The == and != are statically resolve, which means C# will make a compile-time decision as to which type will perform the comparison.
For instance the value-type
int x = 50;
int y = 50;
Console.WriteLine (x == y); // True
but for reference type
object x = 50;
object y = 50;
Console.WriteLine (x == y); // False
The Equals()
originally resoled at runtime according to operand actual type.
For instance, in the following example, at runtime, it will be decided that the Equals()
will apply on int values, the result is true
.
object x = 5;
object y = 5;
Console.WriteLine (x.Equals (y)); // True
However, for a reference type, it will use a reference equality check.
MyObject x = new MyObject();
MyObject y = x;
Console.WriteLine (x.Equals (y)); // True
Note that Equals()
uses structural comparison for struct
, which means it calls Equals on each field of a struct.
I got this error today because the "Source" is missing the ApacheJmeter.jar. I downloaded it again from "Binaries" and everything works as expected.
Update:
The plugin previously mentioned has been abandoned, but it apparently has an up-to-date fork here.
Old Answer:
I use the Android Studio plugin named Android Drawable Importer
:
To use it after installed, right click your res/drawable folder and select New > Batch Drawable Import
:
Then select your image via the +
button and set the Resolution to be xxhdpi (or whatever the resolution of your source image is).
If lakes
is your DataFrame
, you can do something like
area_dict = dict(zip(lakes.area, lakes.count))
You should be able to do the count on the purch variable:
purch.Count();
e.g.
var purch = from purchase in myBlaContext.purchases
select purchase;
purch.Count();
Nginx prefers prefix-based location matches (not involving regular expression), that's why in your code block, /stash redirects are going to /.
The algorithm used by Nginx to select which location to use is described thoroughly here: https://www.digitalocean.com/community/tutorials/understanding-nginx-server-and-location-block-selection-algorithms#matching-location-blocks
I got this error and found that I don't have my SSH port (non standard number) whitelisted in config server firewall.
In addition to the other answers, Class defines the method === to test whether an object is an instance of that class.
Some practical uses for the [Serializable]
attribute:
BinaryFormatter
class in System.Runtime.Serialization.Formatters.BinaryClipboard.SetData()
- nonserialisable classes cannot be placed on the clipboard.MarshalByRefObject
) must be serialisable.These are the most common usage cases that I have come across.
The easiest method to solve your problem (without going to a different editor or learning regex) is to record a macro.
I think the best solution is converting each char to HEX and replace it with another HEX. It's because there are 2 Unicode typing:
Composite Unicode
Precomposed Unicode
For example "Ô`" written by Composite Unicode is different from "?" written by Precomposed Unicode. You can copy my sample chars and convert them to see the difference.
In Composite Unicode, "Ô`" is combined from 2 char: Ô (U+00d4) and ` (U+0300)
In Precomposed Unicode, "?" is single char (U+1ED2)
I have developed this feature for some banks to convert the info before sending it to core-bank (usually don't support Unicode) and faced this issue when the end-users use multiple Unicode typing to input the data. So I think, converting to HEX and replace it is the most reliable way.
UPDATE: The stroke-alignment
attribute was on April 1st, 2015 moved to a completely new spec called SVG Strokes.
As of the SVG 2.0 Editor’s Draft of February 26th, 2015 (and possibly since February 13th), the with the values stroke-alignment
property is presentinner
, center
(default) and outer
.
It seems to work the same way as the stroke-location
property proposed by @Phrogz and the later stroke-position
suggestion. This property has been planned since at least 2011, but apart from an annotation that said
SVG 2 shall include a way to specify stroke position
, it has never been detailed in the spec as it was deferred - until now, it seems.
No browser support this property, or, as far as I know, any of the new SVG 2 features, yet, but hopefully they will soon as the spec matures. This has been a property I personally have been urging to have, and I'm really happy that it's finally there in the spec.
There seems to be some issues as to how to the property should behave on open paths as well as loops. These issues will, most probably, prolong implementations across browsers. However, I will update this answer with new information as browsers begin to support this property.
It's the "frame" or "range" clause of window functions, which are part of the SQL standard and implemented in many databases, including Teradata.
A simple example would be to calculate the average amount in a frame of three days. I'm using PostgreSQL syntax for the example, but it will be the same for Teradata:
WITH data (t, a) AS (
VALUES(1, 1),
(2, 5),
(3, 3),
(4, 5),
(5, 4),
(6, 11)
)
SELECT t, a, avg(a) OVER (ORDER BY t ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)
FROM data
ORDER BY t
... which yields:
t a avg
----------
1 1 3.00
2 5 3.00
3 3 4.33
4 5 4.00
5 4 6.67
6 11 7.50
As you can see, each average is calculated "over" an ordered frame consisting of the range between the previous row (1 preceding
) and the subsequent row (1 following
).
When you write ROWS UNBOUNDED PRECEDING
, then the frame's lower bound is simply infinite. This is useful when calculating sums (i.e. "running totals"), for instance:
WITH data (t, a) AS (
VALUES(1, 1),
(2, 5),
(3, 3),
(4, 5),
(5, 4),
(6, 11)
)
SELECT t, a, sum(a) OVER (ORDER BY t ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM data
ORDER BY t
yielding...
t a sum
---------
1 1 1
2 5 6
3 3 9
4 5 14
5 4 18
6 11 29
Here's another very good explanations of SQL window functions.
For arrays of limited length use the following (as given by camickr). This is slow for repeated checks, especially for longer arrays (linear search).
Arrays.asList(...).contains(...)
For fast performance if you repeatedly check against a larger set of elements
An array is the wrong structure. Use a TreeSet
and add each element to it. It sorts elements and has a fast exist()
method (binary search).
If the elements implement Comparable
& you want the TreeSet
sorted accordingly:
ElementClass.compareTo()
method must be compatable with ElementClass.equals()
: see Triads not showing up to fight? (Java Set missing an item)
TreeSet myElements = new TreeSet();
// Do this for each element (implementing *Comparable*)
myElements.add(nextElement);
// *Alternatively*, if an array is forceably provided from other code:
myElements.addAll(Arrays.asList(myArray));
Otherwise, use your own Comparator
:
class MyComparator implements Comparator<ElementClass> {
int compareTo(ElementClass element1; ElementClass element2) {
// Your comparison of elements
// Should be consistent with object equality
}
boolean equals(Object otherComparator) {
// Your equality of comparators
}
}
// construct TreeSet with the comparator
TreeSet myElements = new TreeSet(new MyComparator());
// Do this for each element (implementing *Comparable*)
myElements.add(nextElement);
The payoff: check existence of some element:
// Fast binary search through sorted elements (performance ~ log(size)):
boolean containsElement = myElements.exists(someElement);
If you are having similar issues with pure components or classes, ensure you are using .js
extension instead of .jsx
.
If I were explaining this to someone I'd say we'll get to it later for now you need to know that the way to run your program is to use :
public static void main(String[] args) {
...
}
Assuming he/she knows what an array is, I'd say the args is an argument array and you can show some cool examples.
Then after you've gone a bit about Java/JVM and that stuff, you'd get to modifiers eventually to static and public as well.
Then you can spend some time talking about meaning of these IMHO.
You could mention other "cool" stuff such as varargs that you can use this in later versions of Java.
public static void main(String ...args) {
//...
}
I can see that this question was originally posted 5 yrs ago when programmers had to work harder to get their desired results. With Visual Studio 2012 and beyond, a lazy programmer can go the Design View for the Listview properties settings, and click on Properties->Sorting, choose Ascending. There are plenty of other properties features to obtain the various results a lazy (aka smart) programmer can leverage.
you can use raiserror
. Read more details here
--from MSDN
BEGIN TRY
-- RAISERROR with severity 11-19 will cause execution to
-- jump to the CATCH block.
RAISERROR ('Error raised in TRY block.', -- Message text.
16, -- Severity.
1 -- State.
);
END TRY
BEGIN CATCH
DECLARE @ErrorMessage NVARCHAR(4000);
DECLARE @ErrorSeverity INT;
DECLARE @ErrorState INT;
SELECT
@ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE();
-- Use RAISERROR inside the CATCH block to return error
-- information about the original error that caused
-- execution to jump to the CATCH block.
RAISERROR (@ErrorMessage, -- Message text.
@ErrorSeverity, -- Severity.
@ErrorState -- State.
);
END CATCH;
EDIT
If you are using SQL Server 2012+ you can use throw
clause. Here are the details.
If you are Using HTML5 you can add the attribute 'download' to your links.
<a href="/test.pdf" download>
As noted by @mastablasta, but also to add that if you call the 'done' argument or rather name it completed you just call the callback completed() in your test when it's done.
// this block signature will trigger async behavior.
it("should work", function(done){
// do stuff and then call done...
done();
});
// this block signature will run synchronously
it("should work", function(){
//...
});
You can get another validation on this tutorial : http://twitterbootstrap.org/bootstrap-form-validation
They use JQuery validation.
jquery.validate.js
jquery.validate.min.js
jquery-1.7.1.min.js
And you'll get the source code there.
<form id="registration-form" class="form-horizontal">
<h2>Sample Registration form <small>(Fill up the forms to get register)</small></h2>
<div class="form-control-group">
<label class="control-label" for="name">Your Name</label>
<div class="controls">
<input type="text" class="input-xlarge" name="name" id="name"></div>
</div>
<div class="form-control-group">
<label class="control-label" for="name">User Name</label>
<div class="controls">
<input type="text" class="input-xlarge" name="username" id="username"></div>
</div>
<div class="form-control-group">
<label class="control-label" for="name">Password</label>
<div class="controls">
<input type="password" class="input-xlarge" name="password" id="password">
</div>
</div>
<div class="form-control-group">
<label class="control-label" for="name"> Retype Password</label>
<div class="controls">
<input type="password" class="input-xlarge" name="confirm_password" id="confirm_password"></div>
</div>
<div class="form-control-group">
<label class="control-label" for="email">Email Address</label>
<div class="controls">
<input type="text" class="input-xlarge" name="email" id="email"></div>
</div>
<div class="form-control-group">
<label class="control-label" for="message">Your Address</label>
<div class="controls">
<textarea class="input-xlarge" name="address" id="address" rows="3"></textarea></div>
</div>
<div class="form-control-group">
<label class="control-label" for="message"> Please agree to our policy</label>
<div class="controls">
<input id="agree" class="checkbox" type="checkbox" name="agree"></div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-success btn-large">Register</button>
<button type="reset" class="btn">Cancel</button></div>
</form>
And The JQuery :
<script src="assets/js/jquery-1.7.1.min.js"></script>
<script src="assets/js/jquery.validate.js"></script>
<script src="script.js"></script>
<script>
addEventListener('load', prettyPrint, false);
$(document).ready(function(){
$('pre').addClass('prettyprint linenums');
});
Here is the live example of the code: http://twitterbootstrap.org/live/bootstrap-form-validation/
Check the full tutorial: http://twitterbootstrap.org/bootstrap-form-validation/
happy coding.
Use a CultureInfo like this, from MSDN:
// Creates a CultureInfo for German in Germany.
CultureInfo ci = new CultureInfo("de-DE");
// Displays dt, formatted using the CultureInfo
Console.WriteLine(dt.ToString(ci));
More info on MSDN. Here is a link of all different cultures.
https://lodash.com/docs#isEmpty comes in pretty handy:
_.isEmpty({}) // true
_.isEmpty() // true
_.isEmpty(null) // true
_.isEmpty("") // true
You can use find_all
in the following way to find every a
element that has an href
attribute, and print each one:
from BeautifulSoup import BeautifulSoup
html = '''<a href="some_url">next</a>
<span class="class"><a href="another_url">later</a></span>'''
soup = BeautifulSoup(html)
for a in soup.find_all('a', href=True):
print "Found the URL:", a['href']
The output would be:
Found the URL: some_url
Found the URL: another_url
Note that if you're using an older version of BeautifulSoup (before version 4) the name of this method is findAll
. In version 4, BeautifulSoup's method names were changed to be PEP 8 compliant, so you should use find_all
instead.
If you want all tags with an href
, you can omit the name
parameter:
href_tags = soup.find_all(href=True)
You could do something like this in a loop based on the number of text fields they enter.
$('<input/>').attr({type:'text',name:'text'+i}).appendTo('#myform');
But for better performance I'd create all the html first and inject it into the DOM only once.
var count = 20;
var html = [];
while(count--) {
html.push("<input type='text' name='name", count, "'>");
}
$('#myform').append(html.join(''));
Edit this example uses jQuery to append the html, but you could easily modify it to use innerHTML as well.
If you want to avoid the hassle of escaping the special characters in your search and replacement string when using regular expressions, do the following steps:
Note that even if you want to manually pich matches for the first search and replace, you can safely use "replace all" for the three last steps.
For example, if you want to replace this:
public IFoo SomeField { get { return this.SomeField; } }
with that:
public IFoo Foo { get { return this.MyFoo; } }
public IBar Bar { get { return this.MyBar; } }
You would do the following substitutions:
public IFoo SomeField { get { return this.SomeField; } }
? XOXOXOXO
(regex off).XOXOXOXO
? XOXOXOXO\nHUHUHUHU
(regex on).XOXOXOXO
? public IFoo Foo { get { return this.MyFoo; } }
(regex off).HUHUHUHU
? public IFoo Bar { get { return this.MyBar; } }
(regex off).If you use native sql, you can refer to my code, otherwise just ignore my answer.
SELECT * FROM table WHERE tags LIKE "%banana%";
from sqlalchemy import text
bar_tags = "banana"
# '%' attention to spaces
query_sql = """SELECT * FROM table WHERE tags LIKE '%' :bar_tags '%'"""
# db is sqlalchemy session object
tags_res_list = db.execute(text(query_sql), {"bar_tags": bar_tags}).fetchall()
Could not commit JPA transaction: Transaction marked as rollbackOnly
This exception occurs when you invoke nested methods/services also marked as @Transactional
. JB Nizet explained the mechanism in detail. I'd like to add some scenarios when it happens as well as some ways to avoid it.
Suppose we have two Spring services: Service1
and Service2
. From our program we call Service1.method1()
which in turn calls Service2.method2()
:
class Service1 {
@Transactional
public void method1() {
try {
...
service2.method2();
...
} catch (Exception e) {
...
}
}
}
class Service2 {
@Transactional
public void method2() {
...
throw new SomeException();
...
}
}
SomeException
is unchecked (extends RuntimeException) unless stated otherwise.
Scenarios:
Transaction marked for rollback by exception thrown out of method2
. This is our default case explained by JB Nizet.
Annotating method2
as @Transactional(readOnly = true)
still marks transaction for rollback (exception thrown when exiting from method1
).
Annotating both method1
and method2
as @Transactional(readOnly = true)
still marks transaction for rollback (exception thrown when exiting from method1
).
Annotating method2
with @Transactional(noRollbackFor = SomeException)
prevents marking transaction for rollback (no exception thrown when exiting from method1
).
Suppose method2
belongs to Service1
. Invoking it from method1
does not go through Spring's proxy, i.e. Spring is unaware of SomeException
thrown out of method2
. Transaction is not marked for rollback in this case.
Suppose method2
is not annotated with @Transactional
. Invoking it from method1
does go through Spring's proxy, but Spring pays no attention to exceptions thrown. Transaction is not marked for rollback in this case.
Annotating method2
with @Transactional(propagation = Propagation.REQUIRES_NEW)
makes method2
start new transaction. That second transaction is marked for rollback upon exit from method2
but original transaction is unaffected in this case (no exception thrown when exiting from method1
).
In case SomeException
is checked (does not extend RuntimeException), Spring by default does not mark transaction for rollback when intercepting checked exceptions (no exception thrown when exiting from method1
).
See all scenarios tested in this gist.
I can't comment on the above answer, but be careful with @Pavel Chuchuva's answer. That formula will not return a result if both coordinates are the same. In that case, distance is null, and so that row won't be returned with that formula as is.
I'm not a MySQL expert, but this seems to be working for me:
SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance
FROM markers HAVING distance < 25 OR distance IS NULL ORDER BY distance LIMIT 0 , 20;
Based on acheron55 answer I posted a possible implementation here.
Here is a brief summery of it:
All you have to do, is to keep track of the path through which the target has been reached.
A simple way to do it, is to push into the Queue
the whole path used to reach a node, rather than the node itself.
The benefit of doing so is that when the target has been reached the queue holds the path used to reach it.
This is also applicable to cyclic graphs, where a node can have more than one parent.
If using in fragment then simply write
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
// Do something on UiThread
}
});
CREATE TABLE dbo.OwnerType
(
ID int NOT NULL,
Name varchar(50) NULL
)
insert into OwnerType (Name) values ('User');
insert into OwnerType (Name) values ('Group');
I think that would be the most general way to represent what you want instead of using a flag.
This issue can occur if the Azure Active Directory Module for Windows PowerShell isn't loaded correctly.
To resolve this issue, follow these steps.
1.Install the Azure Active Directory Module for Windows PowerShell on the computer (if it isn't already installed). To install the Azure Active Directory Module for Windows PowerShell, go to the following Microsoft website:
Manage Azure AD using Windows PowerShell
2.If the MSOnline module isn't present, use Windows PowerShell to import the MSOnline module.
Import-Module MSOnline
After it complete, we can use this command to check it.
PS C:\Users> Get-Module -ListAvailable -Name MSOnline*
Directory: C:\windows\system32\WindowsPowerShell\v1.0\Modules
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Manifest 1.1.166.0 MSOnline {Get-MsolDevice, Remove-MsolDevice, Enable-MsolDevice, Disable-MsolDevice...}
Manifest 1.1.166.0 MSOnlineExtended {Get-MsolDevice, Remove-MsolDevice, Enable-MsolDevice, Disable-MsolDevice...}
More information about this issue, please refer to it.
Update:
We should import azure AD powershell to VS 2015, we can add tool and select Azure AD powershell.
The current HTML5 draft specification does not specify which video formats browsers should support in the video tag. User agents are free to support any video formats they feel are appropriate.
The URI to open a specific channel in Slack app is:
slack://channel?id=<CHANNEL-ID>&team=<TEAM-ID>
You will probably need these resources of the Slack API to get IDs of your team and channel:
Here's the full documentation from Slack
You could do:
svn revert -R .
This will not delete any new file not under version control. But you can easily write a shell script to do that like:
for file in `svn status|grep "^ *?"|sed -e 's/^ *? *//'`; do rm $file ; done
I had a similar problem using Flask, but I did not have to resort to JSON. I just passed a list letters = ['a','b','c']
with render_template('show_entries.html', letters=letters)
, and set
var letters = {{ letters|safe }}
in my javascript code. Jinja2 replaced {{ letters }}
with ['a','b','c']
, which javascript interpreted as an array of strings.
You can't really, but you a halfway step might be:
<input type='number' step='0.01' value='0.00' placeholder='0.00' />
_x000D_
For Windows Server® 2008, Windows 7, Windows Server 2003, Windows Vista®, or Windows XP run "control userpasswords2"
Click the Start button, then click Run (Windows XP, Server 2003 or below)
Type control userpasswords2 and press Enter on your keyboard.
Note: For Windows 7 and Windows Vista, this command will not run by typing it in the Serach box on the Start Menu - it must be run using the Run option. To add the Run command to your Start menu, right-click on it and choose the option to customize it, then go to the Advanced options. Check to option to add the Run command.
You will see a window of user details!
Another option is also using:
div
{
white-space: pre-line;
}
This will set all your div elements in all browsers that support CSS1 (which is pretty much all common browsers as far back as IE 8)
We developed a page where it loaded a number of images and then performed other functions only after the image was loaded. It was a busy site that generated a lot of traffic. It seems that the following simple script worked on practically all browsers:
$(elem).onload = function() {
doSomething();
}
BUT THIS IS A POTENTIAL ISSUE FOR IE9!
The ONLY browser we had reported issues on is IE9. Are we not surprised? It seems that the best way to solve the issue there is to not assign a src to the image until AFTER the onload function has been defined, like so:
$(elem).onload = function() {
doSomething();
}
$(elem).attr('src','theimage.png');
It seems that IE 9 will sometimes not throw the onload
event for whatever reason. Other solutions on this page (such as the one from Evan Carroll, for example) still did not work. Logically, that checked if the load state was already successful and triggered the function and if it wasn't, then set the onload handler, but even when you do that we demonstrated in testing that the image could load between those two lines of js thereby appearing not loaded to the first line and then loading before the onload handler is set.
We found that the best way to get what you want is to not define the image's src until you have set the onload
event trigger.
We only just recently stopped supporting IE8 so I can't speak for versions prior to IE9, otherwise, out of all the other browsers that were used on the site -- IE10 and 11 as well as Firefox, Chrome, Opera, Safari and whatever mobile browser people were using -- setting the src
before assigning the onload
handler was not even an issue.
I think you missed a equal sign at:
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);
Change to:
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null);
2 steps to check if a cronjob is working :
Manually run php command :
/usr/bin/php /mydomain.in/cromail.php
And check if any error is displayed
I had this problem today using any of concat, append or merge, and I got around it by adding a helper column sequentially numbered and then doing an outer join
helper=1
for i in df1.index:
df1.loc[i,'helper']=helper
helper=helper+1
for i in df2.index:
df2.loc[i,'helper']=helper
helper=helper+1
df1.merge(df2,on='helper',how='outer')
Note: The question is about JavaScript, and this answer is about jQuery, which is wrong. This is an old answer, from times when jQuery was widespread.
Instead, I recommend understanding scopes and closures in JavaScript.
With jQuery you can just do this, no matter where the declaration is:
$my_global_var = 'my value';
And will be available everywhere.
I use it for making quick image galleries, when images are spread in different places, like so:
$gallery = $('img');
$current = 0;
$gallery.each(function(i,v){
// preload images
(new Image()).src = v;
});
$('div').eq(0).append('<a style="display:inline-block" class="prev">prev</a> <div id="gallery"></div> <a style="display:inline-block" class="next">next</a>');
$('.next').click(function(){
$current = ( $current == $gallery.length - 1 ) ? 0 : $current + 1;
$('#gallery').hide().html($gallery[$current]).fadeIn();
});
$('.prev').click(function(){
$current = ( $current == 0 ) ? $gallery.length - 1 : $current - 1;
$('#gallery').hide().html($gallery[$current]).fadeIn();
});
Tip: run this whole code in the console in this page ;-)
The category workaround posted by Nathan de Vries will pass the AppStore private API checks, and is useful in cases where you do not have control of the NSUrlConnection
object.
One example is NSXMLParser
which will open the URL you supply, but does not expose the NSURLRequest
or NSURLConnection
.
In iOS 4 the workaround still seems to work, but only on the device, the Simulator does not invoke the allowsAnyHTTPSCertificateForHost:
method anymore.
As others have stated it's combination of your schema and the number of indexes.
A friend had about 100,000,000 historical stock prices, daily closing quotes, in an MDB which approached the 2 Gb limit.
He pulled them down using some code found in a Microsoft Knowledge base article. I was rather surprised that whatever server he was using didn't cut him off after the first 100K records.
He could view any record in under a second.
Since you're returning a string as JSON, that string will include the opening and closing quotes in the raw response. So your response should probably look like:
"abc123XYZ=="
or whatever...You can try confirming this with Fiddler.
My guess is that the result.Content
is the raw string, including the quotes. If that's the case, then result.Content
will need to be deserialized before you can use it.
An alternative stacking arrangement which works and is perhaps a bit more intuitive is the following:
struct ContentView: View {
var body: some View {
HStack() {
VStack(alignment: .leading) {
Text("Hello World")
.font(.title)
Text("Another")
.font(.body)
Spacer()
}
Spacer()
}.background(Color.red)
}
}
The content can also easily be re-positioned by removing the Spacer()
's if necessary.
STEP 1: Go to Firebase Console
STEP 2: Select your Project
STEP 3: Click on Settings icon and select Project Settings
STEP 4: Select CLOUD MESSAGING tab
The fix is that yes, vertical padding and margin are relative to width, but top
and bottom
aren't.
So just place a div inside another, and in the inner div, use something like top:50%
(remember position
matters if it still doesn't work)
I will try to cover it with examples:
Lock: One example where you would use lock
would be a shared dictionary into which items (that must have unique keys) are added.
The lock would ensure that one thread does not enter the mechanism of code that is checking for item being in dictionary while another thread (that is in the critical section) already has passed this check and is adding the item. If another thread tries to enter a locked code, it will wait (be blocked) until the object is released.
private static readonly Object obj = new Object();
lock (obj) //after object is locked no thread can come in and insert item into dictionary on a different thread right before other thread passed the check...
{
if (!sharedDict.ContainsKey(key))
{
sharedDict.Add(item);
}
}
Semaphore: Let's say you have a pool of connections, then an single thread might reserve one element in the pool by waiting for the semaphore to get a connection. It then uses the connection and when work is done releases the connection by releasing the semaphore.
Code example that I love is one of bouncer given by @Patric - here it goes:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace TheNightclub
{
public class Program
{
public static Semaphore Bouncer { get; set; }
public static void Main(string[] args)
{
// Create the semaphore with 3 slots, where 3 are available.
Bouncer = new Semaphore(3, 3);
// Open the nightclub.
OpenNightclub();
}
public static void OpenNightclub()
{
for (int i = 1; i <= 50; i++)
{
// Let each guest enter on an own thread.
Thread thread = new Thread(new ParameterizedThreadStart(Guest));
thread.Start(i);
}
}
public static void Guest(object args)
{
// Wait to enter the nightclub (a semaphore to be released).
Console.WriteLine("Guest {0} is waiting to entering nightclub.", args);
Bouncer.WaitOne();
// Do some dancing.
Console.WriteLine("Guest {0} is doing some dancing.", args);
Thread.Sleep(500);
// Let one guest out (release one semaphore).
Console.WriteLine("Guest {0} is leaving the nightclub.", args);
Bouncer.Release(1);
}
}
}
Mutex It is pretty much Semaphore(1,1)
and often used globally (application wide otherwise arguably lock
is more appropriate). One would use global Mutex
when deleting node from a globally accessible list (last thing you want another thread to do something while you are deleting the node). When you acquire Mutex
if different thread tries to acquire the same Mutex
it will be put to sleep till SAME thread that acquired the Mutex
releases it.
Good example on creating global mutex is by @deepee
class SingleGlobalInstance : IDisposable
{
public bool hasHandle = false;
Mutex mutex;
private void InitMutex()
{
string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();
string mutexId = string.Format("Global\\{{{0}}}", appGuid);
mutex = new Mutex(false, mutexId);
var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
var securitySettings = new MutexSecurity();
securitySettings.AddAccessRule(allowEveryoneRule);
mutex.SetAccessControl(securitySettings);
}
public SingleGlobalInstance(int timeOut)
{
InitMutex();
try
{
if(timeOut < 0)
hasHandle = mutex.WaitOne(Timeout.Infinite, false);
else
hasHandle = mutex.WaitOne(timeOut, false);
if (hasHandle == false)
throw new TimeoutException("Timeout waiting for exclusive access on SingleInstance");
}
catch (AbandonedMutexException)
{
hasHandle = true;
}
}
public void Dispose()
{
if (mutex != null)
{
if (hasHandle)
mutex.ReleaseMutex();
mutex.Dispose();
}
}
}
then use like:
using (new SingleGlobalInstance(1000)) //1000ms timeout on global lock
{
//Only 1 of these runs at a time
GlobalNodeList.Remove(node)
}
Hope this saves you some time.
To check the emptiness of a queryset:
if orgs.exists():
# Do something
or you can check for a the first item in a queryset, if it doesn't exist it will return None
:
if orgs.first():
# Do something
If you have a form action and an input type="submit"
inside form tags, it's going to submit the old fashioned way and basically refresh the page. When doing AJAX type transactions this isn't the desired effect you are after.
Remove the action. Or remove the form altogether, though in cases it does come in handy to serialize to cut your workload. If the form tags remain, move the button outside the form tags, or alternatively make it a link with an onclick or click handler as opposed to an input button. Jquery UI Buttons works great in this case because you can mimic an input button with an a tag element.
Here's another option that's longer but may be more readable:
Boolean(Number("0")); // false
Boolean(Number("1")); // true
Unfortunately, the old xkcd comic isn't completely up to date anymore.
Since Python 3.0 you have to write:
print("Hello, World!")
And someone has still to write that antigravity
library :(
There is no API for this, and you can't auto install it, you can just redirect them to it's Market page so they can upgrade. You can have your latest version in a file on a Web server, and have the app check it. Here's one implementation of this:
http://code.google.com/p/openintents/source/browse/#svn%2Ftrunk%2FUpdateCheckerApp
Your configuration should look similar to that. You may have to change <transport clientCredentialType="None" proxyCredentialType="None" />
depending on your needs for authentication. The config below doesn't require any authentication.
<bindings>
<basicHttpBinding>
<binding name="basicHttpBindingConfiguration">
<security mode="Transport">
<transport clientCredentialType="None" proxyCredentialType="None" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="XXX">
<endpoint
name="AAA"
address=""
binding="basicHttpBinding"
bindingConfiguration="basicHttpBindingConfiguration"
contract="YourContract" />
</service>
<services>
That will allow a WCF service with basicHttpBinding
to use HTTPS.
If you're on a Unix-like system, use gettimeofday
and convert the result from microseconds to milliseconds.
Popen.communicate()
documentation:
Note that if you want to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE. Similarly, to get anything other than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too.
Replacing os.popen*
pipe = os.popen(cmd, 'w', bufsize)
# ==>
pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin
Warning Use communicate() rather than stdin.write(), stdout.read() or stderr.read() to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.
So your example could be written as follows:
from subprocess import Popen, PIPE, STDOUT
p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
grep_stdout = p.communicate(input=b'one\ntwo\nthree\nfour\nfive\nsix\n')[0]
print(grep_stdout.decode())
# -> four
# -> five
# ->
On Python 3.5+ (3.6+ for encoding
), you could use subprocess.run
, to pass input as a string to an external command and get its exit status, and its output as a string back in one call:
#!/usr/bin/env python3
from subprocess import run, PIPE
p = run(['grep', 'f'], stdout=PIPE,
input='one\ntwo\nthree\nfour\nfive\nsix\n', encoding='ascii')
print(p.returncode)
# -> 0
print(p.stdout)
# -> four
# -> five
# ->
Given this binary tree:
Breadth First Traversal:
Traverse across each level from left to right.
"I'm G, my kids are D and I, my grandkids are B, E, H and K, their grandkids are A, C, F"
- Level 1: G
- Level 2: D, I
- Level 3: B, E, H, K
- Level 4: A, C, F
Order Searched: G, D, I, B, E, H, K, A, C, F
Depth First Traversal:
Traversal is not done ACROSS entire levels at a time. Instead, traversal dives into the DEPTH (from root to leaf) of the tree first. However, it's a bit more complex than simply up and down.
There are three methods:
1) PREORDER: ROOT, LEFT, RIGHT.
You need to think of this as a recursive process:
Grab the Root. (G)
Then Check the Left. (It's a tree)
Grab the Root of the Left. (D)
Then Check the Left of D. (It's a tree)
Grab the Root of the Left (B)
Then Check the Left of B. (A)
Check the Right of B. (C, and it's a leaf node. Finish B tree. Continue D tree)
Check the Right of D. (It's a tree)
Grab the Root. (E)
Check the Left of E. (Nothing)
Check the Right of E. (F, Finish D Tree. Move back to G Tree)
Check the Right of G. (It's a tree)
Grab the Root of I Tree. (I)
Check the Left. (H, it's a leaf.)
Check the Right. (K, it's a leaf. Finish G tree)
DONE: G, D, B, A, C, E, F, I, H, K
2) INORDER: LEFT, ROOT, RIGHT
Where the root is "in" or between the left and right child node.
Check the Left of the G Tree. (It's a D Tree)
Check the Left of the D Tree. (It's a B Tree)
Check the Left of the B Tree. (A)
Check the Root of the B Tree (B)
Check the Right of the B Tree (C, finished B Tree!)
Check the Right of the D Tree (It's a E Tree)
Check the Left of the E Tree. (Nothing)
Check the Right of the E Tree. (F, it's a leaf. Finish E Tree. Finish D Tree)...
Onwards until...
DONE: A, B, C, D, E, F, G, H, I, K
3) POSTORDER:
LEFT, RIGHT, ROOT
DONE: A, C, B, F, E, D, H, K, I, G
Usage (aka, why do we care):
I really enjoyed this simple Quora explanation of the Depth First Traversal methods and how they are commonly used:
"In-Order Traversal will print values [in order for the BST (binary search tree)]"
"Pre-order traversal is used to create a copy of the [binary search tree]."
"Postorder traversal is used to delete the [binary search tree]."
https://www.quora.com/What-is-the-use-of-pre-order-and-post-order-traversal-of-binary-trees-in-computing
It looks like the class.phpmailer.php file is corrupt. I would download the latest version and try again.
I've always used phpMailer's SMTP feature:
$mail->IsSMTP();
$mail->Host = "localhost";
And if you need debug info:
$mail->SMTPDebug = 2; // enables SMTP debug information (for testing)
// 1 = errors and messages
// 2 = messages only
How it looks:
Best solution to my case. I need video fit web view size. Use embed youtube link with your video id. Example:
WebView youtubeWebView; //todo find or bind web view
String myVideoYoutubeId = "-bvXmLR3Ozc";
outubeWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
});
WebSettings webSettings = youtubeWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setUseWideViewPort(true);
youtubeWebView.loadUrl("https://www.youtube.com/embed/" + myVideoYoutubeId);
Web view xml code
<WebView
android:id="@+id/youtube_web_view"
android:layout_width="match_parent"
android:layout_height="200dp"/>
Simply add height: 100%;
onto the #B2
styling. min-height
shouldn't be necessary.
If you:
byte[]
before sending to the response;InputStream
;@ControllerAdvice
picking up exceptions for you (or not).The code below is what you need:
@RequestMapping(value = "/stuff/{stuffId}", method = RequestMethod.GET)
public ResponseEntity<FileSystemResource> downloadStuff(@PathVariable int stuffId)
throws IOException {
String fullPath = stuffService.figureOutFileNameFor(stuffId);
File file = new File(fullPath);
long fileLength = file.length(); // this is ok, but see note below
HttpHeaders respHeaders = new HttpHeaders();
respHeaders.setContentType("application/pdf");
respHeaders.setContentLength(fileLength);
respHeaders.setContentDispositionFormData("attachment", "fileNameIwant.pdf");
return new ResponseEntity<FileSystemResource>(
new FileSystemResource(file), respHeaders, HttpStatus.OK
);
}
More on setContentLength()
: First of all, the content-length
header is optional per the HTTP 1.1 RFC. Still, if you can provide a value, it is better. To obtain such value, know that File#length()
should be good enough in the general case, so it is a safe default choice.
In very specific scenarios, though, it can be slow, in which case you should have it stored previously (e.g. in the DB), not calculated on the fly. Slow scenarios include: if the file is very large, specially if it is on a remote system or something more elaborated like that - a database, maybe.
InputStreamResource
If your resource is not a file, e.g. you pick the data up from the DB, you should use InputStreamResource
. Example:
InputStreamResource isr = new InputStreamResource(new FileInputStream(file));
return new ResponseEntity<InputStreamResource>(isr, respHeaders, HttpStatus.OK);
According to python documentation here is a statement:
8.15. types — Names for built-in types
Starting in Python 2.2, built-in factory functions such as
int()
andstr()
are also names for the corresponding types.
So isinstance()
should be preferred over type()
.
If you are familiar with RxJava, you can use Observable.interval(), which is pretty neat.
Observable.interval(60, TimeUnits.SECONDS)
.flatMap(new Function<Long, ObservableSource<String>>() {
@Override
public ObservableSource<String> apply(@NonNull Long aLong) throws Exception {
return getDataObservable(); //Where you pull your data
}
});
The downside of this is that you have to architect polling your data in a different way. However, there are a lot of benefits to the Reactive Programming way:
With RxAndroid, you can handle threads in just 2 lines of code.
Observable.interval(60, TimeUnits.SECONDS)
.flatMap(...) // polling data code
.subscribeOn(Schedulers.newThread()) // poll data on a background thread
.observeOn(AndroidSchedulers.mainThread()) // populate UI on main thread
.subscribe(...); // your UI code
Please check out RxJava. It has a high learning curve but it will make handling asynchronous calls in Android so much easier and cleaner.
Use this:
while IFS= read -r file ; do rm -- "$file" ; done < delete.list
If you need glob expansion you can omit quoting $file
:
IFS=""
while read -r file ; do rm -- $file ; done < delete.list
But be warned that file names can contain "problematic" content and I would use the unquoted version. Imagine this pattern in the file
*
*/*
*/*/*
This would delete quite a lot from the current directory! I would encourage you to prepare the delete list in a way that glob patterns aren't required anymore, and then use quoting like in my first example.
app.all('*', function(req, res,next) {
/**
* Response settings
* @type {Object}
*/
var responseSettings = {
"AccessControlAllowOrigin": req.headers.origin,
"AccessControlAllowHeaders": "Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name",
"AccessControlAllowMethods": "POST, GET, PUT, DELETE, OPTIONS",
"AccessControlAllowCredentials": true
};
/**
* Headers
*/
res.header("Access-Control-Allow-Credentials", responseSettings.AccessControlAllowCredentials);
res.header("Access-Control-Allow-Origin", responseSettings.AccessControlAllowOrigin);
res.header("Access-Control-Allow-Headers", (req.headers['access-control-request-headers']) ? req.headers['access-control-request-headers'] : "x-requested-with");
res.header("Access-Control-Allow-Methods", (req.headers['access-control-request-method']) ? req.headers['access-control-request-method'] : responseSettings.AccessControlAllowMethods);
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
});
You can use a function like this. Complete and modify it to your need :
/**
* Encode URL (except :, /, ?, &, =, ... characters)
* @param url to encode
* @param encodingCharset url encoding charset
* @return encoded URL
* @throws UnsupportedEncodingException
*/
public static String encodeUrl (String url, String encodingCharset) throws UnsupportedEncodingException{
return new URLCodec().encode(url, encodingCharset).replace("%3A", ":").replace("%2F", "/").replace("%3F", "?").replace("%3D", "=").replace("%26", "&");
}
Example of use :
String urlToEncode = ""http://www.growup.com/folder/intérieur-à_vendre?o=4";
Utils.encodeUrl (urlToEncode , "UTF-8")
The result is : http://www.growup.com/folder/int%C3%A9rieur-%C3%A0_vendre?o=4
If you know the location of installed jboss folder then simply open it and look for version.txt
file.
For anyone else who runs into this...
Version 1.2.0 of this plugin (current as of this post) doesn't quite work in all cases as documented with Bootstrap 3.0, but it does with a minor workaround.
Specifically, if using an input with icon, the HTML markup is of course slightly different as class names have changed:
<div class="input-group" data-datepicker="true">
<input name="date" type="text" class="form-control" />
<span class="input-group-addon"><i class="icon-calendar"></i></span>
</div>
It seems because of this, you need to use a selector that points directly to the input element itself NOT the parent container (which is what the auto generated HTML on the demo page suggests).
$('*[data-datepicker="true"] input[type="text"]').datepicker({
todayBtn: true,
orientation: "top left",
autoclose: true,
todayHighlight: true
});
Having done this you will probably also want to add a listener for clicking/tapping on the icon so it sets focus on the text input when clicked (which is the behaviour when using this plugin with TB 2.x by default).
$(document).on('touch click', '*[data-datepicker="true"] .input-group-addon', function(e){
$('input[type="text"]', $(this).parent()).focus();
});
NB: I just use a data-datepicker boolean attribute because the class name 'datepicker' is reserved by the plugin and I already use 'date' for styling elements.
You might try turning off pooling, which is enabled by default. See this discussion for more information.
import pyodbc
pyodbc.pooling = False
conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest')
csr = conn.cursor()
csr.close()
del csr
Depending on what you want the file to contain:
touch /path/to/file
for an empty filesomecommand > /path/to/file
for a file containing the output of some command.
eg: grep --help > randomtext.txt
echo "This is some text" > randomtext.txt
nano /path/to/file
or vi /path/to/file
(or any other editor emacs,gedit etc
)
It either opens the existing one for editing or creates & opens the empty file to enter, if it doesn't exist
Create the file using cat
$ cat > myfile.txt
Now, just type whatever you want in the file:
Hello World!
CTRL-D to save and exit
There are several possible solutions:
touch file
>file
echo -n > file
printf '' > file
The echo
version will work only if your version of echo
supports the -n
switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.
echo '' > file
printf '\n' > file
This is a valid "text file" because it ends in a newline.
"$EDITOR" file
echo 'text' > file
cat > file <<END \
text
END
printf 'text\n' > file
These are equivalent. The $EDITOR
command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat
version presumes a literal newline after the \
and after each other line. Other than that these will all work in a POSIX shell.
Of course there are many other methods of writing and creating files, too.
public void launchPlayStore(Context context, String packageName) {
Intent intent = null;
try {
intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse("market://details?id=" + packageName));
context.startActivity(intent);
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + packageName)));
}
}
Try this site full of Python Practice Problems. It leans towards problems that has already been solved so that you'll have reference solutions.
These links explain it with examples
http://dotnetperls.com/openfiledialog
http://www.geekpedia.com/tutorial67_Using-OpenFileDialog-to-open-files.html
private void button1_Click(object sender, EventArgs e)
{
int size = -1;
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog1.FileName;
try
{
string text = File.ReadAllText(file);
size = text.Length;
}
catch (IOException)
{
}
}
Console.WriteLine(size); // <-- Shows file size in debugging mode.
Console.WriteLine(result); // <-- For debugging use.
}
I believe that most of these answers are for bootstrap 2. I ran into the same issue for bootstrap 3 and wanted to share my fix. Like my previous answer for bootstrap 2, this will still do an opacity fade, but will NOT do the slide transition.
You can either change the modals.less or the theme.css files, depending on your workflow. If you haven't spent any quality time with less, I'd highly recommend it.
for less, find the following code in MODALS.less
&.fade .modal-dialog {
.translate(0, -25%);
.transition-transform(~"0.3s ease-out");
}
&.in .modal-dialog { .translate(0, 0)}
then change the -25%
to 0%
Alternatively, if you're using just the css, find the following in theme.css
:
.modal.fade .modal-dialog {
-webkit-transform: translate(0, -25%);
-ms-transform: translate(0, -25%);
transform: translate(0, -25%);
-webkit-transition: -webkit-transform 0.3s ease-out;
-moz-transition: -moz-transform 0.3s ease-out;
-o-transition: -o-transform 0.3s ease-out;
transition: transform 0.3s ease-out;
}
and then change the -25%
to 0%
.