Ok - for me the source of the problem was in serialisation/deserialisation. The object that was being sent and received was as follows where the code is submitted and the code and maskedPhoneNumber is returned.
@ApiObject(description = "What the object is for.")
@JsonIgnoreProperties(ignoreUnknown = true)
public class CodeVerification {
@ApiObjectField(description = "The code which is to be verified.")
@NotBlank(message = "mandatory")
private final String code;
@ApiObjectField(description = "The masked mobile phone number to which the code was verfied against.")
private final String maskedMobileNumber;
public codeVerification(@JsonProperty("code") String code, String maskedMobileNumber) {
this.code = code;
this.maskedMobileNumber = maskedMobileNumber;
}
public String getcode() {
return code;
}
public String getMaskedMobileNumber() {
return maskedMobileNumber;
}
}
The problem was that I didn't have a JsonProperty defined for the maskedMobileNumber in the constructor. i.e. Constructor should have been
public codeVerification(@JsonProperty("code") String code, @JsonProperty("maskedMobileNumber") String maskedMobileNumber) {
this.code = code;
this.maskedMobileNumber = maskedMobileNumber;
}
I think all you need to do for your function is just add PtrSafe: i.e. the first line of your first function should look like this:
Private Declare PtrSafe Function swe_azalt Lib "swedll32.dll" ......
Check if password you are using is correct one by running below command
keytool -keypasswd -new temp123 -keystore awsdemo-keystore.jks -storepass temp123 -alias movie-service -keypass changeit
If you are getting below error then your password is wrong
keytool error: java.security.UnrecoverableKeyException: Cannot recover key
I really like Tovask's answer but it doesn't work due to the function having the name download
(this answer explains why). I also don't see the point in replacing "data:image/..." with "data:application/...".
The following code has been tested in Chrome and Firefox and seems to work fine in both.
JavaScript:
function prepDownload(a, canvas, name) {
a.download = name
a.href = canvas.toDataURL()
}
HTML:
<a href="#" onclick="prepDownload(this, document.getElementById('canvasId'), 'imgName.png')">Download</a>
<canvas id="canvasId"></canvas>
For z-index to work, you also need to give it a position:
header {
width: 100%;
height: 100px;
background: url(../img/top.png) repeat-x;
z-index: 110;
position: relative;
}
Check the output before the statement that caused current transaction is aborted
. This typically means that database threw an exception that your code had ignored and now expecting next queries to return some data.
So you now have a state mismatch between your application, which considers things are fine, and database, that requires you to rollback and re-start your transaction from the beginning.
You should catch all exceptions and rollback transactions in such cases.
For one, you don't seem to be including jQuery itself in the header but only a bunch of plugins. As for the '<' error, it's impossible to tell without seeing the generated HTML.
Note Slipstream's response, that base64.b64encode
and base64.b64decode
need bytes-like object, not string.
>>> import base64
>>> a = '{"name": "John", "age": 42}'
>>> base64.b64encode(a)
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/usr/lib/python3.6/base64.py", line 58, in b64encode
encoded = binascii.b2a_base64(s, newline=False)
TypeError: a bytes-like object is required, not 'str'
Just a little addition if one wants to parse a space separated text file line by line.
read_file = function (path)
local file = io.open(path, "rb")
if not file then return nil end
local lines = {}
for line in io.lines(path) do
local words = {}
for word in line:gmatch("%w+") do
table.insert(words, word)
end
table.insert(lines, words)
end
file:close()
return lines;
end
For future questioners: If you can't drop the tables from the console, try to create a migration that drops the tables for you. You should create a migration and then in the file note tables you want dropped like this:
class DropTables < ActiveRecord::Migration
def up
drop_table :table_you_dont_want
end
def down
raise ActiveRecord::IrreversibleMigration
end
end
Configuring a working email client from localhost is quite a chore, I have spent hours of frustration attempting it. I'm sure someone more experienced may be able to help, or they may perhaps agree with me.
If you just want to test, here is a great tool for testing mail locally, that requires almost no configuration:
http://www.toolheap.com/test-mail-server-tool/
It worked right off the bat for me, hope this helps you.
A Task can be seen as a convenient and easy way to execute something asynchronously and in parallel.
Normally a Task is all you need, I cannot remember if I have ever used a thread for something else than experimentation.
You can accomplish the same with a thread (with lots of effort) as you can with a task.
Thread
int result = 0;
Thread thread = new System.Threading.Thread(() => {
result = 1;
});
thread.Start();
thread.Join();
Console.WriteLine(result); //is 1
Task
int result = await Task.Run(() => {
return 1;
});
Console.WriteLine(result); //is 1
A task will by default use the Threadpool, which saves resources as creating threads can be expensive. You can see a Task as a higher level abstraction upon threads.
As this article points out, task provides following powerful features over thread.
Tasks are tuned for leveraging multicores processors.
If system has multiple tasks then it make use of the CLR thread pool internally, and so do not have the overhead associated with creating a dedicated thread using the Thread. Also reduce the context switching time among multiple threads.
Wait on a set of tasks, without a signaling construct.
We can chain tasks together to execute one after the other.
Establish a parent/child relationship when one task is started from another task.
Child task exception can propagate to parent task.
Task support cancellation through the use of cancellation tokens.
Asynchronous implementation is easy in task, using’ async’ and ‘await’ keywords.
The read_sql
docs say this params
argument can be a list, tuple or dict (see docs).
To pass the values in the sql query, there are different syntaxes possible: ?
, :1
, :name
, %s
, %(name)s
(see PEP249).
But not all of these possibilities are supported by all database drivers, which syntax is supported depends on the driver you are using (psycopg2
in your case I suppose).
In your second case, when using a dict, you are using 'named arguments', and according to the psycopg2
documentation, they support the %(name)s
style (and so not the :name
I suppose), see http://initd.org/psycopg/docs/usage.html#query-parameters.
So using that style should work:
df = psql.read_sql(('select "Timestamp","Value" from "MyTable" '
'where "Timestamp" BETWEEN %(dstart)s AND %(dfinish)s'),
db,params={"dstart":datetime(2014,6,24,16,0),"dfinish":datetime(2014,6,24,17,0)},
index_col=['Timestamp'])
Nobody mentions memcmp
? This is also a good choice.
/* memcmp example */
#include <stdio.h>
#include <string.h>
int main ()
{
char buffer1[] = "DWgaOtP12df0";
char buffer2[] = "DWGAOTP12DF0";
int n;
n=memcmp ( buffer1, buffer2, sizeof(buffer1) );
if (n>0) printf ("'%s' is greater than '%s'.\n",buffer1,buffer2);
else if (n<0) printf ("'%s' is less than '%s'.\n",buffer1,buffer2);
else printf ("'%s' is the same as '%s'.\n",buffer1,buffer2);
return 0;
}
I find the following to work best, called the central error handling approach.
You have 2 modes of running your application: Debug and Production. In the Debug mode, the code will stop at any unexpected error and allow you to debug easily by jumping to the line where it occurred by pressing F8 twice. In the Production mode, a meaningful error message will get displayed to the user.
You can throw intentional errors like this, which will stop execution of the code with a message to the user:
Err.Raise vbObjectError, gsNO_DEBUG, "Some meaningful error message to the user"
Err.Raise vbObjectError, gsUSER_MESSAGE, "Some meaningful non-error message to the user"
'Or to exit in the middle of a call stack without a message:
Err.Raise vbObjectError, gsSILENT
You need to "wrap" all subroutines and functions with any significant amount of code with the following headers and footers, making sure to specify ehCallTypeEntryPoint
in all your entry points. Note the msModule
constant as well, which needs to be put in all modules.
Option Explicit
Const msModule As String = "<Your Module Name>"
' This is an entry point
Public Sub AnEntryPoint()
Const sSOURCE As String = "AnEntryPoint"
On Error GoTo ErrorHandler
'Your code
ErrorExit:
Exit Sub
ErrorHandler:
If CentralErrorHandler(Err, ThisWorkbook, msModule, sSOURCE, ehCallTypeEntryPoint) Then
Stop
Resume
Else
Resume ErrorExit
End If
End Sub
' This is any other subroutine or function that isn't an entry point
Sub AnyOtherSub()
Const sSOURCE As String = "AnyOtherSub"
On Error GoTo ErrorHandler
'Your code
ErrorExit:
Exit Sub
ErrorHandler:
If CentralErrorHandler(Err, ThisWorkbook, msModule, sSOURCE) Then
Stop
Resume
Else
Resume ErrorExit
End If
End Sub
The contents of the central error handler module is the following:
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Comments: Error handler code.
'
' Run SetDebugMode True to use debug mode (Dev mode)
' It will be False by default (Production mode)
'
' Author: Igor Popov
' Date: 13 Feb 2014
' Licence: MIT
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Option Explicit
Option Private Module
Private Const msModule As String = "MErrorHandler"
Public Const gsAPP_NAME As String = "<You Application Name>"
Public Const gsSILENT As String = "UserCancel" 'A silent error is when the user aborts an action, no message should be displayed
Public Const gsNO_DEBUG As String = "NoDebug" 'This type of error will display a specific message to the user in situation of an expected (provided-for) error.
Public Const gsUSER_MESSAGE As String = "UserMessage" 'Use this type of error to display an information message to the user
Private Const msDEBUG_MODE_COMPANY = "<Your Company>"
Private Const msDEBUG_MODE_SECTION = "<Your Team>"
Private Const msDEBUG_MODE_VALUE = "DEBUG_MODE"
Public Enum ECallType
ehCallTypeRegular = 0
ehCallTypeEntryPoint
End Enum
Public Function DebugMode() As Boolean
DebugMode = CBool(GetSetting(msDEBUG_MODE_COMPANY, msDEBUG_MODE_SECTION, msDEBUG_MODE_VALUE, 0))
End Function
Public Sub SetDebugMode(Optional bMode As Boolean = True)
SaveSetting msDEBUG_MODE_COMPANY, msDEBUG_MODE_SECTION, msDEBUG_MODE_VALUE, IIf(bMode, 1, 0)
End Sub
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Comments: The central error handler for all functions
' Displays errors to the user at the entry point level, or, if we're below the entry point, rethrows it upwards until the entry point is reached
'
' Returns True to stop and debug unexpected errors in debug mode.
'
' The function can be enhanced to log errors.
'
' Date Developer TDID Comment
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' 13 Feb 2014 Igor Popov Created
Public Function CentralErrorHandler(ErrObj As ErrObject, Wbk As Workbook, ByVal sModule As String, ByVal sSOURCE As String, _
Optional enCallType As ECallType = ehCallTypeRegular, Optional ByVal bRethrowError As Boolean = True) As Boolean
Static ssModule As String, ssSource As String
If Len(ssModule) = 0 And Len(ssSource) = 0 Then
'Remember the module and the source of the first call to CentralErrorHandler
ssModule = sModule
ssSource = sSOURCE
End If
CentralErrorHandler = DebugMode And ErrObj.Source <> gsNO_DEBUG And ErrObj.Source <> gsUSER_MESSAGE And ErrObj.Source <> gsSILENT
If CentralErrorHandler Then
'If it's an unexpected error and we're going to stop in the debug mode, just write the error message to the immediate window for debugging
Debug.Print "#Err: " & Err.Description
ElseIf enCallType = ehCallTypeEntryPoint Then
'If we have reached the entry point and it's not a silent error, display the message to the user in an error box
If ErrObj.Source <> gsSILENT Then
Dim sMsg As String: sMsg = ErrObj.Description
If ErrObj.Source <> gsNO_DEBUG And ErrObj.Source <> gsUSER_MESSAGE Then sMsg = "Unexpected VBA error in workbook '" & Wbk.Name & "', module '" & ssModule & "', call '" & ssSource & "':" & vbCrLf & vbCrLf & sMsg
MsgBox sMsg, vbOKOnly + IIf(ErrObj.Source = gsUSER_MESSAGE, vbInformation, vbCritical), gsAPP_NAME
End If
ElseIf bRethrowError Then
'Rethrow the error to the next level up if bRethrowError is True (by Default).
'Otherwise, do nothing as the calling function must be having special logic for handling errors.
Err.Raise ErrObj.Number, ErrObj.Source, ErrObj.Description
End If
End Function
To set yourself in the Debug mode, run the following in the Immediate window:
SetDebugMode True
You can use the util library that comes with nodejs to get a promise from the exec command and can use that output as you need. Use restructuring to store the stdout and stderr in variables.
const util = require('util');
const exec = util.promisify(require('child_process').exec);
async function lsExample() {
const {
stdout,
stderr
} = await exec('ls');
console.log('stdout:', stdout);
console.error('stderr:', stderr);
}
lsExample();
_x000D_
You can also add underscore.js to your project and will be able to do it in one line:
_.map($("input[name='category_ids[]']:checked"), function(el){return $(el).val()})
Try this way
UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
activityIndicator.frame = CGRectMake(10.0, 0.0, 40.0, 40.0);
activityIndicator.center = super_view.center;
[super_view addSubview: activityIndicator];
[activityIndicator startAnimating];
Attention Android Wear developers: "Remove Unused Resources" will delete the xml file where you declare the capability name (res/values/wear.xml) and the phone won't be able to connect to the watch. I spent hours trying to figure out this bug in my app.
List list = new ArrayList();
Or with generics
List<String> list = new ArrayList<String>();
You can, of course, replace string with any type of variable, such as Integer, also.
By default, oracle date subtraction returns a result in # of days.
So just multiply by 24 to get # of hours, and again by 60 for # of minutes.
Example:
select
round((second_date - first_date) * (60 * 24),2) as time_in_minutes
from
(
select
to_date('01/01/2008 01:30:00 PM','mm/dd/yyyy hh:mi:ss am') as first_date
,to_date('01/06/2008 01:35:00 PM','mm/dd/yyyy HH:MI:SS AM') as second_date
from
dual
) test_data
A modern and fast solution, for Python 3.7. May also work in some interpreters of Python 3.6.
TLDR
To sort a dictionary by keys use:
sorted_dict = {k: disordered[k] for k in sorted(disordered)}
Almost three times faster than the accepted answer; probably more when you include imports.
Comment on the accepted answer
The example in the accepted answer instead of iterating over the keys only - with key
parameter of sorted()
or the default behaviour of dict iteration - iterates over tuples (key, value)
, which suprisingly turns out to be much slower than comparing the keys only and accessing dictionary elements in a list comprehension.
How to sort by key in Python 3.7
The big change in Python 3.7 is that the dictionaries are now ordered by default.
OrderedDict
might still be preferable for the compatibility sake.sorted(d.items())
without key
.See:
disordered = {10: 'b', 3: 'a', 5: 'c'}
# sort keys, then get values from original - fast
sorted_dict = {k: disordered[k] for k in sorted(disordered)}
# key = itemgetter - slower
from operator import itemgetter
key = itemgetter(0)
sorted_dict = {k: v for k, v in sorted(disordered.items(), key=key)}
# key = lambda - the slowest
key = lambda item: item[0]
sorted_dict = {k: v for k in sorted(disordered.items(), key=key)}
Timing results:
Best for {k: d[k] for k in sorted(d)}: 7.507327548999456
Best for {k: v for k, v in sorted(d.items(), key=key_getter)}: 12.031082626002899
Best for {k: v for k, v in sorted(d.items(), key=key_lambda)}: 14.22885995300021
Best for dict(sorted(d.items(), key=key_getter)): 11.209122000000207
Best for dict(sorted(d.items(), key=key_lambda)): 13.289728325995384
Best for dict(sorted(d.items())): 14.231471302999125
Best for OrderedDict(sorted(d.items(), key=key_getter)): 16.609151654003654
Best for OrderedDict(sorted(d.items(), key=key_lambda)): 18.52622927199991
Best for OrderedDict(sorted(d.items())): 19.436101284998585
Testing code:
from timeit import repeat
setup_code = """
from operator import itemgetter
from collections import OrderedDict
import random
random.seed(0)
d = {i: chr(i) for i in [random.randint(0, 120) for repeat in range(120)]}
key_getter = itemgetter(0)
key_lambda = lambda item: item[0]
"""
cases = [
# fast
'{k: d[k] for k in sorted(d)}',
'{k: v for k, v in sorted(d.items(), key=key_getter)}',
'{k: v for k, v in sorted(d.items(), key=key_lambda)}',
# slower
'dict(sorted(d.items(), key=key_getter))',
'dict(sorted(d.items(), key=key_lambda))',
'dict(sorted(d.items()))',
# the slowest
'OrderedDict(sorted(d.items(), key=key_getter))',
'OrderedDict(sorted(d.items(), key=key_lambda))',
'OrderedDict(sorted(d.items()))',
]
for code in cases:
times = repeat(code, setup=setup_code, repeat=3)
print(f"Best for {code}: {min(times)}")
Define "remove".
Arrays are fixed length and can not be resized once created. You can set an element to null
to remove an object reference;
for (int i = 0; i < myStringArray.length(); i++)
{
if (myStringArray[i].equals(stringToRemove))
{
myStringArray[i] = null;
break;
}
}
or
myStringArray[indexOfStringToRemove] = null;
If you want a dynamically sized array where the object is actually removed and the list (array) size is adjusted accordingly, use an ArrayList<String>
myArrayList.remove(stringToRemove);
or
myArrayList.remove(indexOfStringToRemove);
Edit in response to OP's edit to his question and comment below
String r = myArrayList.get(rgenerator.nextInt(myArrayList.size()));
It is an implementation of Pythagorean theorem. Link: http://en.wikipedia.org/wiki/Pythagorean_theorem
I know it was asked over 6 years ago, but knowledge is still knowledge. This is different solution than all above, as I had to run it under SQL Server 2000:
DECLARE @TestData TABLE([ID] int, [SKU] char(6), [Product] varchar(15))
INSERT INTO @TestData values (1 ,'FOO-23', 'Orange')
INSERT INTO @TestData values (2 ,'BAR-23', 'Orange')
INSERT INTO @TestData values (3 ,'FOO-24', 'Apple')
INSERT INTO @TestData values (4 ,'FOO-25', 'Orange')
SELECT DISTINCT [ID] = ( SELECT TOP 1 [ID] FROM @TestData Y WHERE Y.[Product] = X.[Product])
,[SKU]= ( SELECT TOP 1 [SKU] FROM @TestData Y WHERE Y.[Product] = X.[Product])
,[PRODUCT]
FROM @TestData X
<ToggleButton
android:id="@+id/togglebutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="Vibrate on"
android:textOff="Vibrate off"
android:onClick="onToggleClicked"/>
Within the Activity that hosts this layout, the following method handles the click event:
public void onToggleClicked(View view) {
// Is the toggle on?
boolean on = ((ToggleButton) view).isChecked();
if (on) {
// Enable vibrate
} else {
// Disable vibrate
}
}
select left(col, charindex(' ', col) - 1)
set style="height:300px !important;" and "imgBanner" for img tag.
<img src="/image/1.jpg" class="imgBanner" style="width:100%; height:300px !important;">
then if you want responsive image, so you can use jquery as:
$.(function(){
$(window).resize(respWhenResize);
respWhenResize();
})
respWhenResize(){
if (pagesize < 578) {
$('.imgBanner').css('height','200px')
} else if (pagesize > 578 ) {
$('.imgBanner').css('height','300px')
}
}
I think this solution is handy if you can test the value of the error field later. This is also applicable by creating a temporary table and returning a list of errors.
DROP PROCEDURE IF EXISTS $procName;
DELIMITER //
CREATE PROCEDURE $procName($params)
BEGIN
DECLARE error INT DEFAULT 0;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET error = 1;
SELECT
$fields
FROM $tables
WHERE $where
ORDER BY $sorting LIMIT 1
INTO $vars;
IF error = 0 THEN
SELECT $vars;
ELSE
SELECT 1 AS error;
SET @error = 0;
END IF;
END//
CALL $procName($effp);
I came to this page specifically looking for a way to format an error string. So if someone needs help with the same, you want to use the fmt.Errorf()
function.
The method signature is func Errorf(format string, a ...interface{}) error
.
It returns the formatted string as a value that satisfies the error
interface.
You can look up more details in the documentation - https://golang.org/pkg/fmt/#Errorf.
I use matplotlib for reading TIFF files:
import matplotlib.pyplot as plt
I = plt.imread(tiff_file)
and I
will be of type ndarray
.
According to the documentation though it is actually PIL that works behind the scenes when handling TIFFs as matplotlib only reads PNGs natively, but this has been working fine for me.
There's also a plt.imsave
function for saving.
git log --reflog
saved me! I lost mine while merging HEAD and could not find my lates commit! Not showing in source tree but git log --reflog
show all my local commits before
Here is how I solved the issue, might be useful to some:
Ajax modal doesn't seem to be available with boostrap 2.1.1
So I ended up coding it myself:
$('[data-toggle="modal"]').click(function(e) {
e.preventDefault();
var url = $(this).attr('href');
//var modal_id = $(this).attr('data-target');
$.get(url, function(data) {
$(data).modal();
});
});
Example of a link that calls a modal:
<a href="{{ path('ajax_get_messages', { 'superCategoryID': 6, 'sex': sex }) }}" data-toggle="modal">
<img src="{{ asset('bundles/yopyourownpoet/images/messageCategories/BirthdaysAnniversaries.png') }}" alt="Birthdays" height="120" width="109"/>
</a>
I now send the whole modal markup through ajax.
Credits to drewjoh
You can bind state value directly to style object. Here is an example:
class Timer extends Component{
constructor(props){
super(props);
this.state = {timer: 0, color: '#FF0000'};
setInterval(() => {
this.setState({timer: this.state.timer + 1, color: this.state.timer % 2 == 0 ? '#FF0000' : '#0000FF'});
}, 1000);
}
render(){
return (
<View>
<Text>Timer:</Text>
<Text style={{backgroundColor: this.state.color}}>{this.state.timer}</Text>
</View>
);
}
}
if you want to use hex code of color which is in this format #123456 then it is very easily be used, create A variables of type Color and assign the following values to it.
Color myHexColor = Color(0xff123456)
// her you notice I use the 0xff and that is opacity or transparency of the color
// and you can also change these value .
use myhexcolor and you are ready to go .
if you want to change the opacity of color direct from the hex code then change the ff value in 0xff to the respectively value from the table below.
Hex Opacity Values
100% — FF
95% — F2
90% — E6
85% — D9
80% — CC
75% — BF
70% — B3
65% — A6
60% — 99
55% — 8C
50% — 80
45% — 73
40% — 66
35% — 59
30% — 4D
25% — 40
20% — 33
15% — 26
10% — 1A
5% — 0D
0% — 00
Codified version of all other answers (at the time of writing):
import java.io.*;
/**
* This class is based on <a href="http://stackoverflow.com/users/2478930/cheneym">cheneym</a>'s
* <a href="http://stackoverflow.com/a/18375641/253468">awesome interpretation</a>
* of the Java {@link Runtime}'s memory query methods, which reflects intuitive thinking.
* Also includes comments and observations from others on the same question, and my own experience.
* <p>
* <img src="https://i.stack.imgur.com/GjuwM.png" alt="Runtime's memory interpretation">
* <p>
* <b>JVM memory management crash course</b>:
* Java virtual machine process' heap size is bounded by the maximum memory allowed.
* The startup and maximum size can be configured by JVM arguments.
* JVMs don't allocate the maximum memory on startup as the program running may never require that.
* This is to be a good player and not waste system resources unnecessarily.
* Instead they allocate some memory and then grow when new allocations require it.
* The garbage collector will be run at times to clean up unused objects to prevent this growing.
* Many parameters of this management such as when to grow/shrink or which GC to use
* can be tuned via advanced configuration parameters on JVM startup.
*
* @see <a href="http://stackoverflow.com/a/42567450/253468">
* What are Runtime.getRuntime().totalMemory() and freeMemory()?</a>
* @see <a href="http://www.oracle.com/technetwork/java/javase/memorymanagement-whitepaper-150215.pdf">
* Memory Management in the Sun Java HotSpot™ Virtual Machine</a>
* @see <a href="http://docs.oracle.com/javase/8/docs/technotes/tools/windows/java.html">
* Full VM options reference for Windows</a>
* @see <a href="http://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html">
* Full VM options reference for Linux, Mac OS X and Solaris</a>
* @see <a href="http://www.oracle.com/technetwork/articles/java/vmoptions-jsp-140102.html">
* Java HotSpot VM Options quick reference</a>
*/
public class SystemMemory {
// can be white-box mocked for testing
private final Runtime runtime = Runtime.getRuntime();
/**
* <b>Total allocated memory</b>: space currently reserved for the JVM heap within the process.
* <p>
* <i>Caution</i>: this is not the total memory, the JVM may grow the heap for new allocations.
*/
public long getAllocatedTotal() {
return runtime.totalMemory();
}
/**
* <b>Current allocated free memory</b>: space immediately ready for new objects.
* <p>
* <i>Caution</i>: this is not the total free available memory,
* the JVM may grow the heap for new allocations.
*/
public long getAllocatedFree() {
return runtime.freeMemory();
}
/**
* <b>Used memory</b>:
* Java heap currently used by instantiated objects.
* <p>
* <i>Caution</i>: May include no longer referenced objects, soft references, etc.
* that will be swept away by the next garbage collection.
*/
public long getUsed() {
return getAllocatedTotal() - getAllocatedFree();
}
/**
* <b>Maximum allocation</b>: the process' allocated memory will not grow any further.
* <p>
* <i>Caution</i>: This may change over time, do not cache it!
* There are some JVMs / garbage collectors that can shrink the allocated process memory.
* <p>
* <i>Caution</i>: If this is true, the JVM will likely run GC more often.
*/
public boolean isAtMaximumAllocation() {
return getAllocatedTotal() == getTotal();
// = return getUnallocated() == 0;
}
/**
* <b>Unallocated memory</b>: amount of space the process' heap can grow.
*/
public long getUnallocated() {
return getTotal() - getAllocatedTotal();
}
/**
* <b>Total designated memory</b>: this will equal the configured {@code -Xmx} value.
* <p>
* <i>Caution</i>: You can never allocate more memory than this, unless you use native code.
*/
public long getTotal() {
return runtime.maxMemory();
}
/**
* <b>Total free memory</b>: memory available for new Objects,
* even at the cost of growing the allocated memory of the process.
*/
public long getFree() {
return getTotal() - getUsed();
// = return getAllocatedFree() + getUnallocated();
}
/**
* <b>Unbounded memory</b>: there is no inherent limit on free memory.
*/
public boolean isBounded() {
return getTotal() != Long.MAX_VALUE;
}
/**
* Dump of the current state for debugging or understanding the memory divisions.
* <p>
* <i>Caution</i>: Numbers may not match up exactly as state may change during the call.
*/
public String getCurrentStats() {
StringWriter backing = new StringWriter();
PrintWriter out = new PrintWriter(backing, false);
out.printf("Total: allocated %,d (%.1f%%) out of possible %,d; %s, %s %,d%n",
getAllocatedTotal(),
(float)getAllocatedTotal() / (float)getTotal() * 100,
getTotal(),
isBounded()? "bounded" : "unbounded",
isAtMaximumAllocation()? "maxed out" : "can grow",
getUnallocated()
);
out.printf("Used: %,d; %.1f%% of total (%,d); %.1f%% of allocated (%,d)%n",
getUsed(),
(float)getUsed() / (float)getTotal() * 100,
getTotal(),
(float)getUsed() / (float)getAllocatedTotal() * 100,
getAllocatedTotal()
);
out.printf("Free: %,d (%.1f%%) out of %,d total; %,d (%.1f%%) out of %,d allocated%n",
getFree(),
(float)getFree() / (float)getTotal() * 100,
getTotal(),
getAllocatedFree(),
(float)getAllocatedFree() / (float)getAllocatedTotal() * 100,
getAllocatedTotal()
);
out.flush();
return backing.toString();
}
public static void main(String... args) {
SystemMemory memory = new SystemMemory();
System.out.println(memory.getCurrentStats());
}
}
JAVA_HOME
and JRE_HOME
are not used by Java itself. Some third-party programs (for example Apache Tomcat) expect one of these environment variables to be set to the installation directory of the JDK
or JRE
. If you are not using software that requires them, you do not need to set JAVA_HOME
and JRE_HOME
.
PATH
is an environment variable used by the operating system (Windows, Mac OS X, Linux) where it will look for native executable programs to run. You should add the bin
subdirectory of your JDK
installation directory to the PATH
, so that you can use the javac
and java
commands and other JDK
tools in a command prompt window. Courtesy: coderanch
For file operations, Python uses the operating system's default buffering unless you configure it do otherwise. You can specify a buffer size, unbuffered, or line buffered.
For example, the open function takes a buffer size argument.
http://docs.python.org/library/functions.html#open
"The optional buffering argument specifies the file’s desired buffer size:"
code:
bufsize = 0
f = open('file.txt', 'w', buffering=bufsize)
Fixed positioning is supported on mobile since Android 2.2 and iOS 5.
You need to use device-with viewport on meta and give the background image with somewhere with an id. Then you will get that id with jquery and give that a height. And of course 100% width
<html>
<head>
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
#main {
background: url(1.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
width: 100%;
overflow: hidden;
}
</style>
</head>
<body id="main">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
var hgt = $(window).height();
$("#main").css("height", hgt)
</script>
Quentin is correct, it can't be done with CSS. If you want to add a title
attribute, you can do it with JavaScript. Here's an example using jQuery:
$('label').attr('title','mandatory');
Is using MS SQL Server you can do the following:
--List all tables primary keys
select * from information_schema.table_constraints
where constraint_type = 'Primary Key'
You can also filter on the table_name column if you want a specific table.
Edit:
In 2.7 / 3.2 there is a new writeheader()
method. Also, John Machin's answer provides a simpler method of writing the header row.
Simple example of using the writeheader()
method now available in 2.7 / 3.2:
from collections import OrderedDict
ordered_fieldnames = OrderedDict([('field1',None),('field2',None)])
with open(outfile,'wb') as fou:
dw = csv.DictWriter(fou, delimiter='\t', fieldnames=ordered_fieldnames)
dw.writeheader()
# continue on to write data
Instantiating DictWriter requires a fieldnames argument.
From the documentation:
The fieldnames parameter identifies the order in which values in the dictionary passed to the writerow() method are written to the csvfile.
Put another way: The Fieldnames argument is required because Python dicts are inherently unordered.
Below is an example of how you'd write the header and data to a file.
Note: with
statement was added in 2.6. If using 2.5: from __future__ import with_statement
with open(infile,'rb') as fin:
dr = csv.DictReader(fin, delimiter='\t')
# dr.fieldnames contains values from first row of `f`.
with open(outfile,'wb') as fou:
dw = csv.DictWriter(fou, delimiter='\t', fieldnames=dr.fieldnames)
headers = {}
for n in dw.fieldnames:
headers[n] = n
dw.writerow(headers)
for row in dr:
dw.writerow(row)
As @FM mentions in a comment, you can condense header-writing to a one-liner, e.g.:
with open(outfile,'wb') as fou:
dw = csv.DictWriter(fou, delimiter='\t', fieldnames=dr.fieldnames)
dw.writerow(dict((fn,fn) for fn in dr.fieldnames))
for row in dr:
dw.writerow(row)
Here's some options that keep the file self-contained without retastering the image:
div
tags<div style="width:300px; height:200px">
![Image](path/to/image)
</div>
---
title: test
output: html_document
css: test.css
---
## Page with an image {#myImagePage}
![Image](path/to/image)
#myImagePage img {
width: 400px;
height: 200px;
}
If you have more than one image you might need to use the nth-child pseudo-selector for this second option.
The extend
method for example in jQuery or PrototypeJS, copies all properties from the source to the destination object.
Now about the prototype
property, it is a member of function objects, it is part of the language core.
Any function can be used as a constructor, to create new object instances. All functions have this prototype
property.
When you use the new
operator with on a function object, a new object will be created, and it will inherit from its constructor prototype
.
For example:
function Foo () {
}
Foo.prototype.bar = true;
var foo = new Foo();
foo.bar; // true
foo instanceof Foo; // true
Foo.prototype.isPrototypeOf(foo); // true
If this happens sporadically then my guess is that it has something to do with the timer.
I'm guessing (and this is only a guess since I have no access to your code) that the timer is firing while the form is being closed. The dbiSchedule object has been disposed but the timer somehow still manages to try to call it. This shouldn't happen, because if the timer has a reference to the schedule object then the garbage collector should see this and not dispose of it.
This leads me to ask: are you calling Dispose() on the schedule object manually? If so, are you doing that before disposing of the timer? Be sure that you release all references to the schedule object before Disposing it (i.e. dispose of the timer beforehand).
Now I realize that a few months have passed between the time you posted this and when I am answering, so hopefully, you have resolved this issue. I'm writing this for the benefit of others who may come along later with a similar issue.
Hope this helps.
Another alternative: use {}
inside quotation marks to easily create dynamic names. This is similar to other solutions but not exactly the same, and I find it easier.
library(dplyr)
library(tibble)
iris <- as_tibble(iris)
multipetal <- function(df, n) {
df <- mutate(df, "petal.{n}" := Petal.Width * n) ## problem arises here
df
}
for(i in 2:5) {
iris <- multipetal(df=iris, n=i)
}
iris
I think this comes from dplyr 1.0.0
but not sure (I also have rlang 4.7.0
if it matters).
If you have a single Buffer
you can use its toString
method that will convert all or part of the binary contents to a string using a specific encoding. It defaults to utf8
if you don't provide a parameter, but I've explicitly set the encoding in this example.
var req = http.request(reqOptions, function(res) {
...
res.on('data', function(chunk) {
var textChunk = chunk.toString('utf8');
// process utf8 text chunk
});
});
If you have streamed buffers like in the question above where the first byte of a multi-byte UTF8
-character may be contained in the first Buffer
(chunk) and the second byte in the second Buffer
then you should use a StringDecoder
. :
var StringDecoder = require('string_decoder').StringDecoder;
var req = http.request(reqOptions, function(res) {
...
var decoder = new StringDecoder('utf8');
res.on('data', function(chunk) {
var textChunk = decoder.write(chunk);
// process utf8 text chunk
});
});
This way bytes of incomplete characters are buffered by the StringDecoder
until all required bytes were written to the decoder.
docker rm $(docker ps -a | awk '/myimage:mytag/{print $1}')
@Column
AnnotationThe nullable
attribute of the @Column
annotation has two purposes:
The HBM2DDL schema generation tool translates the @Column(nullable = false)
entity attribute to a NOT NULL
constraint for the associated table column when generating the CREATE TABLE
statement.
As I explained in the Hibernate User Guide, it's better to use a tool like Flyway instead of relying on the HBM2DDL mechanism for generating the database schema.
When flushing the Persistence Context, Hibernate ORM also uses the @Column(nullable = false)
entity attribute:
new Nullability( session ).checkNullability( values, persister, true );
If the validation fails, Hibernate will throw a PropertyValueException
, and prevents the INSERT or UPDATE statement to be executed needesly:
if ( !nullability[i] && value == null ) {
//check basic level one nullablilty
throw new PropertyValueException(
"not-null property references a null or transient value",
persister.getEntityName(),
persister.getPropertyNames()[i]
);
}
@NotNull
AnnotationThe @NotNull
annotation is defined by Bean Validation and, just like Hibernate ORM is the most popular JPA implementation, the most popular Bean Validation implementation is the Hibernate Validator framework.
When using Hibernate Validator along with Hibernate ORM, Hibernate Validator will throw a ConstraintViolation
when validating the entity.
After changing app.php, make sure you run:
php artisan config:clear
This is needed to clear the cache of config settings. If you notice that your timestamps are still wrong after changing the timezone in your app.php file, then running the above command should refresh everything, and your new timezone should be effective.
Since question was regarding clunkiness of property checking, and one regular usecase for that being validation of function argument options objects, thought I'd mention a library-free short way of testing existence of multiple properties. Disclaimer: It does require ECMAScript 5 (but IMO anyone still using IE8 deserves a broken web).
function f(opts) {
if(!["req1","req2"].every(opts.hasOwnProperty, opts)) {
throw new Error("IllegalArgumentException");
}
alert("ok");
}
f({req1: 123}); // error
f({req1: 123, req2: 456}); // ok
for block elements:
<textarea style="width:100px; word-wrap:break-word;">_x000D_
ACTGATCGAGCTGAAGCGCAGTGCGATGCTTCGATGATGCTGACGATGCTACGATGCGAGCATCTACGATCAGTC_x000D_
</textarea>
_x000D_
for inline elements:
<span style="width:100px; word-wrap:break-word; display:inline-block;"> _x000D_
ACTGATCGAGCTGAAGCGCAGTGCGATGCTTCGATGATGCTGACGATGCTACGATGCGAGCATCTACGATCAGTC_x000D_
</span>
_x000D_
Complete code of passing data using fragment to fragment
Fragment fragment = new Fragment(); // replace your custom fragment class
Bundle bundle = new Bundle();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
bundle.putString("key","value"); // use as per your need
fragment.setArguments(bundle);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(viewID,fragment);
fragmentTransaction.commit();
In custom fragment class
Bundle mBundle = new Bundle();
mBundle = getArguments();
mBundle.getString(key); // key must be same which was given in first fragment
<?php
// Turn off error reporting
error_reporting(0);
// Report runtime errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
// Report all errors
error_reporting(E_ALL);
// Same as error_reporting(E_ALL);
ini_set("error_reporting", E_ALL);
// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
?>
While your site is live, the php.ini
file should have display_errors disabled for security reasons. However, for the development environment, display_errors can be enabled for troubleshooting.
You should use promises for async operations where you don't know when it will be completed. A promise "represents an operation that hasn't completed yet, but is expected in the future." (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise)
An example implementation would be like:
myApp.factory('myService', function($http) {
var getData = function() {
// Angular $http() and then() both return promises themselves
return $http({method:"GET", url:"/my/url"}).then(function(result){
// What we return here is the data that will be accessible
// to us after the promise resolves
return result.data;
});
};
return { getData: getData };
});
function myFunction($scope, myService) {
var myDataPromise = myService.getData();
myDataPromise.then(function(result) {
// this is only run after getData() resolves
$scope.data = result;
console.log("data.name"+$scope.data.name);
});
}
Edit: Regarding Sujoys comment that What do I need to do so that myFuction() call won't return till .then() function finishes execution.
function myFunction($scope, myService) {
var myDataPromise = myService.getData();
myDataPromise.then(function(result) {
$scope.data = result;
console.log("data.name"+$scope.data.name);
});
console.log("This will get printed before data.name inside then. And I don't want that.");
}
Well, let's suppose the call to getData() took 10 seconds to complete. If the function didn't return anything in that time, it would effectively become normal synchronous code and would hang the browser until it completed.
With the promise returning instantly though, the browser is free to continue on with other code in the meantime. Once the promise resolves/fails, the then() call is triggered. So it makes much more sense this way, even if it might make the flow of your code a bit more complex (complexity is a common problem of async/parallel programming in general after all!)
You can use an Extention:
public static void CopyOnlyEqualProperties<T>(this T objDest, object objSource) where T : class
{
foreach (PropertyInfo propInfo in typeof(T).GetProperties())
if (objSource.GetType().GetProperties().Any(z => z.Name == propInfo.Name && z.GetType() == propInfo.GetType()))
propInfo.SetValue(objDest, objSource.GetType().GetProperties().First(z => z.Name == propInfo.Name && z.GetType() == propInfo.GetType()).GetValue(objSource));
}
In Code:
public class BaseClass
{
public string test{ get; set;}
}
public Derived : BaseClass
{
//Some properies
}
public void CopyProps()
{
BaseClass baseCl =new BaseClass();
baseCl.test="Hello";
Derived drv=new Derived();
drv.CopyOnlyEqualProperties(baseCl);
//Should return Hello to the console now in derived class.
Console.WriteLine(drv.test);
}
I’ve created a new SOAP client for the Android platform, it is use a JAX-WS generated interfaces, but it is only a proof-of-concept yet.
If you are interested, please try the example and/or watch the source: http://wiki.javaforum.hu/display/ANDROIDSOAP/Home
Update: the version 0.0.4 is out with tutorial:
http://wiki.javaforum.hu/display/ANDROIDSOAP/2012/04/16/Version+0.0.4+released
http://wiki.javaforum.hu/display/ANDROIDSOAP/Step+by+step+tutorial
With jQuery 1.6, this seems to be a more elegant solution:
$('#element-of-interest').prop('outerHTML');
Worked on Spark V2.*
import sqlContext.implicits._
df.filter($"state" === "TX")
if needs to be compared against a variable (e.g., var):
import sqlContext.implicits._
df.filter($"state" === var)
Note :
import sqlContext.implicits._
What you want to do is a combination of part of 1 and all of 2.
You need to use the PowerMockito.mockStatic to enable static mocking for all static methods of a class. This means make it possible to stub them using the when-thenReturn syntax.
But the 2-argument overload of mockStatic you are using supplies a default strategy for what Mockito/PowerMock should do when you call a method you haven't explicitly stubbed on the mock instance.
From the javadoc:
Creates class mock with a specified strategy for its answers to interactions. It's quite advanced feature and typically you don't need it to write decent tests. However it can be helpful when working with legacy systems. It is the default answer so it will be used only when you don't stub the method call.
The default default stubbing strategy is to just return null, 0 or false for object, number and boolean valued methods. By using the 2-arg overload, you're saying "No, no, no, by default use this Answer subclass' answer method to get a default value. It returns a Long, so if you have static methods which return something incompatible with Long, there is a problem.
Instead, use the 1-arg version of mockStatic to enable stubbing of static methods, then use when-thenReturn to specify what to do for a particular method. For example:
import static org.mockito.Mockito.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
class ClassWithStatics {
public static String getString() {
return "String";
}
public static int getInt() {
return 1;
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStatics.class)
public class StubJustOneStatic {
@Test
public void test() {
PowerMockito.mockStatic(ClassWithStatics.class);
when(ClassWithStatics.getString()).thenReturn("Hello!");
System.out.println("String: " + ClassWithStatics.getString());
System.out.println("Int: " + ClassWithStatics.getInt());
}
}
The String-valued static method is stubbed to return "Hello!", while the int-valued static method uses the default stubbing, returning 0.
If you guys are facing "Permission Denial: starting Intent..." error or if the app is getting crash without any reason during launching the app - Then use this single line code in Manifest
android:exported="true"
Please be careful with finish(); , if you missed out it the app getting frozen. if its mentioned the app would be a smooth launcher.
finish();
The other solution only works for two activities that are in the same application. In my case, application B doesn't know class com.example.MyExampleActivity.class
in the code, so compile will fail.
I searched on the web and found something like this below, and it works well.
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.example", "com.example.MyExampleActivity"));
startActivity(intent);
You can also use the setClassName method:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("com.hotfoot.rapid.adani.wheeler.android", "com.hotfoot.rapid.adani.wheeler.android.view.activities.MainActivity");
startActivity(intent);
finish();
You can also pass the values from one app to another app :
Intent launchIntent = getApplicationContext().getPackageManager().getLaunchIntentForPackage("com.hotfoot.rapid.adani.wheeler.android.LoginActivity");
if (launchIntent != null) {
launchIntent.putExtra("AppID", "MY-CHILD-APP1");
launchIntent.putExtra("UserID", "MY-APP");
launchIntent.putExtra("Password", "MY-PASSWORD");
startActivity(launchIntent);
finish();
} else {
Toast.makeText(getApplicationContext(), " launch Intent not available", Toast.LENGTH_SHORT).show();
}
This worked for me:
COPY (SELECT * FROM table)
TO E'C:\\Program Files (x86)\\PostgreSQL\\8.4\\data\\try.csv';
In my case the problem was with the writing permission to a special folder (though I work as administrator), after changing the path to the original data folder under PostgreSQL I had success.
You maybe wanted to do the following:
foreach($user->data as $mydata)
{
echo $mydata->name . "\n";
foreach($mydata->values as $values)
{
echo $values->value . "\n";
}
}
Well if you know the basics behind them, it shouldn't be too hard.
Generally you create an array called "buckets" that contain the key and value, with an optional pointer to create a linked list.
When you access the hash table with a key, you process the key with a custom hash function which will return an integer. You then take the modulus of the result and that is the location of your array index or "bucket". Then you check the unhashed key with the stored key, and if it matches, then you found the right place.
Otherwise, you've had a "collision" and must crawl through the linked list and compare keys until you match. (note some implementations use a binary tree instead of linked list for collisions).
Check out this fast hash table implementation:
For select twitter meta name , you can add a data attribute.
example :
meta name="twitter:card" data-twitterCard="" content=""
$('[data-twitterCard]').attr('content');
Programatically, you may want to publish the application launcher yourself :
Note: this method no longer works starting with Android 8.0 - Oreo
In your AndroidManifest.xml, add :
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>
Then you need create your app launcher intent:
Intent myLauncherIntent = new Intent();
myLauncherIntent.setClassName("your.package.name", "YourLauncherActivityName");
myLauncherIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Create an install shortcut intent with your app launcher and custom icon:
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, myLauncherIntent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "Application Name");
intent.putExtra
(
Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
Intent.ShortcutIconResource.fromContext
(
getApplicationContext(),
R.drawable.app_icon
)
);
intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
And finally launch the broadcast intent:
getApplicationContext().sendBroadcast(intent);
If you are using chart.js in an Angular project with Typescript, the you can try the following;
Import the library:
import { Chart } from 'chart.js';
In your Component Class declare the variable and define a method:
chart: Chart;
drawGraph(): void {
if (this.chart) {
this.chart.destroy();
}
this.chart = new Chart('myChart', {
.........
});
}
In HTML Template:
<canvas id="myChart"></canvas>
Use Dictionary - it uses hashtable but is typesafe.
Also, your Java code for
int a = map.get(key);
//continue with your logic
will be best coded in C# this way:
int a;
if(dict.TryGetValue(key, out a)){
//continue with your logic
}
This way, you can scope the need of variable "a" inside a block and it is still accessible outside the block if you need it later.
Since java-9
there is a standard way of checking if an index belongs to the array - Objects#checkIndex() :
List<Integer> ints = List.of(1,2,3);
System.out.println(Objects.checkIndex(1,ints.size())); // 1
System.out.println(Objects.checkIndex(10,ints.size())); //IndexOutOfBoundsException
You can't use Microsoft.Office.Interop.Excel without having ms office installed.
Just search in google for some libraries, which allows to modify xls or xlsx:
For one, @JsonProperty("status")
and @JsonProperty("msg")
should only be there only when declaring the fields, not on the setters and geters.
In fact, the simplest way to parse this would be
@JsonAutoDetect //if you don't want to have getters and setters for each JsonProperty
public class StatusResponses {
@JsonProperty("status")
private String status;
@JsonProperty("msg")
private String message;
}
First thing first. set the column in which you are working in by clicking on format cells->number-> date and then format e.g Jan-16 representing Jan, 1, 2016. and then apply either of the formulas above.
If you have declare a bitmap object and you want to display it or store this bitmap object. but first you have to assign any image , and you may use the button click event, this code will only demonstrate that how to store the drawable image in bitmap Object.
Bitmap contact_pic = BitmapFactory.decodeResource(
v.getContext().getResources(),
R.drawable.android_logo
);
Now you can use this bitmap object, whether you want to store it, or to use it in google maps while drawing a pic on fixed latitude and longitude, or to use some where else
we removed a lib folder from the website folder. this was created by a previous installation of typings. this became duplicate. When this was removed it worked!
For those like I who just followed the code by skuntsel and received a cryptic stack trace, allow me to save you some time.
It seems c:if
cannot by itself be followed by c:otherwise
.
The correct solution is as follows:
<c:choose>
<c:when test="#{some.test}">
<p>some.test is true</p>
</c:when>
<c:otherwise>
<p>some.test is not true</p>
</c:otherwise>
</c:choose>
You can add additional c:when
tests in as necessary.
You just declare the property the normal way using a generic type:
public MyType<string> PropertyName { get; set; }
If you want to call predefined methods to do something in the get or set, implement the property getter/setter to call those methods.
Thanks Anda, your post has been a great help!! However the OR sentence didnt' quite work for me and I was getting an error: getCollection() "invalid argument supplied for foreach".
So this is what I ended with (notice the attribute being specified 3 times instead of 2 in this case):
$collection->addFieldToFilter('attribute', array(
array('attribute'=>'my_field1','eq'=>'my_value1'),
array('attribute'=>'my_field2','eq'=>'my_value2') ));
addFieldToFilter first requires a field and then condition -> link.
there are three ways you can use: the RETURN value, and OUTPUT parameter and a result set
ALSO, watch out if you use the pattern: SELECT @Variable=column FROM table ...
if there are multiple rows returned from the query, your @Variable will only contain the value from the last row returned by the query.
RETURN VALUE
since your query returns an int field, at least based on how you named it. you can use this trick:
CREATE PROCEDURE GetMyInt
( @Param int)
AS
DECLARE @ReturnValue int
SELECT @ReturnValue=MyIntField FROM MyTable WHERE MyPrimaryKeyField = @Param
RETURN @ReturnValue
GO
and now call your procedure like:
DECLARE @SelectedValue int
,@Param int
SET @Param=1
EXEC @SelectedValue = GetMyInt @Param
PRINT @SelectedValue
this will only work for INTs, because RETURN can only return a single int value and nulls are converted to a zero.
OUTPUT PARAMETER
you can use an output parameter:
CREATE PROCEDURE GetMyInt
( @Param int
,@OutValue int OUTPUT)
AS
SELECT @OutValue=MyIntField FROM MyTable WHERE MyPrimaryKeyField = @Param
RETURN 0
GO
and now call your procedure like:
DECLARE @SelectedValue int
,@Param int
SET @Param=1
EXEC GetMyInt @Param, @SelectedValue OUTPUT
PRINT @SelectedValue
Output parameters can only return one value, but can be any data type
RESULT SET for a result set make the procedure like:
CREATE PROCEDURE GetMyInt
( @Param int)
AS
SELECT MyIntField FROM MyTable WHERE MyPrimaryKeyField = @Param
RETURN 0
GO
use it like:
DECLARE @ResultSet table (SelectedValue int)
DECLARE @Param int
SET @Param=1
INSERT INTO @ResultSet (SelectedValue)
EXEC GetMyInt @Param
SELECT * FROM @ResultSet
result sets can have many rows and many columns of any data type
In the question:
who | grep $(tty | sed s:/dev/::)
outputs errors claiming that files a and tty do not exist. I understood this to mean that tty is not being interpreted before execution of grep, but instead that bash passed tty as a parameter to grep, which interpreted it as a file name.
There is also a situation of nested redirection, which should be handled by matched parentheses which should specify a child process, but bash is primitively a word separator, creating parameters to be sent to a program, therefore parentheses are not matched first, but interpreted as seen.
I got specific with grep, and specified the file as a parameter instead of using a pipe. I also simplified the base command, passing output from a command as a file, so that i/o piping would not be nested:
grep $(tty | sed s:/dev/::) <(who)
works well.
who | grep $(echo pts/3)
is not really desired, but eliminates the nested pipe and also works well.
In conclusion, bash does not seem to like nested pipping. It is important to understand that bash is not a new-wave program written in a recursive manner. Instead, bash is an old 1,2,3 program, which has been appended with features. For purposes of assuring backward compatibility, the initial manner of interpretation has never been modified. If bash was rewritten to first match parentheses, how many bugs would be introduced into how many bash programs? Many programmers love to be cryptic.
This is an extension to what @pellucide has done, but for Macs:
To determine the number of seconds since epoch (Jan 1 1970) for any given date (e.g. Oct 21 1973)
$ date -j -f "%b %d %Y %T" "Oct 21 1973 00:00:00" "+%s"
120034800
Please note, that for completeness, I have added the time part to the format. The reason being is that date
will take whatever date part you gave it and add the current time to the value provided. For example, if you execute the above command at 4:19PM, without the '00:00:00' part, it will add the time automatically. Such that "Oct 21 1973" will be parsed as "Oct 21 1973 16:19:00". That may not be what you want.
To convert your timestamp back to a date:
$ date -j -r 120034800
Sun Oct 21 00:00:00 PDT 1973
Apple's man page for the date implementation: https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/date.1.html
On Linux, I had the same problem of getting rid of the buffering. I finally used "stdbuf -o0" (or, unbuffer from expect) to get rid of the PIPE buffering.
proc = Popen(['stdbuf', '-o0'] + cmd, stdout=PIPE, stderr=PIPE)
stdout = proc.stdout
I could then use select.select on stdout.
Removing Matrix columns that contain NaN. This is a lengthy answer, but hopefully easy to follow.
def column_to_vector(matrix, i):
return [row[i] for row in matrix]
import numpy
def remove_NaN_columns(matrix):
import scipy
import math
from numpy import column_stack, vstack
columns = A.shape[1]
#print("columns", columns)
result = []
skip_column = True
for column in range(0, columns):
vector = column_to_vector(A, column)
skip_column = False
for value in vector:
# print(column, vector, value, math.isnan(value) )
if math.isnan(value):
skip_column = True
if skip_column == False:
result.append(vector)
return column_stack(result)
### test it
A = vstack(([ float('NaN'), 2., 3., float('NaN')], [ 1., 2., 3., 9]))
print("A shape", A.shape, "\n", A)
B = remove_NaN_columns(A)
print("B shape", B.shape, "\n", B)
A shape (2, 4)
[[ nan 2. 3. nan]
[ 1. 2. 3. 9.]]
B shape (2, 2)
[[ 2. 3.]
[ 2. 3.]]
I think, that maybe git can't totally forget about file because of its conception (section "Snapshots, Not Differences").
This problem is absent, for example, when using CVS. CVS stores information as a list of file-based changes. Information for CVS is a set of files and the changes made to each file over time.
But in Git every time you commit, or save the state of your project, it basically takes a picture of what all your files look like at that moment and stores a reference to that snapshot. So, if you added file once, it will always be present in that snapshot.
These 2 articles were helpful for me:
git assume-unchanged vs skip-worktree and How to ignore changes in tracked files with Git
Basing on it I do the following, if file is already tracked:
git update-index --skip-worktree <file>
From this moment all local changes in this file will be ignored and will not go to remote. If file is changed on remote, conflict will occure, when git pull
. Stash won't work. To resolve it, copy file content to the safe place and follow these steps:
git update-index --no-skip-worktree <file>
git stash
git pull
File content will be replaced by the remote content. Paste your changes from safe place to file and perform again:
git update-index --skip-worktree <file>
If everyone, who works with project, will perform git update-index --skip-worktree <file>
, problems with pull
should be absent. This solution is OK for configurations files, when every developer has their own project configuration.
It is not very convenient to do this every time, when file has been changed on remote, but can protect it from overwriting by remote content.
You can force Modal to refresh the popup by adding this line at the end of the hide method of the Modal plugin (If you are using bootstrap-transition.js v2.1.1, it should be at line 836)
this.$element.removeData()
Or with an event listener
$('#modal').on('hidden', function() {
$(this).data('modal').$element.removeData();
})
If you happen to be using the Ruby gem redcarpet to render Markdown, you may still have this problem.
You can escape the numbering, and redcarpet will happily ignore any special meaning:
1\. Some heading
text text
text text
text text
2\. Some other heading
blah blah
more blah blah
It works for me by using require syntax like this:
$('.eventSlick').slick({
dots: true,
slidesToShow: 3,
slidesToScroll: 1,
autoplay: false,
autoplaySpeed: 2000,
arrows: true,
draggable: false,
prevArrow: '<button type="button" data-role="none" class="slick-prev"><img src="' + require("@/assets/img/icon/Arrow_Left.svg")+'"></button>',
Some time this happens when your Java folder get updated.
Open Eclipse folder and search file eclipse.ini. Open the eclipse.ini file and check whether jre version is same as jre available in your java folder.
I faced same problem when my jre got changed from jre1.8.0_101 to jre1.8.0_111.
C:\Program Files\Java\jre1.8.0_101\bin to C:\Program Files\Java\jre1.8.0_111\bin
The only reasons I can think of are actually in the wiki article you referenced to mention a couple...
"The "Verified by Visa" system has drawn some criticism, since it is hard for users to differentiate between the legitimate Verified by Visa pop-up window or inline frame, and a fraudulent phishing site."
"as of 2008, most web browsers do not provide a simple way to check the security certificate for the contents of an iframe"
If you read the Criticism section in the article it details all the potential security flaws.
Otherwise the only difference is the fact that an IFrame is an inline frame and a Frame is part of a Frameset. Which means more layout problems than anything else!
I think all solutions will fail if the length of the replacing string is different from the length of the string to be replaced. (search for "abc" and replace by "xxxxxx") A general approach might be:
void replaceAll( string &s, const string &search, const string &replace ) {
for( size_t pos = 0; ; pos += replace.length() ) {
// Locate the substring to replace
pos = s.find( search, pos );
if( pos == string::npos ) break;
// Replace by erasing and inserting
s.erase( pos, search.length() );
s.insert( pos, replace );
}
}
Had the same problem where I specified data
but the browser was sending requests to URL ending with [Object object]
.
You should have processData
set to true
.
processData: true, // You should comment this out if is false or set to true
return ((parseInt(str, 10).toString() == str) && str.indexOf('-') === -1);
won't work if you give a string like '0001' though
listOfStuff =([a,b], [c,d], [e,f], [f,g])
for item in listOfStuff[1:3]:
print item
You have to iterate over a slice of your tuple. The 1
is the first element you need and 3
(actually 2+1) is the first element you don't need.
Elements in a list are numerated from 0:
listOfStuff =([a,b], [c,d], [e,f], [f,g])
0 1 2 3
[1:3]
takes elements 1 and 2.
I also had the same issue when trying to fetch the data from "/src" folder. Moving the file into the "/public" solved the problem from.
Way 1: only works for dataURL, not for other types of url.
function dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type:mime});
}
//Usage example:
var file = dataURLtoFile('data:image/png;base64,......', 'a.png');
console.log(file);
Way 2: works for any type of url, (http url, dataURL, blobURL, etc...)
//return a promise that resolves with a File instance
function urltoFile(url, filename, mimeType){
mimeType = mimeType || (url.match(/^data:([^;]+);/)||'')[1];
return (fetch(url)
.then(function(res){return res.arrayBuffer();})
.then(function(buf){return new File([buf], filename, {type:mimeType});})
);
}
//Usage example:
urltoFile('data:image/png;base64,......', 'a.png')
.then(function(file){
console.log(file);
})
Both works in Chrome and Firefox.
I think this may be useful for those who would like attribute's value to be a function:
import { RNCamera } from 'react-native-camera';
[...]
export default class MyView extends React.Component {
_myFunction = (myObject) => {
console.log(myObject.type); //
}
render() {
var scannerProps = Platform.OS === 'ios' ?
{
onBarCodeRead : this._myFunction
}
:
{
// here you can add attribute(s) for other platforms
}
return (
// it is just a part of code for MyView's layout
<RNCamera
ref={ref => { this.camera = ref; }}
style={{ flex: 1, justifyContent: 'flex-end', alignItems: 'center', }}
type={RNCamera.Constants.Type.back}
flashMode={RNCamera.Constants.FlashMode.on}
{...scannerProps}
/>
);
}
}
I'm not sure what you just did there, but from what I can tell this is what you're asking for:
bookingfacilities.php
<form action="successfulbooking.php" method="post">
<input type="hidden" name="date" value="<?php echo $date; ?>">
<input type="submit" value="Submit Form">
</form>
successfulbooking.php
<?php
$date = $_POST['date'];
// add code here
?>
Not sure what you want to do with that third page(booking_now.php) too.
If you don't need a human-readable output, another option you could try is to save the array as a MATLAB .mat
file, which is a structured array. I despise MATLAB, but the fact that I can both read and write a .mat
in very few lines is convenient.
Unlike Joe Kington's answer, the benefit of this is that you don't need to know the original shape of the data in the .mat
file, i.e. no need to reshape upon reading in. And, unlike using pickle
, a .mat
file can be read by MATLAB, and probably some other programs/languages as well.
Here is an example:
import numpy as np
import scipy.io
# Some test data
x = np.arange(200).reshape((4,5,10))
# Specify the filename of the .mat file
matfile = 'test_mat.mat'
# Write the array to the mat file. For this to work, the array must be the value
# corresponding to a key name of your choice in a dictionary
scipy.io.savemat(matfile, mdict={'out': x}, oned_as='row')
# For the above line, I specified the kwarg oned_as since python (2.7 with
# numpy 1.6.1) throws a FutureWarning. Here, this isn't really necessary
# since oned_as is a kwarg for dealing with 1-D arrays.
# Now load in the data from the .mat that was just saved
matdata = scipy.io.loadmat(matfile)
# And just to check if the data is the same:
assert np.all(x == matdata['out'])
If you forget the key that the array is named in the .mat
file, you can always do:
print matdata.keys()
And of course you can store many arrays using many more keys.
So yes – it won't be readable with your eyes, but only takes 2 lines to write and read the data, which I think is a fair trade-off.
Take a look at the docs for scipy.io.savemat and scipy.io.loadmat and also this tutorial page: scipy.io File IO Tutorial
If you want to do this and control the server from which the base page or content is being served, you can use Cross Origin Resource Sharing (http://www.w3.org/TR/access-control/) to allow client-side JavaScript to load data into a <div>
via XMLHttpRequest()
:
// I safely ignore IE 6 and 5 (!) users
// because I do not wish to proliferate
// broken software that will hurt other
// users of the internet, which is what
// you're doing when you write anything
// for old version of IE (5/6)
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
document.getElementById('displayDiv').innerHTML = xhr.responseText;
}
};
xhr.open('GET', 'http://api.google.com/thing?request=data', true);
xhr.send();
Now for the lynchpin of this whole operation, you need to write code for your server that will give clients the Access-Control-Allow-Origin
header, specifying which domains you want the client-side code to be able to access via XMLHttpRequest()
. The following is an example of PHP code you can include at the top of your page in order to send these headers to clients:
<?php
header('Access-Control-Allow-Origin: http://api.google.com');
header('Access-Control-Allow-Origin: http://some.example.com');
?>
Try ro use this like libs:
https://www.npmjs.com/package/promise-chain-break
db.getData()
.then(pb((data) => {
if (!data.someCheck()) {
tellSomeone();
// All other '.then' calls will be skiped
return pb.BREAK;
}
}))
.then(pb(() => {
}))
.then(pb(() => {
}))
.catch((error) => {
console.error(error);
});
Like you tube.. initially they show icon screen instead of white screen. And after 2 seconds shows home screen.
first create an XML drawable in res/drawable.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:drawable="@color/gray"/>
<item>
<bitmap
android:gravity="center"
android:src="@mipmap/ic_launcher"/>
</item>
</layer-list>
Next, you will set this as your splash activity’s background in the theme. Navigate to your styles.xml file and add a new theme for your splash activity
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
</style>
<style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
<item name="android:windowBackground">@drawable/background_splash</item>
</style>
</resources>
In your new SplashTheme, set the window background attribute to your XML drawable. Configure this as your splash activity’s theme in your AndroidManifest.xml:
<activity
android:name=".SplashActivity"
android:theme="@style/SplashTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
This link gives what you want. step by step procedure. https://www.bignerdranch.com/blog/splash-screens-the-right-way/
UPDATE:
The layer-list
can be even simpler like this (which also accepts vector drawables for the centered logo, unlike the <bitmap>
tag):
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Background color -->
<item android:drawable="@color/gray"/>
<!-- Logo at the center of the screen -->
<item
android:drawable="@mipmap/ic_launcher"
android:gravity="center"/>
</layer-list>
As of NuGet 2.8, there is a feature to downgrade a package.
Example:
The following command entered into the Package Manager Console will downgrade the Couchbase client to version 1.3.1.0.
Update-Package CouchbaseNetClient -Version 1.3.1.0
Result:
Updating 'CouchbaseNetClient' from version '1.3.3' to '1.3.1.0' in project [project name].
Removing 'CouchbaseNetClient 1.3.3' from [project name].
Successfully removed 'CouchbaseNetClient 1.3.3' from [project name].
Something to note as per crimbo below:
This approach doesn't work for downgrading from one prerelease version to other prerelease version - it only works for downgrading to a release version
Use []
:
cookie_value_add.push([productID,itemColorTitle, itemColorPath]);
or
arrayToPush.push([value1, value2, ..., valueN]);
For normal select option
<script>
$(document).ready(function() {
$("#id").val('select value here');
});
</script>
For select 2 option trigger option need to use
<script>
$(document).ready(function() {
$("#id").val('select value here').trigger('change');
});
</script>
The following will check whether an IP is valid or not: If the IP is within 0.0.0.0 to 255.255.255.255, then the output will be true, otherwise it will be false:
[0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4
Example:
your_ip = "10.10.10.10"
[0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4
Output:
>>> your_ip = "10.10.10.10"
>>> [0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4
True
>>> your_ip = "10.10.10.256"
>>> [0<=int(x)<256 for x in re.split('\.',re.match(r'^\d+\.\d+\.\d+\.\d+$',your_ip).group(0))].count(True)==4
False
>>>
This isn't sufficient: the object returned by __iter__
must implement the iteration protocol (i.e. next
method). See the relevant section in the documentation.
In Python, a good practice is to "try and see" instead of "checking".
Simple add below line into your MainActivity
and your App never turn lights off.
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
You should go through the titleLabel
property.
button.titleLabel.font
The font
property has been deprecated since iOS 3.0.
Here's what worked for me:
console.log(process.mainModule.filename);
Try the below:
pod deintegrate
pod install
Or, One-Liner:
pod deintegrate; pod install
This error occurred in my application with the CIP-protocol whenever I didn't Send or received data in less than 10s.
This was caused by the use of the forward open method. You can avoid this by working with an other method, or to install an update rate of less the 10s that maintain your forward-open-connection.
You can do as @rmobis has specified in his answer, [Adding something more into it]
Using order by
twice:
MyTable::orderBy('coloumn1', 'DESC')
->orderBy('coloumn2', 'ASC')
->get();
and the second way to do it is,
Using raw order by
:
MyTable::orderByRaw("coloumn1 DESC, coloumn2 ASC");
->get();
Both will produce same query as follow,
SELECT * FROM `my_tables` ORDER BY `coloumn1` DESC, `coloumn2` ASC
As @rmobis specified in comment of first answer you can pass like an array to order by column like this,
$myTable->orders = array(
array('column' => 'coloumn1', 'direction' => 'desc'),
array('column' => 'coloumn2', 'direction' => 'asc')
);
one more way to do it is iterate
in loop,
$query = DB::table('my_tables');
foreach ($request->get('order_by_columns') as $column => $direction) {
$query->orderBy($column, $direction);
}
$results = $query->get();
Hope it helps :)
explode
has some very big problems in real life usage:
count(explode(',', null)); // 1 !!
explode(',', null); // [""] not an empty array, but an array with one empty string!
explode(',', ""); // [""]
explode(',', "1,"); // ["1",""] ending commas are also unsupported, kinda like IE8
this is why i prefer preg_split
preg_split('@,@', $string, NULL, PREG_SPLIT_NO_EMPTY)
the entire boilerplate:
/** @brief wrapper for explode
* @param string|int|array $val string will explode. '' return []. int return string in array (1 returns ['1']). array return itself. for other types - see $as_is
* @param bool $as_is false (default): bool/null return []. true: bool/null return itself.
* @param string $delimiter default ','
* @return array|mixed
*/
public static function explode($val, $as_is = false, $delimiter = ',')
{
// using preg_split (instead of explode) because it is the best way to handle ending comma and avoid empty string converted to ['']
return (is_string($val) || is_int($val)) ?
preg_split('@' . preg_quote($delimiter, '@') . '@', $val, NULL, PREG_SPLIT_NO_EMPTY)
:
($as_is ? $val : (is_array($val) ? $val : []));
}
// MY_PREFS_NAME - a static String variable like:
//public static final String MY_PREFS_NAME = "MyPrefsFile";
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.apply();
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value.
More info:
I recognize that the answer works and has been accepted but there is a much cleaner way to write that query. Tested on mysql and postgres.
SELECT wpoi.order_id As No_Commande
FROM wp_woocommerce_order_items AS wpoi
LEFT JOIN wp_postmeta AS wpp ON wpoi.order_id = wpp.post_id
AND wpp.meta_key = '_shipping_first_name'
WHERE wpoi.order_id =2198
(I am using JupyterLab with Julia)
First thing is that Jupyter lab from my previous use offers more 'themes' which is great on the eyes, and also fontsize changes independent of the browser, so that makes it closer to that of an IDE. There are some specifics I like such as changing the 'code font size' and leaving the interface font size to be the same.
Major features that are great is
What is paramount though is the ability to have split views of the tabs and the terminal. If you use Emacs, then you probably enjoyed having multiple buffers with horizontal and vertical arrangements with one of them running a shell (terminal), and with jupyterlab this can be done, and the arrangement is made with drags and drops which in Emacs is typically done with sets of commands.
(I do not believe that there is a learning curve added to those that have not used the 'notebook' original version first. You can dive straight into this IDE experience)
I really liked Jake Taylor's idea of doing it without additional JavaScript and taking advantage of Bootstrap's collapse toggle. I found you can fix the "flickering" issue present when the menu isn't in collapsed mode by modifying the data-target
selector slightly to include the in
class. So it looks like this:
<li><a href="#Products" data-toggle="collapse" data-target=".navbar-collapse.in">Products</a></li>
I didn't test it with nested dropdowns/menus, so YMMV.
You must include jQuery in the project.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
I didn't find any doc about this so I just opened a random code example from tutorialrepublic.com http://www.tutorialrepublic.com/twitter-bootstrap-tutorial/bootstrap-dropdowns.php
Hope this helps someone else.
If you've got a Mac the easiest way to split those would be to use DfontSplitter, available at https://peter.upfold.org.uk/projects/dfontsplitter
The Windows version they provide doesn't work with ttc files.
It seems to have to do with context wrapping. Most classes derived from Context
are actually a ContextWrapper
, which essentially delegates to another context, possibly with changes by the wrapper.
The context is a general abstraction that supports mocking and proxying. Since many contexts are bound to a limited-lifetime object such as an Activity
, there needs to be a way to get a longer-lived context, for purposes such as registering for future notifications. That is achieved by Context.getApplicationContext()
. A logical implementation is to return the global Application
object, but nothing prevents a context implementation from returning a wrapper or proxy with a suitable lifetime instead.
Activities and services are more specifically associated with an Application
object. The usefulness of this, I believe, is that you can create and register in the manifest a custom class derived from Application
and be certain that Activity.getApplication()
or Service.getApplication()
will return that specific object of that specific type, which you can cast to your derived Application
class and use for whatever custom purpose.
In other words, getApplication()
is guaranteed to return an Application
object, while getApplicationContext()
is free to return a proxy instead.
In C++11, the using
keyword when used for type alias
is identical to typedef
.
7.1.3.2
A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name. It has the same semantics as if it were introduced by the typedef specifier. In particular, it does not define a new type and it shall not appear in the type-id.
Bjarne Stroustrup provides a practical example:
typedef void (*PFD)(double); // C style typedef to make `PFD` a pointer to a function returning void and accepting double
using PF = void (*)(double); // `using`-based equivalent of the typedef above
using P = [](double)->void; // using plus suffix return type, syntax error
using P = auto(double)->void // Fixed thanks to DyP
Pre-C++11, the using
keyword can bring member functions into scope. In C++11, you can now do this for constructors (another Bjarne Stroustrup example):
class Derived : public Base {
public:
using Base::f; // lift Base's f into Derived's scope -- works in C++98
void f(char); // provide a new f
void f(int); // prefer this f to Base::f(int)
using Base::Base; // lift Base constructors Derived's scope -- C++11 only
Derived(char); // provide a new constructor
Derived(int); // prefer this constructor to Base::Base(int)
// ...
};
Ben Voight provides a pretty good reason behind the rationale of not introducing a new keyword or new syntax. The standard wants to avoid breaking old code as much as possible. This is why in proposal documents you will see sections like Impact on the Standard
, Design decisions
, and how they might affect older code. There are situations when a proposal seems like a really good idea but might not have traction because it would be too difficult to implement, too confusing, or would contradict old code.
Here is an old paper from 2003 n1449. The rationale seems to be related to templates. Warning: there may be typos due to copying over from PDF.
First let’s consider a toy example:
template <typename T> class MyAlloc {/*...*/}; template <typename T, class A> class MyVector {/*...*/}; template <typename T> struct Vec { typedef MyVector<T, MyAlloc<T> > type; }; Vec<int>::type p; // sample usage
The fundamental problem with this idiom, and the main motivating fact for this proposal, is that the idiom causes the template parameters to appear in non-deducible context. That is, it will not be possible to call the function foo below without explicitly specifying template arguments.
template <typename T> void foo (Vec<T>::type&);
So, the syntax is somewhat ugly. We would rather avoid the nested
::type
We’d prefer something like the following:template <typename T> using Vec = MyVector<T, MyAlloc<T> >; //defined in section 2 below Vec<int> p; // sample usage
Note that we specifically avoid the term “typedef template” and introduce the new syntax involving the pair “using” and “=” to help avoid confusion: we are not defining any types here, we are introducing a synonym (i.e. alias) for an abstraction of a type-id (i.e. type expression) involving template parameters. If the template parameters are used in deducible contexts in the type expression then whenever the template alias is used to form a template-id, the values of the corresponding template parameters can be deduced – more on this will follow. In any case, it is now possible to write generic functions which operate on
Vec<T>
in deducible context, and the syntax is improved as well. For example we could rewrite foo as:template <typename T> void foo (Vec<T>&);
We underscore here that one of the primary reasons for proposing template aliases was so that argument deduction and the call to
foo(p)
will succeed.
The follow-up paper n1489 explains why using
instead of using typedef
:
It has been suggested to (re)use the keyword typedef — as done in the paper [4] — to introduce template aliases:
template<class T> typedef std::vector<T, MyAllocator<T> > Vec;
That notation has the advantage of using a keyword already known to introduce a type alias. However, it also displays several disavantages among which the confusion of using a keyword known to introduce an alias for a type-name in a context where the alias does not designate a type, but a template;
Vec
is not an alias for a type, and should not be taken for a typedef-name. The nameVec
is a name for the familystd::vector< [bullet] , MyAllocator< [bullet] > >
– where the bullet is a placeholder for a type-name. Consequently we do not propose the “typedef” syntax. On the other hand the sentencetemplate<class T> using Vec = std::vector<T, MyAllocator<T> >;
can be read/interpreted as: from now on, I’ll be using
Vec<T>
as a synonym forstd::vector<T, MyAllocator<T> >
. With that reading, the new syntax for aliasing seems reasonably logical.
I think the important distinction is made here, aliases instead of types. Another quote from the same document:
An alias-declaration is a declaration, and not a definition. An alias- declaration introduces a name into a declarative region as an alias for the type designated by the right-hand-side of the declaration. The core of this proposal concerns itself with type name aliases, but the notation can obviously be generalized to provide alternate spellings of namespace-aliasing or naming set of overloaded functions (see ? 2.3 for further discussion). [My note: That section discusses what that syntax can look like and reasons why it isn't part of the proposal.] It may be noted that the grammar production alias-declaration is acceptable anywhere a typedef declaration or a namespace-alias-definition is acceptable.
Summary, for the role of using
:
namespace PO = boost::program_options
and using PO = ...
equivalent)A typedef declaration can be viewed as a special case of non-template alias-declaration
. It's an aesthetic change, and is considered identical in this case.namespace std
into the global scope), member functions, inheriting constructorsIt cannot be used for:
int i;
using r = i; // compile-error
Instead do:
using r = decltype(i);
Naming a set of overloads.
// bring cos into scope
using std::cos;
// invalid syntax
using std::cos(double);
// not allowed, instead use Bjarne Stroustrup function pointer alias example
using test = std::cos(double);
or try NSString *string = [NSString stringWithFormat:@"%d", [NSNumber intValue], nil];
To set a default value to a column, try this:
ALTER TABLE tb_TableName
ALTER COLUMN Record_Status SET DEFAULT 'default value'
Late reply for future reference. What was working for me was enabling it by nuget and then adding custom headers into web.config.
If the XAMPP server
is running for the moment, stop XAMPP server.
Follow these steps to change the port number.
Open the file in following location.
[XAMPP Installation Folder]/apache/conf/httpd.conf
Open the httpd.conf
file and search for the String:
Listen 80
This is the port number used by XAMMP.
Then search for the string ServerName and update the Port Number which you entered earlier for Listen
Now save and re-start XAMPP server.
Here's the calling order:
app.config()
app.run()
app.controller()
Here's a simple demo where you can watch each one executing (and experiment if you'd like).
From Angular's module docs:
Run blocks - get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time.
Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the services have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.
One situation where run blocks are used is during authentications.
how random count in :
count, one := big.NewInt(0), big.NewInt(1)
count.SetString("100000000000000000000000", 10)
This a very simple recursive approach.
double mySqrt(double v, double test) {
if (abs(test * test - v) < 0.0001) {
return test;
}
double highOrLow = v / test;
return mySqrt(v, (test + highOrLow) / 2.0);
}
double mySqrt(double v) {
return mySqrt(v, v/2.0);
}
aws s3 ls s3://mybucket/ --recursive | wc -l
or
aws cloudwatch get-metric-statistics \
--namespace AWS/S3 --metric-name NumberOfObjects \
--dimensions Name=BucketName,Value=BUCKETNAME \
Name=StorageType,Value=AllStorageTypes \
--start-time 2016-11-05T00:00 --end-time 2016-11-05T00:10 \
--period 60 --statistic Average
Note: The above cloudwatch command seems to work for some while not for others. Discussed here: https://forums.aws.amazon.com/thread.jspa?threadID=217050
You can look at cloudwatch's metric section to get approx number of objects stored.
I have approx 50 Million products and it took more than an hour to count using aws s3 ls
As you are trying to add a string of CSS to <head>
with JavaScript?
injecting a string of CSS into a page it is easier to do this with the <link>
element than the <style>
element.
The following adds p { color: green; }
rule to the page.
<link rel="stylesheet" type="text/css" href="data:text/css;charset=UTF-8,p%20%7B%20color%3A%20green%3B%20%7D" />
You can create this in JavaScript simply by URL encoding your string of CSS and adding it the HREF
attribute. Much simpler than all the quirks of <style>
elements or directly accessing stylesheets.
var linkElement = this.document.createElement('link');
linkElement.setAttribute('rel', 'stylesheet');
linkElement.setAttribute('type', 'text/css');
linkElement.setAttribute('href', 'data:text/css;charset=UTF-8,' + encodeURIComponent(myStringOfstyles));
This will work in IE 5.5 upwards
The solution you have marked will work but this solution requires fewer dom operations and only a single element.
I've found that using a simple for loop, iterating over all elements in the string and comparing using charAt
performs faster than indexOf
or Regex
. The code and proof is available at JSPerf.
ETA: indexOf
and charAt
both perform similarly terrible on Chrome Mobile according to Browser Scope data listed on jsperf.com
Assuming a
is a string. The Slice notation in python has the syntax -
list[<start>:<stop>:<step>]
So, when you do a[::-1]
, it starts from the end towards the first taking each element. So it reverses a. This is applicable for lists/tuples as well.
Example -
>>> a = '1234'
>>> a[::-1]
'4321'
Then you convert it to int and then back to string (Though not sure why you do that) , that just gives you back the string.
Similar situation. It was working. Then, I started to include pytables. At first view, no reason to errors. I decided to use another function, that has a domain constraint (elipse) and received the following error:
TypeError: 'numpy.float64' object cannot be interpreted as an integer
or
TypeError: 'numpy.float64' object is not iterable
The crazy thing: the previous function I was using, no code changed, started to return the same error. My intermediary function, already used was:
def MinMax(x, mini=0, maxi=1)
return max(min(x,mini), maxi)
The solution was avoid numpy
or math
:
def MinMax(x, mini=0, maxi=1)
x = [x_aux if x_aux > mini else mini for x_aux in x]
x = [x_aux if x_aux < maxi else maxi for x_aux in x]
return max(min(x,mini), maxi)
Then, everything calm again. It was like one library possessed max
and min
!
I got the same error, on debian6, when I had not yet installed php5-mysql
.
So I installed it, then restarted apache2
apt-get install php5-mysql
/etc/init.d/apache2 restart
Then the error went away.
If you have the same error on Ubuntu, instead of:
/etc/init.d/apache2 restart
Type:
service apache2 restart
I make my own extended class to see what I need, so when I need into my controller or my View, I only add the using to my namespace something like this:
public static class UserExtended
{
public static string GetFullName(this IPrincipal user)
{
var claim = ((ClaimsIdentity)user.Identity).FindFirst(ClaimTypes.Name);
return claim == null ? null : claim.Value;
}
public static string GetAddress(this IPrincipal user)
{
var claim = ((ClaimsIdentity)user.Identity).FindFirst(ClaimTypes.StreetAddress);
return claim == null ? null : claim.Value;
}
public ....
{
.....
}
}
In my controller:
using XXX.CodeHelpers.Extended;
var claimAddress = User.GetAddress();
In my razor:
@using DinexWebSeller.CodeHelpers.Extended;
@User.GetFullName()
The reason of why your code throws an UnboundLocalError
is already well explained in other answers.
But it seems to me that you're trying to build something that works like itertools.count()
.
So why don't you try it out, and see if it suits your case:
>>> from itertools import count
>>> counter = count(0)
>>> counter
count(0)
>>> next(counter)
0
>>> counter
count(1)
>>> next(counter)
1
>>> counter
count(2)
No matter what state your repo is in you can always reset to any previous commit:
git reset --hard <commit hash>
This will discard all changes which were made after that commit.
If you are using a G Suite account, anything you try will fail. At least at the time, this answer is being typed. You must use @gmail.com
account, anything else like @example.com
will not work.
After you use the gmail.com
address. You just need to update .env
as most of the people already mentioned.
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=****@gmail.com
MAIL_PASSWORD=16digitapppassword
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=****@gmail.com
MAIL_FROM_NAME="${APP_NAME}"
Don't forget to create an App password, if you don't see the option probably your 2-factor authentication is not enabled. And there is no need to allow less secure apps if you follow this approach.
At some point I too tried to do this, but the Android Studio doesn’t work quite like Eclipse does.
It's simpler: if you create a project at, say /home/USER/Projects/AndroidStudio/MyApplication
from there on all new projects will default to /home/USER/Projects/AndroidStudio
.
You can also edit ~/.AndroidStudioPreview/config/options/ide.general.xml
(in linux) and change the line that reads <option name="lastProjectLocation" value="$USER_HOME$/AndroidStudioProjects" />
to <option name="lastProjectLocation" value="$USER_HOME$/Projects/AndroidStudio" />
, but be aware that as soon as you create a project anywhere else this will change to that place and all new projects will default to it.
Hope this helps, but the truth is there really isn't much more to it other than what I explained here.
Let me know if you need anything else.
This uses the above ideas but makes it a derived 'more sensitive' collection:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Collections;
namespace somethingelse
{
public class ObservableCollectionEx<T> : ObservableCollection<T> where T : INotifyPropertyChanged
{
// this collection also reacts to changes in its components' properties
public ObservableCollectionEx() : base()
{
this.CollectionChanged +=new System.Collections.Specialized.NotifyCollectionChangedEventHandler(ObservableCollectionEx_CollectionChanged);
}
void ObservableCollectionEx_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Remove)
{
foreach(T item in e.OldItems)
{
//Removed items
item.PropertyChanged -= EntityViewModelPropertyChanged;
}
}
else if (e.Action == NotifyCollectionChangedAction.Add)
{
foreach(T item in e.NewItems)
{
//Added items
item.PropertyChanged += EntityViewModelPropertyChanged;
}
}
}
public void EntityViewModelPropertyChanged(object sender, PropertyChangedEventArgs e)
{
//This will get called when the property of an object inside the collection changes - note you must make it a 'reset' - I don't know, why
NotifyCollectionChangedEventArgs args = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset);
OnCollectionChanged(args);
}
}
}
If you've installed 32-bit Office on a 64-bit machine, you may need to check for the presence of "SOFTWARE\Wow6432Node\Microsoft\Office\12.0\", substituting the 12.0 with the appropriate version. This is certainly the case for Office 2007 installed on 64-bit Windows 7.
Note that Office 2010 (== 14.0) is the first Office for which a 64-bit version exists.
A simple return
statement will 'stop' or return the function; in precise terms, it 'returns' function execution to the point at which the function was called - the function is terminated without further action.
That means you could have a number of places throughout your function where it might return. Like this:
def player():
# do something here
check_winner_variable = check_winner() # check something
if check_winner_variable == '1':
return
second_test_variable = second_test()
if second_test_variable == '1':
return
# let the computer do something
computer()
a simple function to create a second file reversed (linux only):
import os
def tac(file1, file2):
print(os.system('tac %s > %s' % (file1,file2)))
how to use
tac('ordered.csv', 'reversed.csv')
f = open('reversed.csv')
if (/(^|;)\s*visited=/.test(document.cookie)) {
alert("Hello again!");
} else {
document.cookie = "visited=true; max-age=" + 60 * 60 * 24 * 10; // 60 seconds to a minute, 60 minutes to an hour, 24 hours to a day, and 10 days.
alert("This is your first time!");
}
is one way to do it. Note that document.cookie
is a magic property, so you don't have to worry about overwriting anything, either.
There are also more convenient libraries to work with cookies, and if you don’t need the information you’re storing sent to the server on every request, HTML5’s localStorage
and friends are convenient and useful.
Went through this $h!†
again after updating to Catalina, which requires an XCode
update.
And to clarify, while this post is about VS Code
, this issue, is system wide. Your git
install is affected/hosed. You can try to run git
in your terminal/bash/zsh or whatever it is now and it just won't.
Same fix, just update XCode
, start it up and agree to license. That's it.
Old post, but just hit this on MAC/OSX
so hope this helps someone.
VS Code
for some time and have no issues with Git
XCode
(for whatever reason - OS update, etc)XCode
, VS Code
suddenly "can't find Git and asks you to either install or set the Path in settings"Run XCode
(for the first time, after installing) and agree to license. That's it.
How I stumbled upon this "fix":
After going through numerous tips about checking git
, e.g. which git
and git --version
, the latter actually offered clues with this Terminal message:
Agreeing to the Xcode/iOS license requires admin privileges, please run “sudo xcodebuild -license” and then retry this command.
As to why XCode
would even wrap it's hands on git
, WAT
Happy holidays and happy coding :)
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/', ['as' => 'home', 'uses' => 'BaseController@index']);
Route::group(['namespace' => 'User', 'prefix' => 'user'], function(){
Route::get('{nickname}/settings', ['as' => 'user.settings', 'uses' => 'SettingsController@index']);
Route::get('{nickname}/profile', ['as' => 'user.profile', 'uses' => 'ProfileController@index']);
});
});
For those of you using Centos (and perhaps other linux distibutions), you need to make sure that its FW (iptables) allows for port 80 or any other port you want.
See here on how to completely disable it (for testing purposes only!). And here for specific rules
I would do the following:
public class Book { private final String title; private final String isbn; public Book(final String t, final String i) { if(t == null) { throw new IllegalArgumentException("t cannot be null"); } if(i == null) { throw new IllegalArgumentException("i cannot be null"); } title = t; isbn = i; } }
I am making the assumption here that:
1) the title will never change (hence title is final) 2) the isbn will never change (hence isbn is final) 3) that it is not valid to have a book without both a title and an isbn.
Consider a Student class:
public class Student { private final StudentID id; private String firstName; private String lastName; public Student(final StudentID i, final String first, final String last) { if(i == null) { throw new IllegalArgumentException("i cannot be null"); } if(first == null) { throw new IllegalArgumentException("first cannot be null"); } if(last == null) { throw new IllegalArgumentException("last cannot be null"); } id = i; firstName = first; lastName = last; } }
There a Student must be created with an id, a first name, and a last name. The student ID can never change, but a persons last and first name can change (get married, changes name due to losing a bet, etc...).
When deciding what constrructors to have you really need to think about what makes sense to have. All to often people add set/get methods because they are taught to - but very often it is a bad idea.
Immutable classes are much better to have (that is classes with final variables) over mutable ones. This book: http://books.google.com/books?id=ZZOiqZQIbRMC&pg=PA97&sig=JgnunNhNb8MYDcx60Kq4IyHUC58#PPP1,M1 (Effective Java) has a good discussion on immutability. Look at items 12 and 13.
I use this script
EXEC sp_MSForEachTable ‘ALTER TABLE ? NOCHECK CONSTRAINT ALL’
EXEC sp_MSForEachTable ‘DELETE FROM ?’
EXEC sp_MSForEachTable ‘ALTER TABLE ? CHECK CONSTRAINT ALL’
GO
Here's where it gets confusing, the text states "If the balance factor of R is 1, it means the insertion occurred on the (external) right side of that node and a left rotation is needed". But from m understanding the text said (as I quoted) that if the balance factor was within [-1, 1] then there was no need for balancing?
R
is the right-hand child of the current node N
.
If balance(N) = +2
, then you need a rotation of some sort. But which rotation to use? Well, it depends on balance(R)
: if balance(R) = +1
then you need a left-rotation on N
; but if balance(R) = -1
then you will need a double-rotation of some sort.
public class Organization {
@Id
@Column(name="org_id")
@GeneratedValue
private int id;
@Column(name="org_name")
private String name;
@Column(name="org_office_address1")
private String address1;
@Column(name="org_office_addres2")
private String address2;
@Column(name="city")
private String city;
@Column(name="state")
private String state;
@Column(name="country")
private String country;
@JsonIgnore
@OneToOne
@JoinColumn(name="pkg_id")
private int pkgId;
public int getPkgId() {
return pkgId;
}
public void setPkgId(int pkgId) {
this.pkgId = pkgId;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
@Column(name="pincode")
private String pincode;
@OneToMany(mappedBy = "organization", cascade=CascadeType.ALL, fetch = FetchType.EAGER)
private Set<OrganizationBranch> organizationBranch = new HashSet<OrganizationBranch>(0);
@Column(name="status")
private String status = "ACTIVE";
@Column(name="project_id")
private int redmineProjectId;
public int getRedmineProjectId() {
return redmineProjectId;
}
public void setRedmineProjectId(int redmineProjectId) {
this.redmineProjectId = redmineProjectId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Set<OrganizationBranch> getOrganizationBranch() {
return organizationBranch;
}
public void setOrganizationBranch(Set<OrganizationBranch> organizationBranch) {
this.organizationBranch = organizationBranch;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
}
You change the private int pkgId line in change datatype int to primitive class name or add annotation @autowired
Use Dart Generators, that is used to produce a sequence of number or values.
main(){
print("Sequence Number");
oddnum(10).forEach(print);
}
Iterable<int> oddnum(int num) sync*{
int k=num;
while(k>=0){
if(k%2==1){
yield k;
}
k--;
}
}
I had similar issue where it was not recognizing Promise.resolve() method. I changed "target" value from ES5 to ES6 in tsconfig.json. That solved the problem.
Hope this helps.
Try =Year(Now())
and format the cell as General
.
I know it's very late for this one... But here is a (not so simple) oneliner to get what you were looking for:
git show-branch --all 2>/dev/null | grep -E "\[$(git branch | grep -E '^\*' | awk '{ printf $2 }')" | tail -n+2 | sed -E "s/^[^\[]*?\[/[/"
git show-branch
(sending the warnings to /dev/null
).grep -E "\[$BRANCH_NAME"
.$BRANCH_NAME
is obtained with git branch | grep -E '^\*' | awk '{ printf $2 }'
(the branch with a star, echoed without that star).tail -n+2
.[$BRANCH_NAME]
with sed -E "s/^[^\[]*?\[/[/"
.actually, your answer is not complete as the values also depend on the wrapping container. In case of relative or linear layouts, the values behave like this:
In case of an horizontal scroll view, your code will work.
after 5 long years I'm sure not much attention is going to be received for this answer, But still to make all options complete, here is the one with data.table
library(data.table)
setDT(df)[ , list(mean_gr = mean(dt), sum_gr = sum(dt)) , by = .(group)]
# group mean_gr sum_gr
#1: A 61 244
#2: B 66 396
#3: C 68 408
#4: D 61 488
As per https://android.stackexchange.com/a/78183/239063 you can run a one line command in Linux to add in an appropriate tar header to extract it.
( printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" ; tail -c +25 backup.ab ) | tar xfvz -
Replace backup.ab with the path to your file.
I got this error after change a loop in my program, let`s see:
for ...
for ...
x_batch.append(one_hot(int_word, vocab_size))
y_batch.append(one_hot(int_nb, vocab_size, value))
...
...
if ...
x_batch = np.asarray(x_batch)
y_batch = np.asarray(y_batch)
...
In fact, I was reusing the variable and forgot to reset them inside the external loop, like the comment of John Lyon:
for ...
x_batch = []
y_batch = []
for ...
x_batch.append(one_hot(int_word, vocab_size))
y_batch.append(one_hot(int_nb, vocab_size, value))
...
...
if ...
x_batch = np.asarray(x_batch)
y_batch = np.asarray(y_batch)
...
Then, check if you are using np.asarray() or something like that.
I'm quite late to the party, but one approach is to use a static inner class to unwrap values:
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
class Scratch {
private final String aString;
private final String bString;
private final String cString;
private final static String jsonString;
static {
jsonString = "{\n" +
" \"wrap\" : {\n" +
" \"A\": \"foo\",\n" +
" \"B\": \"bar\",\n" +
" \"C\": \"baz\"\n" +
" }\n" +
"}";
}
@JsonCreator
Scratch(@JsonProperty("A") String aString,
@JsonProperty("B") String bString,
@JsonProperty("C") String cString) {
this.aString = aString;
this.bString = bString;
this.cString = cString;
}
@Override
public String toString() {
return "Scratch{" +
"aString='" + aString + '\'' +
", bString='" + bString + '\'' +
", cString='" + cString + '\'' +
'}';
}
public static class JsonDeserializer {
private final Scratch scratch;
@JsonCreator
public JsonDeserializer(@JsonProperty("wrap") Scratch scratch) {
this.scratch = scratch;
}
public Scratch getScratch() {
return scratch;
}
}
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
Scratch scratch = objectMapper.readValue(jsonString, Scratch.JsonDeserializer.class).getScratch();
System.out.println(scratch.toString());
}
}
However, it's probably easier to use objectMapper.configure(SerializationConfig.Feature.UNWRAP_ROOT_VALUE, true);
in conjunction with @JsonRootName("aName")
, as pointed out by pb2q
@PaulR posted this as a comment, but people should view it as an answer (and this answer works best for my needs):
sed -i 's/abc/xyz/g' xa*
This will work for a moderate amount of files, probably on the order of tens, but probably not on the order of millions.
The only solution that worked for me
Other solutions I have tried, which didn't work.
Cleaning/Rebuilding
Cleaning bin, obj folders
Changing namespace
Newer versions of phpMyAdmin don't have the "Relation View" option anymore, in which case you'll have to execute a statement to achieve the same thing. For example
ALTER TABLE employees
ADD CONSTRAINT fk_companyid FOREIGN KEY (companyid)
REFERENCES companies (id)
ON DELETE CASCADE;
In this example, if a row from companies is deleted, all employees with that companyid are also deleted.
Sometimes you can achieve the same result by playing only with padding OR margin. Example :
Say View X contains view Y (aka : View Y is inside View X).
-View Y with Margin=30 OR View X with Padding=30 will achieve the same result: View Y will have an offset of 30.
I had the same issue with firefox 38.
After using following version dependencies, I could resolve the issue.
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.53.0</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-firefox-driver</artifactId>
<version>2.53.0</version>
</dependency>
Not sure if this was what you were asking for, but I was personally trying to 'hide' some info in my html so that if someone inspected it, they would see the text in the source code.
It turns out that you can add ANY attribute, and so long as it isn't understood by the browser, it will just be left buried in the tag. My code was an easter egg: For people who couldn't afford to do the Makers Academy course, I basically encouraged them to inspect the element, where they would be given a secret URL where they could apply for a special, cut-price course (it's in haml, but it's the same idea in HTML):
.entry
%h2 I can't afford to do the course... What should I do?
%p{:url_you_should_visit => 'http://ronin.makersacademy.com'} Inspect and you shall find.
Or in html:
<p url_you_should_visit="http://ronin.makersacademy.com">Inspect and you shall find.</p>
Because 'url' is not a recognised html attribute, it makes no difference but is still discoverable. You could do the same with anything you wanted. You could have an attribute (in html) like:
<p thanks="Thanks to all the bloggers that helped me"> Some text </p>
And they'll be able to find your little easter egg if they want it... Hope that helps - it certainly helped me :)
You can directly set the content type like below:
res.writeHead(200, {'Content-Type': 'text/plain'});
For reference go through the nodejs Docs link.
I see this is quite an old post, but came across this looking for an answer for this problem. After reading some of the answers they seem very long winded, so after about 5 mins I managed to solve the problem very simply as follows:
httpd.conf for Apache leave the listen port as 80 and 'Server Name' as FQDN/IP :80.
Now for IIS go to Administrative Services > IIS Manager > 'Sites' in the Left hand nav drop down > in the right window select the top line (default web site) then bindings on the right.
Now select http > edit and change to 81 and enter your local IP for the server/pc and in domain enter either your FQDN (www.domain.com) or external IP close.
Restart both servers ensure your ports are open on both router and firewall, done.
This sounds long winded but literally took 5 mins of playing about. works perfectly.
System: Windows 8, IIS 8, Apache 2.2
Try stopping Apache and MySql and starting them again in the following order.
Wait for both services to stop properly before restarting. Turning them on and off too quickly gives the same problem.
Inspired by lansharks answer.
It is very simple, just do this:
t4.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
launchQuiz2(); // TODO Auto-generated method stub
}
private void launchQuiz2() {
Intent i = new Intent(MainActivity.this, Quiz2.class);
startActivity(i);
// TODO Auto-generated method stub
}
});
echo realpath(dirname(__FILE__));
If you place this in an included file, it prints the path to this include. To get the path of the parent script, replace __FILE__
with $_SERVER['PHP_SELF']
. But be aware that PHP_SELF is a security risk!
You can set the flag directly using setter method. In Kotlin or
is the replacement for the Java bitwise or |
.
intent.flags = FLAG_ACTIVITY_NEW_TASK or FLAG_ACTIVITY_CLEAR_TASK
If you plan to use this regularly, create an Intent extension function
fun Intent.clearStack() {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
You can then directly call this function before starting the intent
intent.clearStack()
If you need the option to add additional flags in other situations, add an optional param to the extension function.
fun Intent.clearStack(additionalFlags: Int = 0) {
flags = additionalFlags or Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
update table_name set field1 = field1 + 1;
I would like to add that if you only have Python3 on your system then you need to start using pip3 instead of pip.
You can install pip3 using the following command;
sudo apt install python3-pip -y
After this you can try to install the package you need with;
sudo pip3 install <package>
The min sdk version is the minimum version of the Android operating system required to run your application.
The target sdk version is the version of Android that your app was created to run on.
The compile sdk version is the the version of Android that the build tools uses to compile and build the application in order to release, run, or debug.
Usually the compile sdk version and the target sdk version are the same.
I think you should do
for index, row in result:
If you wanna access by name.
try this,it should work fine
this.setState(Object.assign(this.state.jasper,{name:'someOtherName'}));
year(table_column)
Example:
select * from mytable where year(transaction_day)='2013'
Goto my blog : retrofit with kotlin
the link below explains everything step by step.
http://loopj.com/android-async-http/
Here are sample apps:
Create a class :
public class HttpUtils {
private static final String BASE_URL = "http://api.twitter.com/1/";
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(getAbsoluteUrl(url), params, responseHandler);
}
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
}
public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(url, params, responseHandler);
}
public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(url, params, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl;
}
}
Call Method :
RequestParams rp = new RequestParams();
rp.add("username", "aaa"); rp.add("password", "aaa@123");
HttpUtils.post(AppConstant.URL_FEED, rp, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// If the response is JSONObject instead of expected JSONArray
Log.d("asd", "---------------- this is response : " + response);
try {
JSONObject serverResp = new JSONObject(response.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
// Pull out the first event on the public timeline
}
});
Please grant internet permission in your manifest file.
<uses-permission android:name="android.permission.INTERNET" />
you can add compile 'com.loopj.android:android-async-http:1.4.9'
for Header[]
and compile 'org.json:json:20160212'
for JSONObject
in build.gradle file if required.
Although it doesn't add the "(.env)" prefix to the shell prompt, I found this script works as expected.
#!/bin/bash
script_dir=`dirname $0`
cd $script_dir
/bin/bash -c ". ../.env/bin/activate; exec /bin/bash -i"
e.g.
user@localhost:~/src$ which pip
/usr/local/bin/pip
user@localhost:~/src$ which python
/usr/bin/python
user@localhost:~/src$ ./shell
user@localhost:~/src$ which pip
~/.env/bin/pip
user@localhost:~/src$ which python
~/.env/bin/python
user@localhost:~/src$ exit
exit
There are detailed notes on this that helped me completely, located here.
Jonathon Reinhart has already answered with the key bit, to edit /etc/gitlab/gitlab.rb, alter the external_url and then run sudo gitlab-ctl reconfigure; sudo gitlab-ctl restart
However I needed to go a bit further and docs I linked above explained it. So what I ended up with looks like:
external_url 'https://gitlab.toilethumor.com'
nginx['ssl_certificate'] = "/www/ssl/star_toilethumor.com-chained.crt"
nginx['ssl_certificate_key'] = "/www/ssl/star_toilethumor.com.key"
nginx['proxy_set_headers'] = {
"X-Forwarded-Proto" => "http",
"CUSTOM_HEADER" => "VALUE"
}
Above, I've explicitly declared where my SSL goodies are on this server. And that's of course followed by
sudo gitlab-ctl reconfigure
sudo gitlab-ctl restart
Also, when you switch the omnibus package to https, the bundled nginx will only serve on port 443. Since all my stuff is reached via reverse proxy, this part was potentially significant.
As I went through this, I screwed something up and it helpful to find the actual nginx logs, this lead me there:
sudo gitlab-ctl tail nginx
you can use Vuex to handle all your global data
^(\d{0,2}\\.)?\d{1,2}$
\d{1,2}$
matches a 1-2 digit number with nothing after it (3
, 33
, etc.), (\d{0,2}\.)?
matches optionally a number 0-2 digits long followed by a period (3.
, 44.
, .
, etc.). Put them together and you've got your regex.
Shift + Alt + J will help you add author name in existing file.
To add author name automatically,
go to Preferences --> java --> Code Style --> Code Templates
in case you don't find above option in new versions of Eclipse - install it from https://marketplace.eclipse.org/content/jautodoc
var body: some View {
VStack {
CarouselView().edgesIgnoringSafeArea(.all)
List {
ForEach(viewModel.parents) { k in
VideosRowView(parent: k)
}
}
}
}
ECU = EC2 Compute Unit. More from here: http://aws.amazon.com/ec2/faqs/#What_is_an_EC2_Compute_Unit_and_why_did_you_introduce_it
Amazon EC2 uses a variety of measures to provide each instance with a consistent and predictable amount of CPU capacity. In order to make it easy for developers to compare CPU capacity between different instance types, we have defined an Amazon EC2 Compute Unit. The amount of CPU that is allocated to a particular instance is expressed in terms of these EC2 Compute Units. We use several benchmarks and tests to manage the consistency and predictability of the performance from an EC2 Compute Unit. One EC2 Compute Unit provides the equivalent CPU capacity of a 1.0-1.2 GHz 2007 Opteron or 2007 Xeon processor. This is also the equivalent to an early-2006 1.7 GHz Xeon processor referenced in our original documentation. Over time, we may add or substitute measures that go into the definition of an EC2 Compute Unit, if we find metrics that will give you a clearer picture of compute capacity.
If you can't add to the BODY tag for some reason, you can add this AFTER the Form:
<SCRIPT type="text/javascript">
document.yourFormName.yourFieldName.focus();
</SCRIPT>
If the value is between –2147483648 and 2147483647, cast(string_filed as int) will work. else cast(string_filed as bigint) will work
hive> select cast('2147483647' as int);
OK
2147483647
hive> select cast('2147483648' as int);
OK
NULL
hive> select cast('2147483648' as bigint);
OK
2147483648
Recently, I explored the possibilities to parameterize the folder to scan through and the place where the result of recursive scan will be stored. At the end, I also did summarize the number of folders scanned and number of files inside as well. Sharing it with community in case it may help other developers.
##Script Starts
#read folder to scan and file location to be placed
$whichFolder = Read-Host -Prompt 'Which folder to Scan?'
$whereToPlaceReport = Read-Host -Prompt 'Where to place Report'
$totalFolders = 1
$totalFiles = 0
Write-Host "Process started..."
#IMP separator ? : used as a file in window cannot contain this special character in the file name
#Get Foldernames into Variable for ForEach Loop
$DFSFolders = get-childitem -path $whichFolder | where-object {$_.Psiscontainer -eq "True"} |select-object name ,fullName
#Below Logic for Main Folder
$mainFiles = get-childitem -path "C:\Users\User\Desktop" -file
("Folder Path" + "?" + "Folder Name" + "?" + "File Name " + "?"+ "File Length" )| out-file "$whereToPlaceReport\Report.csv" -Append
#Loop through folders in main Directory
foreach($file in $mainFiles)
{
$totalFiles = $totalFiles + 1
("C:\Users\User\Desktop" + "?" + "Main Folder" + "?"+ $file.name + "?" + $file.length ) | out-file "$whereToPlaceReport\Report.csv" -Append
}
foreach ($DFSfolder in $DFSfolders)
{
#write the folder name in begining
$totalFolders = $totalFolders + 1
write-host " Reading folder C:\Users\User\Desktop\$($DFSfolder.name)"
#$DFSfolder.fullName | out-file "C:\Users\User\Desktop\PoC powershell\ok2.csv" -Append
#For Each Folder obtain objects in a specified directory, recurse then filter for .sft file type, obtain the filename, then group, sort and eventually show the file name and total incidences of it.
$files = get-childitem -path "$whichFolder\$($DFSfolder.name)" -recurse
foreach($file in $files)
{
$totalFiles = $totalFiles + 1
($DFSfolder.fullName + "?" + $DFSfolder.name + "?"+ $file.name + "?" + $file.length ) | out-file "$whereToPlaceReport\Report.csv" -Append
}
}
# If running in the console, wait for input before closing.
if ($Host.Name -eq "ConsoleHost")
{
Write-Host ""
Write-Host ""
Write-Host ""
Write-Host " **Summary**" -ForegroundColor Red
Write-Host " ------------" -ForegroundColor Red
Write-Host " Total Folders Scanned = $totalFolders " -ForegroundColor Green
Write-Host " Total Files Scanned = $totalFiles " -ForegroundColor Green
Write-Host ""
Write-Host ""
Write-Host "I have done my Job,Press any key to exit" -ForegroundColor white
$Host.UI.RawUI.FlushInputBuffer() # Make sure buffered input doesn't "press a key" and skip the ReadKey().
$Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp") > $null
}
##Output
##Bat Code to run above powershell command
@ECHO OFF
SET ThisScriptsDirectory=%~dp0
SET PowerShellScriptPath=%ThisScriptsDirectory%MyPowerShellScript.ps1
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%PowerShellScriptPath%""' -Verb RunAs}";
A simple, shell/platform-independent, pure macro solution is ...
# GNU make (`gmake`) compatible; ref: <https://www.gnu.org/software/make/manual>
define EOL
$()
endef
%sequence = $(if $(word ${1},${2}),$(wordlist 1,${1},${2}),$(call %sequence,${1},${2} $(words _ ${2})))
.PHONY: target
target:
$(foreach i,$(call %sequence,10),./a.out ${i}${EOL})
Just add box-sizing:
input[type="text"] {
box-sizing: border-box;
}
It's very easy to write that yourself, and that way you have more control over things.. As the other answers say, TypeScript is not aimed at adding runtime types or functionality.
Map:
class Map<T> {
private items: { [key: string]: T };
constructor() {
this.items = {};
}
add(key: string, value: T): void {
this.items[key] = value;
}
has(key: string): boolean {
return key in this.items;
}
get(key: string): T {
return this.items[key];
}
}
List:
class List<T> {
private items: Array<T>;
constructor() {
this.items = [];
}
size(): number {
return this.items.length;
}
add(value: T): void {
this.items.push(value);
}
get(index: number): T {
return this.items[index];
}
}
I haven't tested (or even tried to compile) this code, but it should give you a starting point.. you can of course then change what ever you want and add the functionality that YOU need...
As for your "special needs" from the List, I see no reason why to implement a linked list, since the javascript array lets you add and remove items.
Here's a modified version of the List to handle the get prev/next from the element itself:
class ListItem<T> {
private list: List<T>;
private index: number;
public value: T;
constructor(list: List<T>, value: T, index: number) {
this.list = list;
this.index = index;
this.value = value;
}
prev(): ListItem<T> {
return this.list.get(this.index - 1);
}
next(): ListItem<T> {
return this.list.get(this.index + 1);
}
}
class List<T> {
private items: Array<ListItem<T>>;
constructor() {
this.items = [];
}
size(): number {
return this.items.length;
}
add(value: T): void {
this.items.push(new ListItem<T>(this, value, this.size()));
}
get(index: number): ListItem<T> {
return this.items[index];
}
}
Here too you're looking at untested code..
Hope this helps.
Javascript has a native Map object so there's no need to create your own:
let map = new Map();
map.set("key1", "value1");
console.log(map.get("key1")); // value1
The simplest way is using python-dateutil
import datetime
import dateutil
def birthday(date):
# Get the current date
now = datetime.datetime.utcnow()
now = now.date()
# Get the difference between the current date and the birthday
age = dateutil.relativedelta.relativedelta(now, date)
age = age.years
return age
Use this css, as you already have the markup for it:
.img-container {
position: absolute;
top: 50%;
left: 50%;
}
.img-container > img {
margin-top:-50%;
margin-left:-50%;
}
Here is a working JsBin: http://jsbin.com/ihilUnI/1/edit
This solution only works for square images (because a percentage margin-top value depends on the width of the container, not the height). For random-size images, you can do the following:
.img-container {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* add browser-prefixes */
}
Working JsBin solution: http://jsbin.com/ihilUnI/2/edit
These might work. I don't know how they behave when running as a service. They aren't portable, but that's what os.name
and if
statements are for.
win32api.GetUserName()
win32api.GetUserNameEx(...)
See: http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file.html
Use underscore (or loDash :)):
var randomArray = [
'#cc0000','#00cc00', '#0000cc'
];
// use _.sample
var randomElement = _.sample(randomArray);
// manually use _.random
var randomElement = randomArray[_.random(randomArray.length-1)];
Or to shuffle an entire array:
// use underscore's shuffle function
var firstRandomElement = _.shuffle(randomArray)[0];
This will also work and you don't need the extra class:
#navigation li li {}
If you have a third level of LI's you may have to reset/override some of the styles they will inherit from the above selector. You can target the third level like so:
#navigation li li li {}
Maintain a list of nodes you can travel to, sorted by the distance from your start node. In the beginning only your start node will be in the list.
While you haven't reached your destination: Visit the node closest to the start node, this will be the first node in your sorted list. When you visit a node, add all its neighboring nodes to your list except the ones you have already visited. Repeat!
The UN maintains a list of countries and "states" / regions for economic trade. That DB is available here: http://www.unece.org/cefact/locode/welcome.html
The question does not mention the VM Provider but in my case, I use Virtual Box under the same environment. There is an option in the Virtual Box GUI that I needed to enable in order to make it work. Is located in the Virtual Box app preferences: File >> Preferences... >> Proxy. Once I configured this, I was able to work without problems. Hope this tip can also help you guys.
You can always use the DATALENGTH Function to determine if you have extra white space characters in text fields. This won't make the text visible but will show you where there are extra white space characters.
SELECT DATALENGTH('MyTextData ') AS BinaryLength, LEN('MyTextData ') AS TextLength
This will produce 11 for BinaryLength and 10 for TextLength.
In a table your SQL would like this:
SELECT *
FROM tblA
WHERE DATALENGTH(MyTextField) > LEN(MyTextField)
This function is usable in all versions of SQL Server beginning with 2005.
When the JVM loads classes, or otherwise sees a literal string, or some code intern
s a string, it adds the string to a mostly-hidden lookup table that has one copy of each such string. If another copy is added, the runtime arranges it so that all the literals refer to the same string object. This is called "interning". If you say something like
String s = "test";
return (s == "test");
it'll return true
, because the first and second "test" are actually the same object. Comparing interned strings this way can be much, much faster than String.equals
, as there's a single reference comparison rather than a bunch of char
comparisons.
You can add a string to the pool by calling String.intern()
, which will give you back the pooled version of the string (which could be the same string you're interning, but you'd be crazy to rely on that -- you often can't be sure exactly what code has been loaded and run up til now and interned the same string). The pooled version (the string returned from intern
) will be equal to any identical literal. For example:
String s1 = "test";
String s2 = new String("test"); // "new String" guarantees a different object
System.out.println(s1 == s2); // should print "false"
s2 = s2.intern();
System.out.println(s1 == s2); // should print "true"
document.querySelector('#from1').onsubmit = function(e){
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'Yes, I am sure!',
cancelButtonText: "No, cancel it!",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm){
if (isConfirm){
swal("Shortlisted!", "Candidates are successfully shortlisted!", "success");
} else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
e.preventDefault();
}
});
};
When you separate code from main.go
into for example more.go
, you simply pass that file to go build
/go run
/go install
as well.
So if you previously ran
go build main.go
you now simply
go build main.go more.go
As further information:
go build --help
states:
If the arguments are a list of .go files, build treats them as a list of source files specifying a single package.
Notice that go build
and go install
differ from go run
in that the first two state to expect package names as arguments, while the latter expects go files. However, the first two will also accept go files as go install does.
If you are wondering: build will just build
the packages/files, install
will produce object and binary files in your GOPATH, and run
will compile and run your program.
Edit:
As some folks needs help in Unlocking device after locking programmatically, I came through post Android screen lock/ unlock programatically, please have look, may help you.
Original Answer was:
You need to get Admin permission and you can lock phone screen
please check below simple tutorial to achive this one
Lock Phone Screen Programmtically
also here is the code example..
LockScreenActivity.java
public class LockScreenActivity extends Activity implements OnClickListener {
private Button lock;
private Button disable;
private Button enable;
static final int RESULT_ENABLE = 1;
DevicePolicyManager deviceManger;
ActivityManager activityManager;
ComponentName compName;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
deviceManger = (DevicePolicyManager)getSystemService(
Context.DEVICE_POLICY_SERVICE);
activityManager = (ActivityManager)getSystemService(
Context.ACTIVITY_SERVICE);
compName = new ComponentName(this, MyAdmin.class);
setContentView(R.layout.main);
lock =(Button)findViewById(R.id.lock);
lock.setOnClickListener(this);
disable = (Button)findViewById(R.id.btnDisable);
enable =(Button)findViewById(R.id.btnEnable);
disable.setOnClickListener(this);
enable.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v == lock){
boolean active = deviceManger.isAdminActive(compName);
if (active) {
deviceManger.lockNow();
}
}
if(v == enable){
Intent intent = new Intent(DevicePolicyManager
.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
compName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
"Additional text explaining why this needs to be added.");
startActivityForResult(intent, RESULT_ENABLE);
}
if(v == disable){
deviceManger.removeActiveAdmin(compName);
updateButtonStates();
}
}
private void updateButtonStates() {
boolean active = deviceManger.isAdminActive(compName);
if (active) {
enable.setEnabled(false);
disable.setEnabled(true);
} else {
enable.setEnabled(true);
disable.setEnabled(false);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case RESULT_ENABLE:
if (resultCode == Activity.RESULT_OK) {
Log.i("DeviceAdminSample", "Admin enabled!");
} else {
Log.i("DeviceAdminSample", "Admin enable FAILED!");
}
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
}
MyAdmin.java
public class MyAdmin extends DeviceAdminReceiver{
static SharedPreferences getSamplePreferences(Context context) {
return context.getSharedPreferences(
DeviceAdminReceiver.class.getName(), 0);
}
static String PREF_PASSWORD_QUALITY = "password_quality";
static String PREF_PASSWORD_LENGTH = "password_length";
static String PREF_MAX_FAILED_PW = "max_failed_pw";
void showToast(Context context, CharSequence msg) {
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}
@Override
public void onEnabled(Context context, Intent intent) {
showToast(context, "Sample Device Admin: enabled");
}
@Override
public CharSequence onDisableRequested(Context context, Intent intent) {
return "This is an optional message to warn the user about disabling.";
}
@Override
public void onDisabled(Context context, Intent intent) {
showToast(context, "Sample Device Admin: disabled");
}
@Override
public void onPasswordChanged(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw changed");
}
@Override
public void onPasswordFailed(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw failed");
}
@Override
public void onPasswordSucceeded(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw succeeded");
}
}
Ok, finally found the solution.
Probably due to lack of experience with ReactJS and web development...
var Task = React.createClass({
render: function() {
var percentage = this.props.children + '%';
....
<div className="ui-progressbar-value ui-widget-header ui-corner-left" style={{width : percentage}}/>
...
I created the percentage variable outside in the render function.
try this:
//this method to check bluetooth is enable or not: true if enable, false is not enable
public static boolean isBluetoothEnabled()
{
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()) {
// Bluetooth is not enable :)
return false;
}
else{
return true;
}
}
//method to enable bluetooth
public static void enableBluetooth(){
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.enable();
}
}
//method to disable bluetooth
public static void disableBluetooth(){
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
}
}
Add these permissions in manifest
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>