If you can't find the password based on other answers that point to a default one, the log message wording in recent versions changed to
Using generated security password: <some UUID>
This is because you are executing the function not referencing it. You should do:
setInterval(swapImages,1000);
I had been using the method in Jon Skeet's answer, but another one occurred to me using Concat
. The Concat
method performed slightly better in a limited test, but it's a hassle and I'll probably just stick with Contains
, or maybe I'll write a helper method to do this for me. Either way, here's another option if anyone is interested:
// Given an array of id's
var ids = new Guid[] { ... };
// and a DataContext
var dc = new MyDataContext();
// start the queryable
var query = (
from thing in dc.Things
where thing.Id == ids[ 0 ]
select thing
);
// then, for each other id
for( var i = 1; i < ids.Count(); i++ ) {
// select that thing and concat to queryable
query.Concat(
from thing in dc.Things
where thing.Id == ids[ i ]
select thing
);
}
This was not remotely scientific. I imagine your database structure and the number of IDs involved in the list would have a significant impact.
I set up a test where I did 100 trials each of Concat
and Contains
where each trial involved selecting 25 rows specified by a randomized list of primary keys. I've run this about a dozen times, and most times the Concat
method comes out 5 - 10% faster, although one time the Contains
method won by just a smidgen.
There is another way to reset the password through command prompt ...
1) Go to the Oracle Database Folder ( In my case Oracle Database 11g Express Edition) in the START MENU.
2) Within that folder click "Run SQL Commandline"
3) Type "connect username/password" (your username and old password without the quotation marks)
4) The message displayed is ...
ERROR: ORA-28001: the password has expired
Changing password for hr
--> New password:
Enter Username, Password image
5) Type the new password
6) Retype the new password
7) Message displayed is ...
Password changed Connected.
SQL>
8) GO TO Sql developer --> type the new password --> connected
Two changes are needed:
Array[]
to ArtWorkData[]
Labels[]
in the return statement to Labels
These guys have an API that will give the results. It's also free to use.
Note: they also provide data source download in xls or sql format at a premium price. but these data also provides technical specifications for all the make model and trim options.
Here's a chart that summarises some of the most important conversions in pandas.
Conversions to string are trivial .astype(str)
and are not shown in the figure.
Note that "conversions" in this context could either refer to converting text data into their actual data type (hard conversion), or inferring more appropriate data types for data in object columns (soft conversion). To illustrate the difference, take a look at
df = pd.DataFrame({'a': ['1', '2', '3'], 'b': [4, 5, 6]}, dtype=object)
df.dtypes
a object
b object
dtype: object
# Actually converts string to numeric - hard conversion
df.apply(pd.to_numeric).dtypes
a int64
b int64
dtype: object
# Infers better data types for object data - soft conversion
df.infer_objects().dtypes
a object # no change
b int64
dtype: object
# Same as infer_objects, but converts to equivalent ExtensionType
df.convert_dtypes().dtypes
when: myvar | default('', true) | trim != ''
I use | trim != ''
to check if a variable has an empty value or not. I also always add the | default(..., true)
check to catch when myvar
is undefined too.
To add to the valuable content, I would like to create this reminder on why sometimes RegEx within VBA is not ideal. Not all expressions are supported, but instead may throw an Error 5017
and may leave the author guessing (which I am a victim of myself).
Whilst we can find some sources on what is supported, it would be helpfull to know which metacharacters etc. are not supported. A more in-depth explaination can be found here. Mentioned in this source:
"Although "VBScript’s regular expression ... version 5.5 implements quite a few essential regex features that were missing in previous versions of VBScript. ... JavaScript and VBScript implement Perl-style regular expressions. However, they lack quite a number of advanced features available in Perl and other modern regular expression flavors:"
So, not supported are:
\A
, alternatively use the ^
caret to match postion before 1st char in string\Z
, alternatively use the $
dollar sign to match postion after last char in string(?<=a)b
(whilst postive LookAhead is supported)(?<!a)b
(whilst negative LookAhead is supported)\{uFFFF}
/i
(case sensitivity) or /g
(global) etc. Set these through the RegExp
object properties > RegExp.Global = True
and RegExp.IgnoreCase = True
if available.'
comments in script I already hit a wall more than once using regular expressions within VBA. Usually with LookBehind
but sometimes I even forget the modifiers. I have not experienced all these above mentioned backdrops myself but thought I would try to be extensive referring to some more in-depth information. Feel free to comment/correct/add. Big shout out to regular-expressions.info for a wealth of information.
P.S. You have mentioned regular VBA methods and functions, and I can confirm they (at least to myself) have been helpful in their own ways where RegEx would fail.
As everyone already mentioned, this is not the best way of using lists in Scala...
scala> val list = scala.collection.mutable.MutableList[String]()
list: scala.collection.mutable.MutableList[String] = MutableList()
scala> list += "hello"
res0: list.type = MutableList(hello)
scala> list += "world"
res1: list.type = MutableList(hello, world)
scala> list mkString " "
res2: String = hello world
<form action="" onsubmit="additon()" name="form1" id="form1">
a: <input type="number" name="a" id="a"><br>
b: <input type="number" name="b" id="b"><br>
<input type="submit" value="Submit" name="submit">
</form>
<script>
function additon()
{
var a = document.getElementById('a').value;
var b = document.getElementById('b').value;
var sum = parseInt(a) + parseInt(b);
return sum;
}
</script>
While C++ (excluding C++11) has enums, the values in them are "leaked" into the global namespace.
If you don't want to have them leaked (and don't NEED to use the enum type), consider the following:
class EnumName {
public:
static int EnumVal1;
(more definitions)
};
EnumName::EnumVal1 = {value};
if ([your value] == EnumName::EnumVal1) ...
Use double quote to enclose the quote or escape it.
newTemp = mystring.replace(/"/g, "'");
or
newTemp = mystring.replace(/"/g, '\'');
Remove this
android:onClick="goToAttract"
Then
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
Button b = (Button)rootView.findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(getActivity(), MainActivityList.class);
startActivity(intent);
}
});
return rootView;
The error says you need to public void goToAttract(View v)
in Activity class
Could not find method goToAttract(View) in the activity class
Reason pls check the answer by PareshMayani @
Android app crashing (fragment and xml onclick)
Edit:
Caused by: java.lang.OutOfMemoryError
I guess you have a image that is too big to fit in and it needs to be scaled down. Hence the OutOfMemoryError
.
Get all the outdated packages and create a batch file with the following commands pip install xxx --upgrade for each outdated packages
You can have separate configuration file, but you'll have to read it "manually", the ConfigurationManager.AppSettings["key"]
will read only the config of the running assembly.
Assuming you're using Visual Studio as your IDE, you can right click the desired project ? Add ? New item ? Application Configuration File
This will add App.config
to the project folder, put your settings in there under <appSettings>
section. In case you're not using Visual Studio and adding the file manually, make sure to give it such name: DllName.dll.config, otherwise the below code won't work properly.
Now to read from this file have such function:
string GetAppSetting(Configuration config, string key)
{
KeyValueConfigurationElement element = config.AppSettings.Settings[key];
if (element != null)
{
string value = element.Value;
if (!string.IsNullOrEmpty(value))
return value;
}
return string.Empty;
}
And to use it:
Configuration config = null;
string exeConfigPath = this.GetType().Assembly.Location;
try
{
config = ConfigurationManager.OpenExeConfiguration(exeConfigPath);
}
catch (Exception ex)
{
//handle errror here.. means DLL has no sattelite configuration file.
}
if (config != null)
{
string myValue = GetAppSetting(config, "myKey");
...
}
You'll also have to add reference to System.Configuration namespace in order to have the ConfigurationManager class available.
When building the project, in addition to the DLL you'll have DllName.dll.config
file as well, that's the file you have to publish with the DLL itself.
The above is basic sample code, for those interested in a full scale example, please refer to this other answer.
A simple safe way would be to use an alias. Place this into ~/.bashrc file: if you have gedit editor use
gedit ~/.bashrc
to go into the bashrc file and then at the top of the bashrc file make the following change.
alias python=python3
After adding the above in the file. run the below command
source ~/.bash_aliases or source ~/.bashrc
example:
$ python --version
Python 2.7.6
$ python3 --version
Python 3.4.3
$ alias python=python3
$ python --version
Python 3.4.3
Packet Capture Android app implements a VPN that logs all network traffic on the Android device. You don't need to setup any VPN/proxy server on your PC. Does not needs root. Supports SSL decryption which tPacketCapture does not. It also includes a good log viewer.
You can do this in 2 steps:
1: Change the input type(In your EditText
field) in the layout file to android:inputType="number"
2: Use int a = Integer.parseInt(yourEditTextObject.getText().toString());
Got it myself, it's a bit kludgy but it works:
substr(dirname($_SERVER['SCRIPT_NAME']), 0, strrpos(dirname($_SERVER['SCRIPT_NAME']), '/') + 1)
So if I have /path/to/folder/index.php
, this results in /path/to/
.
If you need a PEM file without any password you can use this solution.
Just copy and paste the private key and the certificate to the same file and save as .pem.
The file will look like:
-----BEGIN PRIVATE KEY-----
............................
............................
-----END PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
...........................
...........................
-----END CERTIFICATE-----
That's the only way I found to upload certificates to Cisco devices for HTTPS.
It can be done by code as follows:
import time
time.sleep(10) #Set the time
for x in range(60):
time.sleep(1)
print('\a')
The answer above is correct, but in terms of the workaround, I had problems with the BouncyCastle implementation when I set it as preferred provider:
java.lang.ArrayIndexOutOfBoundsException: 64
at com.sun.crypto.provider.TlsPrfGenerator.expand(DashoA13*..)
This is also discussed in one forum thread I found, which doesn't mention a solution. http://www.javakb.com/Uwe/Forum.aspx/java-programmer/47512/TLS-problems
I found an alternative solution which works for my case, although I'm not at all happy with it. The solution is to set it so that the Diffie-Hellman algorithm is not available at all. Then, supposing the server supports an alternative algorithm, it will be selecting during normal negotiation. Obviously the downside of this is that if somebody somehow manages to find a server that only supports Diffie-Hellman at 1024 bits or less then this actually means it will not work where it used to work before.
Here is code which works given an SSLSocket (before you connect it):
List<String> limited = new LinkedList<String>();
for(String suite : ((SSLSocket)s).getEnabledCipherSuites())
{
if(!suite.contains("_DHE_"))
{
limited.add(suite);
}
}
((SSLSocket)s).setEnabledCipherSuites(limited.toArray(
new String[limited.size()]));
Nasty.
sizeof()
is just an alias of count()
as mentioned here
The problem I had was using the output in a conditional in a bash script.
This is not elegant, but in a docker env this should really not matter. Basically all this does is ignore the output that isn't on the last line. You can do similar with awk, and change to return all but the first line etc.
This only returns the Last line
mysql -u db_user -pInsecurePassword my_database ... | sed -e '$!d'
It won't suppress the error, but it will make sure you can use the output of a query in a bash script.
Add condition in Click event to restrict the clickable area .
$('#thing').click(function(e) {
if (e.clientX > $(this).offset().left + 90 &&
e.clientY < $(this).offset().top + 10) {
// action when clicking on after-element
// your code here
}
});
I solved it by interchanging the arguments, I was using
export default connect(mapDispatchToProps, mapStateToProps)(Checkbox)
which is wrong. The mapStateToProps
has to be the first argument:
export default connect(mapStateToProps, mapDispatchToProps)(Checkbox)
It sounds obvious now, but might help someone.
These are automatic variables, like $null
, $true
, $false
etc.
about_Automatic_Variables
, see https://technet.microsoft.com/en-us/library/hh847768.aspx?f=255&MSPPError=-2147217396
$NULL
$null
is an automatic variable that contains a NULL or empty value. You can use this variable to represent an absent or undefined value in commands and scripts.Windows PowerShell treats
$null
as an object with a value, that is, as an explicit placeholder, so you can use $null to represent an empty value in a series of values.For example, when
$null
is included in a collection, it is counted as one of the objects.C:\PS> $a = ".dir", $null, ".pdf" C:\PS> $a.count 3
If you pipe the
$null
variable to theForEach-Object
cmdlet, it generates a value for$null
, just as it does for the other objects.PS C:\ps-test> ".dir", $null, ".pdf" | Foreach {"Hello"} Hello Hello Hello
As a result, you cannot use
$null
to mean "no parameter value." A parameter value of$null
overrides the default parameter value.However, because Windows PowerShell treats the
$null
variable as a placeholder, you can use it scripts like the following one, which would not work if$null
were ignored.$calendar = @($null, $null, “Meeting”, $null, $null, “Team Lunch”, $null) $days = Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday" $currentDay = 0 foreach($day in $calendar) { if($day –ne $null) { "Appointment on $($days[$currentDay]): $day" } $currentDay++ }
output:
Appointment on Tuesday: Meeting Appointment on Friday: Team lunch
I had the same issue and resolved by adding "Connection Time" value in web.config file. locate the connectionStrings and add Connection Timeout=3600"
here is the sample
<connectionStrings>
<add name="MyConn" providerName="System.Data.SqlClient" connectionString="Data Source=MySQLServer;Initial Catalog=MyDB;User ID=sa;Password=123;Connection Timeout=3600" />
</connectionStrings>
Instead of using $http.get('abc/xyz/getSomething') try to use $http.jsonp('abc/xyz/getSomething')
return{
getList:function(){
return $http.jsonp('http://localhost:8080/getNames');
}
}
The System.Math.Round
method uses the Double
structure, which, as others have pointed out, is prone to floating point precision errors. The simple solution I found to this problem when I encountered it was to use the System.Decimal.Round
method, which doesn't suffer from the same problem and doesn't require redifining your variables as decimals:
Decimal.Round(0.575, 2, MidpointRounding.AwayFromZero)
Result: 0.58
Based on the other answers, here is a first draft for usage with knockout:
Usage
<div data-bind="editableSelect: {options: optionsObservable, value: nameObservable}"></div>
Knockout data binding
composition.addBindingHandler('editableSelect',
{
init: function(hostElement, valueAccessor) {
var optionsObservable = getOptionsObservable();
var valueObservable = getValueObservable();
var $editableSelect = $(hostElement);
$editableSelect.addClass('select-editable');
var editableSelect = $editableSelect[0];
var viewModel = new editableSelectViewModel(optionsObservable, valueObservable);
ko.applyBindingsToNode(editableSelect, { compose: viewModel });
//tell knockout to not apply bindings twice
return { controlsDescendantBindings: true };
function getOptionsObservable() {
var accessor = valueAccessor();
return getAttribute(accessor, 'options');
}
function getValueObservable() {
var accessor = valueAccessor();
return getAttribute(accessor, 'value');
}
}
});
View
<select
data-bind="options: options, event:{ focus: resetComboBoxValue, change: setTextFieldValue} "
id="comboBox"
></select>
<input
data-bind="value: value, , event:{ focus: textFieldGotFocus, focusout: textFieldLostFocus}"
id="textField"
type="text"/>
ViewModel
define([
'lodash',
'services/errorHandler'
], function(
_,
errorhandler
) {
var viewModel = function(optionsObservable, valueObservable) {
var self = this;
self.options = optionsObservable();
self.value = valueObservable;
self.resetComboBoxValue = resetComboBoxValue;
self.setTextFieldValue = setTextFieldValue;
self.textFieldGotFocus = textFieldGotFocus;
self.textFieldLostFocus = textFieldLostFocus;
function resetComboBoxValue() {
$('#comboBox').val(null);
}
function setTextFieldValue() {
var selection = $('#comboBox').val();
self.value(selection);
}
function textFieldGotFocus() {
$('#comboBox').addClass('select-editable-input-focus');
}
function textFieldLostFocus() {
$('#comboBox').removeClass('select-editable-input-focus');
}
};
errorhandler.includeIn(viewModel);
return viewModel;
});
CSS
.select-editable {
display: block;
width: 100%;
height: 31px;
padding: 6px 12px;
font-size: 12px;
line-height: 1.42857143;
color: #555555;
background-color: #ffffff;
background-image: none;
border: 1px solid #cccccc;
border-radius: 0px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
-o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;padding: 0;
}
.select-editable select {
outline:0;
padding-left: 10px;
border:none;
width:100%;
height: 29px;
}
.select-editable input {
outline:0;
position: relative;
top: -27px;
margin-left: 10px;
width:90%;
height: 25px;
border:none;
}
.select-editable select:focus {
outline:0;
border: 1px solid #66afe9;
-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);
box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);
}
.select-editable input:focus {
outline:0;
}
.select-editable-input-focus {
outline:0;
border: 1px solid #66afe9 !important;
-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);
box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);
}
For me there was no default constructor defined for the POJOs I was trying to use. creating default constructor fixed it.
public class TeamCode {
@Expose
private String value;
public String getValue() {
return value;
}
**public TeamCode() {
}**
public TeamCode(String value) {
this.value = value;
}
@Override
public String toString() {
return "TeamCode{" +
"value='" + value + '\'' +
'}';
}
public void setValue(String value) {
this.value = value;
}
}
It very much depend on the program you're using. Different programs (Emacs, vi, sed, and Perl) use slightly different regular expressions. In this case, I'd say that in the first pattern, the last "+" should be removed.
If you want to have bare run
command in gdb
to execute your program with redirections and arguments, you can use set args
:
% gdb ./a.out
(gdb) set args arg1 arg2 <file
(gdb) run
I was unable to achieve the same behaviour with --args
parameter, gdb
fiercely escapes the redirections, i.e.
% gdb --args echo 1 2 "<file"
(gdb) show args
Argument list to give program being debugged when it is started is "1 2 \<file".
(gdb) run
...
1 2 <file
...
This one actually redirects the input of gdb itself, not what we really want here
% gdb --args echo 1 2 <file
zsh: no such file or directory: file
You have to add this permission in Info.plist for iOS 10.
Photo :
Key : Privacy - Photo Library Usage Description
Value : $(PRODUCT_NAME) photo use
Microphone :
Key : Privacy - Microphone Usage Description
Value : $(PRODUCT_NAME) microphone use
Camera :
Key : Privacy - Camera Usage Description
Value : $(PRODUCT_NAME) camera use
SELECT 1 FROM user_right where userid = ? LIMIT 1
If your resultset contains a row then you do not have to insert. Otherwise insert your records.
This is a simple code that uses the System.in.read()
function. This code just writes out whatever was typed. You can get rid of the while loop if you just want to take input once, and you could store answers in a character array if you so choose.
package main;
import java.io.IOException;
public class Root
{
public static void main(String[] args)
{
new Root();
}
public Root()
{
while(true)
{
try
{
for(int y = 0; y < System.in.available(); ++y)
{
System.out.print((char)System.in.read());
}
}
catch(IOException ex)
{
ex.printStackTrace(System.out);
break;
}
}
}
}
While there is no iterator reset, the "itertools" module from python 2.6 (and later) has some utilities that can help there. One of then is the "tee" which can make multiple copies of an iterator, and cache the results of the one running ahead, so that these results are used on the copies. I will seve your purposes:
>>> def printiter(n):
... for i in xrange(n):
... print "iterating value %d" % i
... yield i
>>> from itertools import tee
>>> a, b = tee(printiter(5), 2)
>>> list(a)
iterating value 0
iterating value 1
iterating value 2
iterating value 3
iterating value 4
[0, 1, 2, 3, 4]
>>> list(b)
[0, 1, 2, 3, 4]
One of the best examples of Hadoop-like MapReduce implementation.
Keep in mind though that they are limited to key-value based implementations of the MapReduce idea (so they are limiting in applicability).
Sorry For late but perfect solution: when you try to remove a specific item just call notifydatasetchange() and get these item in bindviewholder and remove that item and add again to the last of list and then chek list position if this is last index then remove item. basically the problem is come when you try to remove item from the center. if you remove item from last index then there have no more recycling and also your adpter count are mantine (this is critical point crash come here) and the crash is solved the code snippet below .
holder.itemLayout.setVisibility( View.GONE );//to hide temprory it show like you have removed item
Model current = list.get( position );
list.remove( current );
list.add( list.size(), current );//add agine to last index
if(position==list.size()-1){// remove from last index
list.remove( position );
}
I had to use pip3 instead of pip in order to get the right versions for the right version of python (python 3.4 instead of python 2.x)
Check what you got install at: /usr/local/lib/python3.4/dist-packages
Also, when you run python, you might have to write python3.4 instead of python in order to use the right version of python.
No, template member functions cannot be virtual.
Try this php code.
<?PHP
function getUserIP()
{
// Get real visitor IP behind CloudFlare network
if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
$_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
$_SERVER['HTTP_CLIENT_IP'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
}
$client = @$_SERVER['HTTP_CLIENT_IP'];
$forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = $_SERVER['REMOTE_ADDR'];
if(filter_var($client, FILTER_VALIDATE_IP))
{
$ip = $client;
}
elseif(filter_var($forward, FILTER_VALIDATE_IP))
{
$ip = $forward;
}
else
{
$ip = $remote;
}
return $ip;
}
$user_ip = getUserIP();
echo $user_ip; // Output IP address [Ex: 177.87.193.134]
?>
Additionally to nargs
, you might want to use choices
if you know the list in advance:
>>> parser = argparse.ArgumentParser(prog='game.py')
>>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
>>> parser.parse_args(['rock'])
Namespace(move='rock')
>>> parser.parse_args(['fire'])
usage: game.py [-h] {rock,paper,scissors}
game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
'paper', 'scissors')
Use location.reload()
:
$('#something').click(function() {
location.reload();
});
The reload()
function takes an optional parameter that can be set to true
to force a reload from the server rather than the cache. The parameter defaults to false
, so by default the page may reload from the browser's cache.
I found this answer which is what nailed it for me as none of the above answers worked
https://unix.stackexchange.com/questions/91561/ps-full-command-is-too-long
Basically, the kernel is limiting my cmd line.
Make the code say if (msg.content === ('trigger') msg.author.send('text')}
<script>
var insertHtml = function (selector, argHtml) {
$(document).ready(function(){
$(selector).load(argHtml);
});
var targetElem = document.querySelector(selector);
targetElem.innerHTML = html;
};
var sliderHtml="snippets/slider.html";//url of slider html
var items="snippets/menuItems.html";
insertHtml("#main",sliderHtml);
insertHtml("#main2",items);
</script>
this one worked for me when I tried to add a snippet of HTML to my main.html.
Please don't forget to add ajax in your code
pass class or id as a selector and the link to the HTML snippet as argHtml
One correct way to get selected value would be
var selected_value = $('#fruit_name').val()
And then you should do
if(selected_value) { ... }
--for setting buffer size needed most of time to avoid `anonymous block completed` message
set serveroutput on size 30000;
-- declaration block in case output need to catch
DECLARE
--declaration for in and out parameter
V_OUT_1 NUMBER;
V_OUT_2 VARCHAR2(200);
BEGIN
--your stored procedure name
schema.package.procedure(
--declaration for in and out parameter
V_OUT_1 => V_OUT_1,
V_OUT_2 => V_OUT_2
);
V_OUT_1 := V_OUT_1;
V_OUT_2 := V_OUT_2;
-- console output, no need to open DBMS OUTPUT seperatly
-- also no need to print each output on seperat line
DBMS_OUTPUT.PUT_LINE('Ouput => ' || V_OUT_1 || ': ' || V_OUT_2);
END;
Java's Double
class has members containing the Min and Max value for the type.
2^-1074 <= x <= (2-2^-52)·2^1023 // where x is the double.
Check out the Min_VALUE
and MAX_VALUE
static final members of Double
.
(some)People will suggest against using floating point types for things where accuracy and precision are critical because rounding errors can throw off calculations by measurable (small) amounts.
If you have LineageOS 7.1.2 (and have root), try this solution from XDA.
After having tried all the solutions proposed here, none of which worked for my Nexus 4 (mako), I found one on XDA that solves the problem with the Android dialer (but not with other apps). Basically I downloaded a recompiled version of the Dialer.apk file, which simply ignores the proximity sensor and behaves in the same way as the stock dialer app does.
Rename /system/priv-app/Dialer/Dialer.apk to something, then place the downloaded file to that folder. After reboot, I had to install the new dialer manually (simply by clicking on it). So now the original app is replaced, and the calls should be handled by this new one.
[Downside: the new way to answer a call is by pulling down the status bar and clicking 'Answer' (or 'Dismiss'), the usual slider is missing. Also, you'll need to repeat this every time your Android updates to a newer version.]
If you're in Google Chrome, try installing this add-on:
Default to using the built in System.Text.Json
parser implementation.
e.g.
using System.Text.Json;
var json = JsonSerializer.Serialize(aList);
alternatively, other, less mainstream options are available like Utf8Json parser and Jil: These may offer superior performance, if you really need it but, you will need to install their respective packages.
Default to using Newtonsoft JSON.Net as your first choice JSON Parser.
e.g.
using Newtonsoft.Json;
var json = JsonConvert.SerializeObject(aList);
you may need to install the package first.
PM> Install-Package Newtonsoft.Json
For more details see and upvote the answer that is the source of this information.
// you need to reference System.Web.Extensions
using System.Web.Script.Serialization;
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(aList);
You will get it by tag type="date"...then it will render beautiful calendar and all...
@Html.TextBoxFor(model => model.EndTime, new { type = "date" })
Using a regex approach:
$regex = <<<'END'
/
(
(?: [\x00-\x7F] # single-byte sequences 0xxxxxxx
| [\xC0-\xDF][\x80-\xBF] # double-byte sequences 110xxxxx 10xxxxxx
| [\xE0-\xEF][\x80-\xBF]{2} # triple-byte sequences 1110xxxx 10xxxxxx * 2
| [\xF0-\xF7][\x80-\xBF]{3} # quadruple-byte sequence 11110xxx 10xxxxxx * 3
){1,100} # ...one or more times
)
| . # anything else
/x
END;
preg_replace($regex, '$1', $text);
It searches for UTF-8 sequences, and captures those into group 1. It also matches single bytes that could not be identified as part of a UTF-8 sequence, but does not capture those. Replacement is whatever was captured into group 1. This effectively removes all invalid bytes.
It is possible to repair the string, by encoding the invalid bytes as UTF-8 characters. But if the errors are random, this could leave some strange symbols.
$regex = <<<'END'
/
(
(?: [\x00-\x7F] # single-byte sequences 0xxxxxxx
| [\xC0-\xDF][\x80-\xBF] # double-byte sequences 110xxxxx 10xxxxxx
| [\xE0-\xEF][\x80-\xBF]{2} # triple-byte sequences 1110xxxx 10xxxxxx * 2
| [\xF0-\xF7][\x80-\xBF]{3} # quadruple-byte sequence 11110xxx 10xxxxxx * 3
){1,100} # ...one or more times
)
| ( [\x80-\xBF] ) # invalid byte in range 10000000 - 10111111
| ( [\xC0-\xFF] ) # invalid byte in range 11000000 - 11111111
/x
END;
function utf8replacer($captures) {
if ($captures[1] != "") {
// Valid byte sequence. Return unmodified.
return $captures[1];
}
elseif ($captures[2] != "") {
// Invalid byte of the form 10xxxxxx.
// Encode as 11000010 10xxxxxx.
return "\xC2".$captures[2];
}
else {
// Invalid byte of the form 11xxxxxx.
// Encode as 11000011 10xxxxxx.
return "\xC3".chr(ord($captures[3])-64);
}
}
preg_replace_callback($regex, "utf8replacer", $text);
EDIT:
!empty(x)
will match non-empty values ("0"
is considered empty).x != ""
will match non-empty values, including "0"
.x !== ""
will match anything except ""
.x != ""
seem the best one to use in this case.
I have also sped up the match a little. Instead of matching each character separately, it matches sequences of valid UTF-8 characters.
The best solution is the attribute selector in CSS (input[type="text"]
) as the others suggested.
But if you have to support Internet Explorer 6, you cannot use it (QuirksMode). Well, only if you have to and also are willing to support it.
In this case your only option seems to be to define classes on input elements.
<input type="text" class="input-box" ... />
<input type="submit" class="button" ... />
...
and target them with a class selector:
input.input-box, textarea { background: cyan; }
I suggest you to do in the following way:
(\d+)(,\s*\d+)*
which would work for a list containing 1 or more elements.
/*
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# dejavu sans
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
*/
/*default version*/
@font-face {
font-family: 'DejaVu Sans';
src: url('dejavu/DejaVuSans.ttf'); /* IE9 Compat Modes */
src:
local('DejaVu Sans'),
local('DejaVu-Sans'), /* Duplicated name with hyphen */
url('dejavu/DejaVuSans.ttf')
format('truetype');
}
/*bold version*/
@font-face {
font-family: 'DejaVu Sans';
src: url('dejavu/DejaVuSans-Bold.ttf');
src:
local('DejaVu Sans'),
local('DejaVu-Sans'),
url('dejavu/DejaVuSans-Bold.ttf')
format('truetype');
font-weight: bold;
}
/*italic version*/
@font-face {
font-family: 'DejaVu Sans';
src: url('dejavu/DejaVuSans-Oblique.ttf');
src:
local('DejaVu Sans'),
local('DejaVu-Sans'),
url('dejavu/DejaVuSans-Oblique.ttf')
format('truetype');
font-style: italic;
}
/*bold italic version*/
@font-face {
font-family: 'DejaVu Sans';
src: url('dejavu/DejaVuSans-BoldOblique.ttf');
src:
local('DejaVu Sans'),
local('DejaVu-Sans'),
url('dejavu/DejaVuSans-BoldOblique.ttf')
format('truetype');
font-weight: bold;
font-style: italic;
}
I did a similar thing a few months ago, and it turned out this simple format was enough for Hudson to accept it as a test protocol:
<testsuite tests="3">
<testcase classname="foo1" name="ASuccessfulTest"/>
<testcase classname="foo2" name="AnotherSuccessfulTest"/>
<testcase classname="foo3" name="AFailingTest">
<failure type="NotEnoughFoo"> details about failure </failure>
</testcase>
</testsuite>
This question has answers with more details: Spec. for JUnit XML Output
simple and easier solution:
select extract(hour from systimestamp) from dual;
EXTRACT(HOURFROMSYSTIMESTAMP)
-----------------------------
16
<table id="myData">
</table>
<script type="text/javascript">
$('#search').click(function() {
alert("submit handler has fired");
$.ajax({
type: 'POST',
url: 'cityResults.htm',
data: $('#cityDetails').serialize(),
success: function(data){
$.each(data, function( index, value ) {
var row = $("<tr><td>" + value.city + "</td><td>" + value.cStatus + "</td></tr>");
$("#myData").append(row);
});
},
error: function(jqXHR, textStatus, errorThrown){
alert('error: ' + textStatus + ': ' + errorThrown);
}
});
return false;//suppress natural form submission
});
</script>
loop through the data and append it to a table like the code above.
It's trying to connect to the computer it's running on on port 5000, but the connection is being refused. Are you sure you have a server running?
If not, you can use netcat
for testing:
nc -l -k -p 5000
Some implementations may require you to omit the -p
flag.
You can send Email by Jquery just follow these steps
include this link : <script src="https://smtpjs.com/v3/smtp.js"></script>
after that use this code :
$( document ).ready(function() {
Email.send({
Host : "smtp.yourisp.com",
Username : "username",
Password : "password",
To : '[email protected]',
From : "[email protected]",
Subject : "This is the subject",
Body : "And this is the body"}).then( message => alert(message));});
Try this:
string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority +
Request.ApplicationPath.TrimEnd('/') + "/";
You can use a background image
.application-title img {_x000D_
width:200px;_x000D_
height:200px;_x000D_
box-sizing:border-box;_x000D_
padding-left: 200px;_x000D_
/*width of the image*/_x000D_
background: url(http://lorempixel.com/200/200/city/2) left top no-repeat;_x000D_
}
_x000D_
<div class="application-title">_x000D_
<img src="http://lorempixel.com/200/200/city/1/">_x000D_
</div><br />_x000D_
Original Image: <br />_x000D_
_x000D_
<img src="http://lorempixel.com/200/200/city/1/">
_x000D_
If you want to modify this I'd go with either of the following:
List<string[]> results;
-- or --
List<List<string>> results;
depending on your needs...
I would echo what Wyzard wrote but add that:
URLEncoder
should not be usedI wrote a blog post a while back about this subject: Java: safe character handling and URL building
Try this. It is in VB.net and you need to convert it to Javascript. This function accepts parameters in decimal minutes.
Private Function calculateDistance(ByVal long1 As String, ByVal lat1 As String, ByVal long2 As String, ByVal lat2 As String) As Double
long1 = Double.Parse(long1)
lat1 = Double.Parse(lat1)
long2 = Double.Parse(long2)
lat2 = Double.Parse(lat2)
'conversion to radian
lat1 = (lat1 * 2.0 * Math.PI) / 60.0 / 360.0
long1 = (long1 * 2.0 * Math.PI) / 60.0 / 360.0
lat2 = (lat2 * 2.0 * Math.PI) / 60.0 / 360.0
long2 = (long2 * 2.0 * Math.PI) / 60.0 / 360.0
' use to different earth axis length
Dim a As Double = 6378137.0 ' Earth Major Axis (WGS84)
Dim b As Double = 6356752.3142 ' Minor Axis
Dim f As Double = (a - b) / a ' "Flattening"
Dim e As Double = 2.0 * f - f * f ' "Eccentricity"
Dim beta As Double = (a / Math.Sqrt(1.0 - e * Math.Sin(lat1) * Math.Sin(lat1)))
Dim cos As Double = Math.Cos(lat1)
Dim x As Double = beta * cos * Math.Cos(long1)
Dim y As Double = beta * cos * Math.Sin(long1)
Dim z As Double = beta * (1 - e) * Math.Sin(lat1)
beta = (a / Math.Sqrt(1.0 - e * Math.Sin(lat2) * Math.Sin(lat2)))
cos = Math.Cos(lat2)
x -= (beta * cos * Math.Cos(long2))
y -= (beta * cos * Math.Sin(long2))
z -= (beta * (1 - e) * Math.Sin(lat2))
Return Math.Sqrt((x * x) + (y * y) + (z * z))
End Function
Edit The converted function in javascript
function calculateDistance(lat1, long1, lat2, long2)
{
//radians
lat1 = (lat1 * 2.0 * Math.PI) / 60.0 / 360.0;
long1 = (long1 * 2.0 * Math.PI) / 60.0 / 360.0;
lat2 = (lat2 * 2.0 * Math.PI) / 60.0 / 360.0;
long2 = (long2 * 2.0 * Math.PI) / 60.0 / 360.0;
// use to different earth axis length
var a = 6378137.0; // Earth Major Axis (WGS84)
var b = 6356752.3142; // Minor Axis
var f = (a-b) / a; // "Flattening"
var e = 2.0*f - f*f; // "Eccentricity"
var beta = (a / Math.sqrt( 1.0 - e * Math.sin( lat1 ) * Math.sin( lat1 )));
var cos = Math.cos( lat1 );
var x = beta * cos * Math.cos( long1 );
var y = beta * cos * Math.sin( long1 );
var z = beta * ( 1 - e ) * Math.sin( lat1 );
beta = ( a / Math.sqrt( 1.0 - e * Math.sin( lat2 ) * Math.sin( lat2 )));
cos = Math.cos( lat2 );
x -= (beta * cos * Math.cos( long2 ));
y -= (beta * cos * Math.sin( long2 ));
z -= (beta * (1 - e) * Math.sin( lat2 ));
return (Math.sqrt( (x*x) + (y*y) + (z*z) )/1000);
}
I found a solution of my own. I know that Andras answer is probably the most consistent with MSTEST, but I didn't feel like refactoring my code.
[TestMethod]
public void OneIsOne()
{
using (ConsoleRedirector cr = new ConsoleRedirector())
{
Assert.IsFalse(cr.ToString().Contains("New text"));
/* call some method that writes "New text" to stdout */
Assert.IsTrue(cr.ToString().Contains("New text"));
}
}
The disposable ConsoleRedirector
is defined as:
internal class ConsoleRedirector : IDisposable
{
private StringWriter _consoleOutput = new StringWriter();
private TextWriter _originalConsoleOutput;
public ConsoleRedirector()
{
this._originalConsoleOutput = Console.Out;
Console.SetOut(_consoleOutput);
}
public void Dispose()
{
Console.SetOut(_originalConsoleOutput);
Console.Write(this.ToString());
this._consoleOutput.Dispose();
}
public override string ToString()
{
return this._consoleOutput.ToString();
}
}
double click the button and add write // this.close();
private void buttonClick(object sender, EventArgs e)
{
this.Close();
}
There are possible solutions here: http://forums.mysql.com/read.php?35,64808,254785#msg-254785 and here: http://forums.mysql.com/read.php?35,23138,254786#msg-254786
All of these are config settings. In my case I have two computers with everything in XAMPP synced. On the other computer phpMyAdmin did start normally. So the problem in my case seemed to be with the specific computer, not the config files. Stopping firewall didn't help.
Finally, more or less by accident, I bumped into the file:
...path_to_XAMPP\XAMPP...\mysql\bin\mysqld-debug.exe
Doubleclicking that file miraculously gave me back PhpMyAdmin. Posted here in case anyone might be helped by this too.
You could use a classmethod
or staticmethod
class Paul(object):
elems = []
@classmethod
def addelem(cls, e):
cls.elems.append(e)
@staticmethod
def addelem2(e):
Paul.elems.append(e)
Paul.addelem(1)
Paul.addelem2(2)
print(Paul.elems)
classmethod
has advantage that it would work with sub classes, if you really wanted that functionality.
module is certainly best though.
You should use the "siblings()" method, and prevent from running the ".content a" selector over and over again just for applying that effect:
HTML
<div class="content">
<a href="#">A</a>
</div>
<div class="content">
<a href="#">B</a>
</div>
<div class="content">
<a href="#">C</a>
</div>
CSS
.content {
background-color:red;
margin:10px;
}
.content.other {
background-color:yellow;
}
Javascript
$(".content a").click(function() {
var current = $(this).parent();
current.removeClass('other')
.siblings()
.addClass('other');
});
See here: http://jsfiddle.net/3bzLV/1/
What moves origin/HEAD "organically"?
git clone
sets it once to the spot where HEAD is on origin
git clone
What does HEAD on origin represent?
git clone
uses it in such a wayWhat sets origin/HEAD?
git clone
fetches and sets itgit fetch
updates it like any other reference, but it doesn’tgit remote set-head origin -a
fetches and sets it
Trivia
origin/HEAD
can also be set to any other value without contacting the remote: git remote set-head origin <branch>
SVG would be easier for you, since selection and moving it around is already built in. SVG objects are DOM objects, so they have "click" handlers, etc.
DIVs are okay but clunky and have awful performance loading at large numbers.
Canvas has the best performance hands-down, but you have to implement all concepts of managed state (object selection, etc) yourself, or use a library.
HTML5 Canvas is simply a drawing surface for a bit-map. You set up to draw (Say with a color and line thickness), draw that thing, and then the Canvas has no knowledge of that thing: It doesn't know where it is or what it is that you've just drawn, it's just pixels. If you want to draw rectangles and have them move around or be selectable then you have to code all of that from scratch, including the code to remember that you drew them.
SVG on the other hand must maintain references to each object that it renders. Every SVG/VML element you create is a real element in the DOM. By default this allows you to keep much better track of the elements you create and makes dealing with things like mouse events easier by default, but it slows down significantly when there are a large number of objects
Those SVG DOM references mean that some of the footwork of dealing with the things you draw is done for you. And SVG is faster when rendering really large objects, but slower when rendering many objects.
A game would probably be faster in Canvas. A huge map program would probably be faster in SVG. If you do want to use Canvas, I have some tutorials on getting movable objects up and running here.
Canvas would be better for faster things and heavy bitmap manipulation (like animation), but will take more code if you want lots of interactivity.
I've run a bunch of numbers on HTML DIV-made drawing versus Canvas-made drawing. I could make a huge post about the benefits of each, but I will give some of the relevant results of my tests to consider for your specific application:
I made Canvas and HTML DIV test pages, both had movable "nodes." Canvas nodes were objects I created and kept track of in Javascript. HTML nodes were movable Divs.
I added 100,000 nodes to each of my two tests. They performed quite differently:
The HTML test tab took forever to load (timed at slightly under 5 minutes, chrome asked to kill the page the first time). Chrome's task manager says that tab is taking up 168MB. It takes up 12-13% CPU time when I am looking at it, 0% when I am not looking.
The Canvas tab loaded in one second and takes up 30MB. It also takes up 13% of CPU time all of the time, regardless of whether or not one is looking at it. (2013 edit: They've mostly fixed that)
Dragging on the HTML page is smoother, which is expected by the design, since the current setup is to redraw EVERYTHING every 30 milliseconds in the Canvas test. There are plenty of optimizations to be had for Canvas for this. (canvas invalidation being the easiest, also clipping regions, selective redrawing, etc.. just depends on how much you feel like implementing)
There is no doubt you could get Canvas to be faster at object manipulation as the divs in that simple test, and of course far faster in the load time. Drawing/loading is faster in Canvas and has far more room for optimizations, too (ie, excluding things that are off-screen is very easy).
You can access any LayoutParams
from code using View.getLayoutParams
. You just have to be very aware of what LayoutParams
your accessing. This is normally achieved by checking the containing ViewGroup
if it has a LayoutParams
inner child then that's the one you should use. In your case it's RelativeLayout.LayoutParams
. You'll be using RelativeLayout.LayoutParams#addRule(int verb)
and RelativeLayout.LayoutParams#addRule(int verb, int anchor)
You can get to it via code:
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)button.getLayoutParams();
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.addRule(RelativeLayout.LEFT_OF, R.id.id_to_be_left_of);
button.setLayoutParams(params); //causes layout update
This is a self contained project so that you can see everything in context.
Create a layout like the following with a UIView
and a UIButton
. The UIView
will be the container in which we will play our video.
If you need a sample video to practice with, you can get one from sample-videos.com. I'm using an mp4 format video in this example. Drag and drop the video file into your project. I also had to add it explicitly into the bundle resources (go to Build Phases > Copy Bundle Resources, see this answer for more).
Here is the complete code for the project.
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player: AVPlayer?
@IBOutlet weak var videoViewContainer: UIView!
override func viewDidLoad() {
super.viewDidLoad()
initializeVideoPlayerWithVideo()
}
func initializeVideoPlayerWithVideo() {
// get the path string for the video from assets
let videoString:String? = Bundle.main.path(forResource: "SampleVideo_360x240_1mb", ofType: "mp4")
guard let unwrappedVideoPath = videoString else {return}
// convert the path string to a url
let videoUrl = URL(fileURLWithPath: unwrappedVideoPath)
// initialize the video player with the url
self.player = AVPlayer(url: videoUrl)
// create a video layer for the player
let layer: AVPlayerLayer = AVPlayerLayer(player: player)
// make the layer the same size as the container view
layer.frame = videoViewContainer.bounds
// make the video fill the layer as much as possible while keeping its aspect size
layer.videoGravity = AVLayerVideoGravity.resizeAspectFill
// add the layer to the container view
videoViewContainer.layer.addSublayer(layer)
}
@IBAction func playVideoButtonTapped(_ sender: UIButton) {
// play the video if the player is initialized
player?.play()
}
}
Notes
AVPlayerItem
.AVFoundation
and AVPlayer
, then you have to build all of your own controls. If you want full screen video playback, you can use AVPlayerViewController
. You will need to import AVKit
for that. It comes with a full set of controls for pause, fast forward, rewind, stop, etc. Here and here are some video tutorials.MPMoviePlayerController
that you may have seen in other answers is deprecated.The project should look like this now.
"Unable to find valid certification path to requested target"
If you are getting this message, you probably are behind a Proxy on your company, which probably is signing all request certificates with your company root CA certificate, this certificate is trusted only inside your company, so Android Studio cannot validate any certificate signed with your company certificate as valid, so, you need to tell Android Studio to trust your company certificate, you do that by adding your company certificate to Android Studio truststore.
(I'm doing this on macOS, but should be similar on Linux or Windows)
On the popup window, to save the root certificate as a file, make sure to select the top level of the certificates chain (the root cert) and drag the certificate image to a folder/directory on your disk drive. It should be saved as a file as, for example: my-root-ca-cert.cer, or my-root-ca-cert.pem
On Android Studio open Preferences -> Tools -> Server Certificates
,
on the box Accepted certificates
click the plus icon (+
), search the certificate you saved previously and click Apply
and OK
In Android Studio open File -> Project Structure -> SDK Location -> JDK Location
Copy the path of JDK Location, and open the Terminal, and change your directory to that path, for example, execute:
cd /Applications/Android\ Studio.app/Contents/jre/jdk/Contents/Home/
(don't forget to scape the whitespace, "\ ")
Now, to import the certificate to the truststore, execute:
./bin/keytool -importcert -file /path/to/your/certificate/my-root-ca-cert.cer -keystore ./jre/lib/security/cacerts -storepass changeit -noprompt
File -> Invalidate Caches / Restart
Done, you should be able to build your project now.
not exactly, but you may be able to accomplish what you need by invoking Collectors.groupingBy()
. you create a new Collection, and can then instantiate streams on that new collection.
First, your posted data isn't valid JSON. This would be:
{"value": "aériennes"}
Note the double quotes: They are required.
The Content-Type for JSON data should be application/json
. The actual JSON data (what we have above) should be encoded using UTF-8, UTF-16, or UTF-32 - I'd recommend using UTF-8.
You can use a tool like Wireshark to monitor network traffic and see how the data looks, you should see the bytes c3 89
for the é. I've never worked with Spring, but if it's doing the JSON encoding, this is probably taken care of properly, for you.
Once the JSON reaches the browser, it should good, if it is valid. However, how are you inserting the data from the JSON response into the webpage?
The problem is that you are using gulp 4 and the syntax in gulfile.js is of gulp 3. So either downgrade your gulp to 3.x.x or make use of gulp 4 syntaxes.
Syntax Gulp 3:
gulp.task('default', ['sass'], function() {....} );
Syntax Gulp 4:
gulp.task('default', gulp.series(sass), function() {....} );
You can read more about gulp and gulp tasks on: https://medium.com/@sudoanushil/how-to-write-gulp-tasks-ce1b1b7a7e81
How about the following one? Should allow you to use either raw_input or input in both Python2 and Python3 with the semantics of Python2's raw_input (aka the semantics of Python3's input)
# raw_input isn't defined in Python3.x, whereas input wasn't behaving like raw_input in Python 2.x
# this should make both input and raw_input work in Python 2.x/3.x like the raw_input from Python 2.x
try: input = raw_input
except NameError: raw_input = input
The way to get the selection of the spinner is:
spinner1.getSelectedItemPosition();
Documentation reference: http://developer.android.com/reference/android/widget/AdapterView.html#getSelectedItemPosition()
However, in your code, the one place you are referencing it is within your setOnItemSelectedListener()
. It is not necessary to poll the spinner, because the onItemSelected
method gets passed the position as the "position" variable.
So you could change that line to:
TestProjectActivity.this.number = position + 1;
If that does not fix the problem, please post the error message generated when your app crashes.
<option name="workOffline" value="true" />
in workspace.xml
is not your friend. Advise to check this before deleting your .idea
(which has a lot of useful settings you probably don't want to lose)
It's a maven workspace.xml
setting
Here is one way to “untrack” any files that are would otherwise be ignored under the current set of exclude patterns:
(GIT_INDEX_FILE=some-non-existent-file \
git ls-files --exclude-standard --others --directory --ignored -z) |
xargs -0 git rm --cached -r --ignore-unmatch --
This leaves the files in your working directory but removes them from the index.
The trick used here is to provide a non-existent index file to git ls-files so that it thinks there are no tracked files. The shell code above asks for all the files that would be ignored if the index were empty and then removes them from the actual index with git rm.
After the files have been “untracked”, use git status to verify that nothing important was removed (if so adjust your exclude patterns and use git reset -- path to restore the removed index entry). Then make a new commit that leaves out the “crud”.
The “crud” will still be in any old commits. You can use git filter-branch to produce clean versions of the old commits if you really need a clean history (n.b. using git filter-branch will “rewrite history”, so it should not be undertaken lightly if you have any collaborators that have pulled any of your historical commits after the “crud” was first introduced).
I found this post when I started wondering about the easiest way to implement
rot13
into Python myself. My goals were:
This meets all three of those requirements. That being said, I'm sure it's not winning any code golf competitions.
def rot13(string):
CLEAR = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
ROT13 = 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm'
TABLE = {x: y for x, y in zip(CLEAR, ROT13)}
return ''.join(map(lambda x: TABLE.get(x, x), string))
if __name__ == '__main__':
CLEAR = 'Hello, World!'
R13 = 'Uryyb, Jbeyq!'
r13 = rot13(CLEAR)
assert r13 == R13
clear = rot13(r13)
assert clear == CLEAR
This works by creating a lookup table and simply returning the original character for any character not found in the lookup table.
I got to worrying about someone wanting to use this to encrypt an arbitrarily-large file (say, a few gigabytes of text). I don't know why they'd want to do this, but what if they did? So I rewrote it as a generator. Again, this has been tested in both Python 2.7.6 and 3.3.
def rot13(clear):
CLEAR = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
ROT13 = 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm'
TABLE = {x: y for x, y in zip(CLEAR, ROT13)}
for c in clear:
yield TABLE.get(c, c)
if __name__ == '__main__':
CLEAR = 'Hello, World!'
R13 = 'Uryyb, Jbeyq!'
r13 = ''.join(rot13(CLEAR))
assert r13 == R13
clear = ''.join(rot13(r13))
assert clear == CLEAR
Although this is an old question, I think none has already answered using this approach:
# python 2.7
import os
d='/home/me/test'
filesToRemove = [os.path.join(d,f) for f in os.listdir(d)]
for f in filesToRemove:
os.remove(f)
From the npm docs:
git://github.com/<user>/<project>.git#<branch>
git://github.com/<user>/<project>.git#feature\/<branch>
As of NPM version 1.1.65, you can do this:
<user>/<project>#<branch>
If you want to open it for a range and for a protocol
ufw allow 11200:11299/tcp
ufw allow 11200:11299/udp
Example for CoffeeScript
:
test = (str, callback) ->
data = "Input values"
$.ajax
type: "post"
url: "http://www.mydomain.com/ajaxscript"
data: data
success: callback
test (data, textStatus, xhr) ->
alert data + "\t" + textStatus
Go to the directory manually and do right click → Select 'Git bash' option.
Git bash terminal automatically opens with the intended directory. For example, go to your project folder. While in the folder, right click and select the option and 'Git bash'. It will open automatically with /c/project
.
try this example
function toggleRed() {_x000D_
var text = $('.editable').text();_x000D_
$('.editable').html('<p style="color:red">' + text + '</p>');_x000D_
}_x000D_
_x000D_
function toggleItalic() {_x000D_
var text = $('.editable').text();_x000D_
$('.editable').html("<i>" + text + "</i>");_x000D_
}_x000D_
_x000D_
$('.bold').click(function() {_x000D_
toggleRed();_x000D_
});_x000D_
_x000D_
$('.italic').click(function() {_x000D_
toggleItalic();_x000D_
});
_x000D_
.editable {_x000D_
width: 300px;_x000D_
height: 200px;_x000D_
border: 1px solid #ccc;_x000D_
padding: 5px;_x000D_
resize: both;_x000D_
overflow: auto;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="editable" contenteditable="true"></div>_x000D_
<button class="bold">toggle red</button>_x000D_
<button class="italic">toggle italic</button>
_x000D_
Webkit is the html/css rendering engine used in Apple's Safari browser, and in Google's Chrome. css values prefixes with -webkit- are webkit-specific, they're usually CSS3 or other non-standardised features.
to answer update 2 w3c is the body that tries to standardize these things, they write the rules, then programmers write their rendering engine to interpret those rules. So basically w3c says DIVs should work "This way" the engine-writer then uses that rule to write their code, any bugs or mis-interpretations of the rules cause the compatibility issues.
Is date_field
of type datetime
? Also you need to put the eariler date first.
It should be:
SELECT * FROM `objects`
WHERE (date_field BETWEEN '2010-01-30 14:15:55' AND '2010-09-29 10:15:55')
Now there is the pandas_profiling
package, which is a more complete alternative to df.describe()
.
If your pandas dataframe is df
, the below will return a complete analysis including some warnings about missing values, skewness, etc. It presents histograms and correlation plots as well.
import pandas_profiling
pandas_profiling.ProfileReport(df)
See the example notebook detailing the usage.
For posterity, I'd like to note that I ended up choosing Raphael, because of the clean API and "free" IE support, and also because the active development looks promising (event support was just added in 0.7, for instance). However, I'll leave the question unanswered, and I'd still be interested to hear about others' experiences using Javascript + SVG libraries.
Kasperd asked in a comment of the accepted answer:
The Java and C examples use quite different register names. Are both example using the AMD64 ISA?
xor edx, edx
xor eax, eax
.L2:
mov ecx, edx
imul ecx, edx
add edx, 1
lea eax, [rax+rcx*2]
cmp edx, 1000000000
jne .L2
I don't have enough reputation to answer this in the comments, but these are the same ISA. It's worth pointing out that the GCC version uses 32-bit integer logic and the JVM compiled version uses 64-bit integer logic internally.
R8 to R15 are just new X86_64 registers. EAX to EDX are the lower parts of the RAX to RDX general purpose registers. The important part in the answer is that the GCC version is not unrolled. It simply executes one round of the loop per actual machine code loop. While the JVM version has 16 rounds of the loop in one physical loop (based on rustyx answer, I did not reinterpret the assembly). This is one of the reasons why there are more registers being used since the loop body is actually 16 times longer.
With an OR
(||) operation, if any one of the conditions are true, the result is true.
I think you want an AND
(&&) operation here.
select *
from
(
( select * from TableInSchema1
minus
select * from TableInSchema2)
union all
( select * from TableInSchema2
minus
select * from TableInSchema1)
)
should do the trick if you want to solve this with a query
My case:
www.mycompany.com/api/ws
...localhost:8000
). Setting document.cookie = "sessionid=foobar;path=/"
won't help as domains don't match.
The solution:
Add 127.0.0.1 wsdev.company.com
to /etc/hosts
.
This way your browser will use cookies from mycompany.com
when connecting to www.mycompany.com/api/ws
as you are connecting from a valid subdomain wsdev.company.com
.
The easiest is setting a program variable (see GDB: assignment):
(gdb) l
6 {
7 int i;
8 struct file *f, *ftmp;
9
(gdb) set variable i = 10
(gdb) p i
$1 = 10
Or you can just update arbitrary (writable) location by address:
(gdb) set {int}0x83040 = 4
There's more. Read the manual.
I found 2 suggestions elsewhere via Google that suggested a) making sure your db connectionstring (the one that Roles is using) is correct and that the key to it is spelled correctly, and b) that the Enabled flag on RoleManager is set to true. Hope one of those helps. It did for me.
Did you try checking Roles.Enabled? Also, you can check Roles.Providers to see how many providers are available and you can check the Roles.Provider for the default provider. If it is null then there isn't one.
Put the assets folder in the main/src/assets
path.
When you use a code like this:
using (var rsa = new RSACryptoServiceProvider(1024))
{
// Do something with the key...
// Encrypt, export, etc.
}
.NET (actually Windows) stores your key in a persistent key container forever. The container is randomly generated by .NET
This means:
Any random RSA/DSA key you have EVER generated for the purpose of protecting data, creating custom X.509 certificate, etc. may have been exposed without your awareness in the Windows file system. Accessible by anyone who has access to your account.
Your disk is being slowly filled with data. Normally not a big concern but it depends on your application (e.g. it might generates hundreds of keys every minute).
To resolve these issues:
using (var rsa = new RSACryptoServiceProvider(1024))
{
try
{
// Do something with the key...
// Encrypt, export, etc.
}
finally
{
rsa.PersistKeyInCsp = false;
}
}
ALWAYS
IF your data won't overflow 4000 characters AND you're on SQL Server 2000 or compatibility level of 8 or SQL Server 2000:
UPDATE [CMS_DB_test].[dbo].[cms_HtmlText]
SET Content = CAST(REPLACE(CAST(Content as NVarchar(4000)),'ABC','DEF') AS NText)
WHERE Content LIKE '%ABC%'
For SQL Server 2005+:
UPDATE [CMS_DB_test].[dbo].[cms_HtmlText]
SET Content = CAST(REPLACE(CAST(Content as NVarchar(MAX)),'ABC','DEF') AS NText)
WHERE Content LIKE '%ABC%'
Up until JDK6, you could use a static initializer block to print the message. This way, as soon as your class is loaded the message will be printed. The trick then becomes using another program to load your class.
public class Hello {
static {
System.out.println("Hello, World!");
}
}
Of course, you can run the program as java Hello
and you will see the message; however, the command will also fail with a message stating:
Exception in thread "main" java.lang.NoSuchMethodError: main
[Edit] as noted by others, you can avoid the NoSuchmethodError by simply calling System.exit(0)
immediately after printing the message.
As of JDK6 onward, you no longer see the message from the static
initializer block; details here.
According to the above answers setdefault() method worked for me.
old_attr_name = mydict.setdefault(key, attr_name)
if attr_name != old_attr_name:
raise RuntimeError(f"Key '{key}' duplication: "
f"'{old_attr_name}' and '{attr_name}'.")
Though this solution is not generic. Just suited me in this certain case. The exact solution would be checking for the key
first (as was already advised), but with setdefault()
we avoid one extra lookup on the dictionary, that is, though small, but still a performance gain.
Yes it stops execution so this is generally preferable to HAVING COUNT(*) > 0
which often won't.
With EXISTS
if you look at the execution plan you will see that the actual number of rows coming out of table1
will not be more than 1 irrespective of number of matching records.
In some circumstances SQL Server can convert the tree for the COUNT
query to the same as the one for EXISTS
during the simplification phase (with a semi join and no aggregate operator in sight) an example of that is discussed in the comments here.
For more complicated sub trees than shown in the question you may occasionally find the COUNT
performs better than EXISTS
however. Because the semi join needs only retrieve one row from the sub tree this can encourage a plan with nested loops for that part of the tree - which may not work out optimal in practice.
You can use this
TextView output = (TextView) findViewById(R.id.output);
one.setOnClickListener(youractivity.this);
// set the onclicklistener for other buttons also
@Override
public void onClick(View v) {
int id = v.getId();
switch(id) {
case R.id.oneButton:
append("1",output);
break;
case R.id.twoButton:
append("2",output);
break;
case R.id.threeButton:
append("3",output);
break;
}
}
private void append(String s,TextView t){
t.setText(s);
}
you can identify the views in your activity in a separate method.
Managed to get the input field value by doing something like this:
import React, { Component } from 'react';
class App extends Component {
constructor(props){
super(props);
this.state = {
username : ''
}
this.updateInput = this.updateInput.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
updateInput(event){
this.setState({username : event.target.value})
}
handleSubmit(){
console.log('Your input value is: ' + this.state.username)
//Send state to the server code
}
render(){
return (
<div>
<input type="text" onChange={this.updateInput}></input>
<input type="submit" onClick={this.handleSubmit} ></input>
</div>
);
}
}
//output
//Your input value is: x
Try with these:
virtualenv -p /usr/bin/python3 test_env
source test_env/bin/activate
pip install psycopg2
run python and try to import if you insist on installing it on your systems python try:
pip3 install psycopg2
I have same problem, because i don't have keystore path then i see Waffles.inc solutions and had a new problem In my Android Studio 3.1 for mac had a windows dialog problem when trying create new keystore path, it's like this
if u have the same problem, don't worried about the black windows it's just typing your new keystore and then save.
Once I had to make the same decision and I'm really happy with that decision today. Use resque scheduler because not only a seperate redis will take out the load from your db, you will also have access to many plugins like resque-web which provides a great user interface. As your system develops you will have more and more tasks to schedule so you will be able to control them from a single place.
Maybe you are using:
$(document).ready(function(){
// Your code here
});
Try this instead:
window.onload = function(){ }
If you need a CakePHP Docker Container with MySQL, I have created a Docker image for that purpose! No need to worry about setting it up. It just works!
Here's how I installed in Ubuntu-based image:
https://github.com/marcellodesales/php-apache-mysql-4-cakephp-docker/blob/master/Dockerfile#L8
RUN docker-php-ext-install mysql mysqli pdo pdo_mysql
Building and running your application is just a 2 step process (considering you are in the current directory of the app):
$ docker build -t myCakePhpApp .
$ docker run -ti myCakePhpApp
The vshost.exe file is the executable run by Visual Studio (Visual Studio host executable). This is the executable that links to Visual Studio and improves debugging.
When you're distributing your application to others, you do not use the vshost.exe or .pdb (debug database) files.
launchMode = "singleInstance"
FirstActivity.fa.finish();
and call the new Intent.Not jQuery
, as the question asks for, but natively (i.e., no libraries required) I think the better tool for the job is querySelector
to get a single instance of a selector:
let el = document.querySelector('img');
console.log(el);
For all matching instances, use document.querySelectorAll()
, or for those within another element you can chain as follows:
// Get some wrapper, with class="parentClassName"
let parentEl = document.querySelector('.parentClassName');
// Get all img tags within the parent element by parentEl variable
let childrenEls = parentEl.querySelectorAll('img');
Note the above is equivalent to:
let childrenEls = document.querySelector('.parentClassName').querySelectorAll('img');
I have made a jsfiddle for you.
<canvas id="canvas" width="480" height="320"></canvas>
<button id="download">Download Pdf</button>
'
html2canvas($("#canvas"), {
onrendered: function(canvas) {
var imgData = canvas.toDataURL(
'image/png');
var doc = new jsPDF('p', 'mm');
doc.addImage(imgData, 'PNG', 10, 10);
doc.save('sample-file.pdf');
}
});
jsfiddle: http://jsfiddle.net/rpaul/p4s5k59s/5/
Tested in Chrome38, IE11 and Firefox 33. Seems to have issues with Safari. However, Andrew got it working in Safari 8 on Mac OSx by switching to JPEG from PNG. For details, see his comment below.
As far as I know, Javascript has dynamic arrays. You can add,delete and modify the elements on the fly.
var myArray = [1,2,3,4,5,6,7,8,9,10];
myArray.push(11);
document.writeln(myArray); // Gives 1,2,3,4,5,6,7,8,9,10,11
var myArray = [1,2,3,4,5,6,7,8,9,10];
var popped = myArray.pop();
document.writeln(myArray); // Gives 1,2,3,4,5,6,7,8,9
You can even add elements like
var myArray = new Array()
myArray[0] = 10
myArray[1] = 20
myArray[2] = 30
you can even change the values
myArray[2] = 40
If you want in the same order, this would suffice. Javascript prints the values in the order of key values. If you have inserted values in the array in monotonically increasing key values, then they will be printed in the same way unless you want to change the order.
If you are using JavaScript you don't even need to submit the values to the different page. You can even show the data on the same page by manipulating the DOM.
This seems to work:
$("#theSelect").change(function(){
var value = $("#theSelect option:selected").val();
var theDiv = $(".is" + value);
theDiv.slideDown().removeClass("hidden");
//Add this...
$("#theSelect option:selected").attr('disabled', 'disabled');
});
$("div a.remove").click(function () {
$(this).parent().slideUp(function() { $(this).addClass("hidden"); });
//...and this.
$("#theSelect option:disabled").removeAttr('disabled');
});
I couldn't be more concise than this. For all your other needs and information, Google is your friend.
Here is simple code snippet working for AES Encryption and Decryption.
import android.util.Base64;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
public class AESEncryptionClass {
private static String INIT_VECTOR_PARAM = "#####";
private static String PASSWORD = "#####";
private static String SALT_KEY = "#####";
private static SecretKeySpec generateAESKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
// Prepare password and salt key.
char[] password = new String(Base64.decode(PASSWORD, Base64.DEFAULT)).toCharArray();
byte[] salt = new String(Base64.decode(SALT_KEY, Base64.DEFAULT)).getBytes(StandardCharsets.UTF_8);
// Create object of [Password Based Encryption Key Specification] with required iteration count and key length.
KeySpec spec = new PBEKeySpec(password, salt, 64, 256);
// Now create AES Key using required hashing algorithm.
SecretKey key = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(spec);
// Get encoded bytes of secret key.
byte[] bytesSecretKey = key.getEncoded();
// Create specification for AES Key.
SecretKeySpec secretKeySpec = new SecretKeySpec(bytesSecretKey, "AES");
return secretKeySpec;
}
/**
* Call this method to encrypt the readable plain text and get Base64 of encrypted bytes.
*/
public static String encryptMessage(String message) throws BadPaddingException, IllegalBlockSizeException, NoSuchPaddingException, NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException, InvalidAlgorithmParameterException, InvalidKeyException {
byte[] initVectorParamBytes = new String(Base64.decode(INIT_VECTOR_PARAM, Base64.DEFAULT)).getBytes(StandardCharsets.UTF_8);
Cipher encryptionCipherBlock = Cipher.getInstance("AES/CBC/PKCS5Padding");
encryptionCipherBlock.init(Cipher.ENCRYPT_MODE, generateAESKey(), new IvParameterSpec(initVectorParamBytes));
byte[] messageBytes = message.getBytes();
byte[] cipherTextBytes = encryptionCipherBlock.doFinal(messageBytes);
String encryptedText = Base64.encodeToString(cipherTextBytes, Base64.DEFAULT);
return encryptedText;
}
/**
* Call this method to decrypt the Base64 of encrypted message and get readable plain text.
*/
public static String decryptMessage(String base64Cipher) throws BadPaddingException, IllegalBlockSizeException, NoSuchPaddingException, NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException, InvalidAlgorithmParameterException, InvalidKeyException {
byte[] initVectorParamBytes = new String(Base64.decode(INIT_VECTOR_PARAM, Base64.DEFAULT)).getBytes(StandardCharsets.UTF_8);
Cipher decryptionCipherBlock = Cipher.getInstance("AES/CBC/PKCS5Padding");
decryptionCipherBlock.init(Cipher.DECRYPT_MODE, generateAESKey(), new IvParameterSpec(initVectorParamBytes));
byte[] cipherBytes = Base64.decode(base64Cipher, Base64.DEFAULT);
byte[] messageBytes = decryptionCipherBlock.doFinal(cipherBytes);
String plainText = new String(messageBytes);
return plainText;
}
}
Now, call
encryptMessage()
ordecryptMessage()
for desiredAES
Operation with required parameters.Also, handle the exceptions during
AES
operations.
Hope it helped...
The namespace in your config should reflect the rest of the namespace path after your client's default namespace (as configured in the project properties). Based on your posted answer, my guess is that your client is configured to be in the "Fusion.DataExchange.Workflows" namespace. If you moved the client code to another namespace you would need to update the config to match the remaining namespace path.
Adding MaxHeight
and VerticalScrollBarVisibility="Auto"
on the DataGrid
solved my problem.
If you want to match starting from the beginning of the word, use:
\b\w{3,}
\b: word boundary
\w: word character
{3,}: three or more times for the word character
simple write in your bat file
@cmd
or
@cmd /k "command1&command2"
public static object GetDefault(Type type)
{
if(type.IsValueType)
{
return Activator.CreateInstance(type);
}
return null;
}
In the newer version of .net such as .net standard, type.IsValueType
needs to be written as type.GetTypeInfo().IsValueType
Neither databases, nor tablespaces nor data files belong to any user. Are you coming to this from an MS SQL background?
select tablespace_name,
file_name
from dba_tablespaces
order by tablespace_name,
file_name;
If you have to load a lot of data into tables on a regular basis, check out SQL Loader or external tables. Should be much faster than individual Inserts.
<script type="text/javascript" runat="server">
public void Page_Load(object Sender, System.EventArgs e)
{
double rad=0.0;
TextBox1.Attributes.Add("Visible", "False");
if (TextBox1.Text != "")
rad = Convert.ToDouble(TextBox1.Text);
Button1.Attributes.Add("OnClick","alert("+ rad +")");
}
</script>
<asp:Button ID="Button1" runat="server" Text="Diameter"
style="z-index: 1; left: 133px; top: 181px; position: absolute" />
<asp:TextBox ID="TextBox1" Visible="True" Text="" runat="server"
AutoPostBack="true"
style="z-index: 1; left: 134px; top: 133px; position: absolute" ></asp:TextBox>
use the help of this, hope it will be usefull
Define the expected and desired output for a normal case, with correct input.
Now, implement the test by declaring a class, name it anything (Usually something like TestAddingModule), and add the testAdd method to it (i.e. like the one below) :
assertEquals(expectedVal,calculatedVal)
.Test your method by running it (in Eclipse, right click, select Run as ? JUnit test).
//for normal addition
@Test
public void testAdd1Plus1()
{
int x = 1 ; int y = 1;
assertEquals(2, myClass.add(x,y));
}
Add other cases as desired.
Test that your method handles Null inputs gracefully (example below).
//if you are using 0 as default for null, make sure your class works in that case.
@Test
public void testAdd1Plus1()
{
int y = 1;
assertEquals(0, myClass.add(null,y));
}
Everything is cool, man. The 'u' is a good thing, it indicates that the string is of type Unicode in python 2.x.
http://docs.python.org/2/howto/unicode.html#the-unicode-type
I have just experienced this issue in one of my MySQL db's and I looked at the phpMyAdmin answer here. However the best way I fixed it in phpMyAdmin was in the affected table, drop the id column and make a fresh/new id column (adding A-I -autoincrement-). This restored my table id correctly-simples! Hope that helps (no MySQL code needed-I hope to learn to use that but later!) anyone else with this problem.
Go to properties of your project ( with Alt+Enter or righ-click )
check on Apache Tomcat v7.0 under Targeted Runtime and it works.
The Dimensions of my input array were skewed, as my input csv had empty spaces.
func post() {
NotificationCenter.default.post(name: Notification.Name("SomeNotificationName"),
object: nil,
userInfo:["key0": "value", "key1": 1234])
}
func addObservers() {
NotificationCenter.default.addObserver(self,
selector: #selector(someMethod),
name: Notification.Name("SomeNotificationName"),
object: nil)
}
@objc func someMethod(_ notification: Notification) {
let info0 = notification.userInfo?["key0"]
let info1 = notification.userInfo?["key1"]
}
Replace Notification.Name("SomeNotificationName")
with .someNotificationName
:
extension Notification.Name {
static let someNotificationName = Notification.Name("SomeNotificationName")
}
Replace "key0"
and "key1"
with Notification.Key.key0
and Notification.Key.key1
:
extension Notification {
enum Key: String {
case key0
case key1
}
}
Why should I definitely do this ? To avoid costly typo errors, enjoy renaming, enjoy find usage etc...
Chrome has a very nice feature called 'USB Web debugging' which allows to see the mobile device's debug console on your PC when connected via USB.
EDIT: Seems that the ADB is not supported on Windows 8, but this link seems to provide a solution:
http://mikemurko.com/general/chrome-remote-debugging-nexus-7-on-windows-8/
If you start eclipse using oracle java, then eclipse might fail in finding native libraries like SWT or SVN libraries. The SWT-JNI libraries are located in /usr/lib/jni/ and the SVN-JNI libraries are located in /usr/lib/x86_64-linux-gnu/jni/.
Instead of starting eclipse with the command
eclipse
you can use the command
env LD_LIBRARY_PATH=/usr/lib/jni/:/usr/lib/x86_64-linux-gnu/jni/:$LD_LIBRARY_PATH eclipse
to pass the environment variable LD_LIBRARY_PATH to eclipse. Eclipse will find the native libraries and will run properly.
you can do this using ReflectionTestUtils of Spring (org.springframework.test.util.ReflectionTestUtils)
ReflectionTestUtils.invokeMethod(instantiatedObject,"methodName",argument);
Example : if you have a class with a private method square(int x)
Calculator calculator = new Calculator();
ReflectionTestUtils.invokeMethod(calculator,"square",10);
You can use the ternary operator easily:
{{ $usersType ? $usersType : '' }}
-w
is the GCC-wide option to disable warning messages.
I think the following is a good exhibit of Echo vs. Write-Host. Notice how test() actually returns an array of ints, not a single int as one could easily be led to believe.
function test {
Write-Host 123
echo 456 # AKA 'Write-Output'
return 789
}
$x = test
Write-Host "x of type '$($x.GetType().name)' = $x"
Write-Host "`$x[0] = $($x[0])"
Write-Host "`$x[1] = $($x[1])"
Terminal output of the above:
123
x of type 'Object[]' = 456 789
$x[0] = 456
$x[1] = 789
When you change attribute value like mentioned above the change
event is not triggered so if needed for some reasons you can trigger it like so
$('input[name=video_radio][value="' + r.data.video_radio + '"]')
.prop('checked', true)
.trigger('change');
You can use the function RESHAPE:
B = reshape(A.',1,[]);
I have recently faced the same issue. I wrote the following code:
$('html').click(function(e) {
var a = e.target;
if ($(a).parents('.menu_container').length === 0) {
$('.ofSubLevelLinks').removeClass('active'); //hide menu item
$('.menu_container li > img').hide(); //hide dropdown image, if any
}
});
It has worked for me perfectly.
String currency = "135.69";
System.out.println(new BigDecimal(currency));
//will print 135.69
Simply put it will define a setter and getter for the class.
Note that
attr_reader :v is equivalant to
def v
@v
end
attr_writer :v is equivalant to
def v=(value)
@v=value
end
So
attr_accessor :v which means
attr_reader :v; attr_writer :v
are equivalant to define a setter and getter for the class.
I had a conditional break point wrongly put on the method entry point. Removed that breakpoint and it worked.
Note: Tried Skip all Breakpoints, Clean all projects, Refresh, close Eclipse with no luck before nailing it.
Find highest number, including negative:
return max([abs(max($array)),abs(min($array))]);
We can easy to upload multiple files using php by using the below script.
Download Full Source code and preview
<?php
if (isset($_POST['submit'])) {
$j = 0; //Variable for indexing uploaded image
$target_path = "uploads/"; //Declaring Path for uploaded images
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array
$validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed
$ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.)
$file_extension = end($ext); //store extensions in the variable
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];//set the target path with a new name of image
$j = $j + 1;//increment the number of uploaded images according to the files in array
if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder
echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
} else {//if file was not moved.
echo $j. ').<span id="error">please try again!.</span><br/><br/>';
}
} else {//if file size and file type was incorrect.
echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
}
}
?>
Without configuring your math environment to clip, you could force a new line with two backslashes in a sequence like this:
Bla Bla \\ Bla Bla in another line
The problem with this is that you will need to determine where a line is likely to end and force to always have a line break there. With equations, rather than text, I prefer this manual way.
You could also use \\*
to prevent a new page from being started.
if you just want to show the file itself:
header('Content-Type: text/plain');
header('Content-Disposition: inline; filename="filename.txt"');
readfile(path);
It is actually really simple to understand, you can even compute it with the google calculator: you have 32 bits for an int and computers are binary, therefore you can have 2 values per bit (spot). if you compute 2^32 you will get the 4,294,967,296. so if you divide this number by 2, (because half of them are negative integers and the other half are positive), then you get 2,147,483,648. and this number is the biggest int that can be represented by 32 bits, although if you pay attention you will notice that 2,147,483,648 is greater than 2,147,483,647 by 1, this is because one of the numbers represents 0 which is right in the middle unfortunately 2^32 is not an odd number therefore you dont have only one number in the middle, so the possitive integers have one less cipher while the negatives get the complete half 2,147,483,648.
And thats it. It depends on the machine not on the language.
This is commonly reported as an error due to using the wrong version of SSMS(Sql Server Management Studio). Use the version designed for your database version. You can use the command select @@version
to check which version of sql server you are actually using. This version is reported in a way that is easier to interpret than that shown in the Help About in SSMS.
Using a newer version of SSMS than your database is generally error-free, i.e. backward compatible.
This one-liner works for me:
WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultNetworkCredentials;
CredentialCache.DefaultNetWorkCredentials
is the proxy settings set in Internet Explorer.
WebRequest.DefaultWebProxy.Credentials
is used for all internet connectivity in the application.
first, create a class to hold your parameters:
public class PkRk {
public int pk { get; set; }
public int rk { get; set; }
}
then, use the Html.Action
passing the parameters:
Html.Action("PkRkAction", new { pkrk = new PkRk { pk=400, rk=500} })
and use in Controller:
public ActionResult PkRkAction(PkRk pkrk) {
return PartialView(pkrk);
}
Your system can have many different tomcat versions. You can try to solve it.
Right Click on Project then Select Properties, Select Project Facets and on the right section, Select right Apache Tomcat versions as Runtimes and click ok
I'd like to throw in an answer that addresses "When not to use it" as it hasn't been covered yet and can imagine it being used blindly and no one noticing the there is a problem till later down the line. Some of this contradicts some of the existing answers somewhat.
If outputting to a webpage in HTML, particularly text in <textarea>
, <pre>
or <code>
you probably always want to use \n
and not PHP_EOL
.
The reason for this is that while code may work perform well on one sever - which happens to be a Unix-like platform - if deployed on a Windows host (such the Windows Azure platform) then it may alter how pages are displayed in some browsers (specifically Internet Explorer - some versions of which will see both the \n and \r).
I'm not sure if this is still an issue since IE6 or not, so it might be fairly moot but seems worth mentioning if it helps people prompt to think about the context. There might be other cases (such as strict XHTML) where suddently outputting \r
's on some platforms could cause problems with the output, and I'm sure there are other edge cases like that.
As noted by someone already, you wouldn't want to use it when returning HTTP headers - as they should always follow the RFC on any platform.
I wouldn't use it for something like delimiters on CSV files (as someone has suggested). The platform the sever is running on shouldn't determine the line endings in generated or consumed files.
Although the question refers to only PhoneGap and iOS usage, and although it was already answered, I can add a few points to the broader question of detecting screen orientation with JS in 2019:
window.orientation
property is deprecated and not supported by Android browsers.There is a newer property that provides more information about the orientation - screen.orientation
. But it is still experimental and not supported by iOS Safari. So to achieve the best result you probably need to use the combination of the two: const angle = screen.orientation ? screen.orientation.angle : window.orientation
.
As @benallansmith mentioned in his comment, window.onorientationchange
event is fired before window.onresize
, so you won't get the actual dimensions of the screen unless you add some delay after the orientationchange event.
There is a Cordova Screen Orientation Plugin for supporting older mobile browsers, but I believe there is no need in using it nowadays.
There was also a screen.onorientationchange
event, but it is deprecated and should not be used. Added just for completeness of the answer.
In my use-case, I didn't care much about the actual orientation, but rather about the actual width and height of the window, which obviously changes with orientation. So I used resize
event to avoid dealing with delays between orientationchange
event and actualizing window dimensions:
window.addEventListener('resize', () => {
console.log(`Actual dimensions: ${window.innerWidth}x${window.innerHeight}`);
console.log(`Actual orientation: ${screen.orientation ? screen.orientation.angle : window.orientation}`);
});
Note 1: I used EcmaScript 6 syntax here, make sure to compile it to ES5 if needed.
Note 2: window.onresize
event is also fired when virtual keyboard is toggled, not only when orientation changes.
If you're using a UINavigationController
, you can use an extension like this:
extension UINavigationController {
private struct AssociatedKeys {
static var navigationBarBackgroundViewName = "NavigationBarBackground"
}
var navigationBarBackgroundView: UIView? {
get {
return objc_getAssociatedObject(self,
&AssociatedKeys.navigationBarBackgroundViewName) as? UIView
}
set(newValue) {
objc_setAssociatedObject(self,
&AssociatedKeys.navigationBarBackgroundViewName,
newValue,
.OBJC_ASSOCIATION_RETAIN)
}
}
func setNavigationBar(hidden isHidden: Bool, animated: Bool = false) {
if animated {
UIView.animate(withDuration: 0.3) {
self.navigationBarBackgroundView?.isHidden = isHidden
}
} else {
navigationBarBackgroundView?.isHidden = isHidden
}
}
func setNavigationBarBackground(color: UIColor, includingStatusBar: Bool = true, animated: Bool = false) {
navigationBarBackgroundView?.backgroundColor = UIColor.clear
navigationBar.backgroundColor = UIColor.clear
navigationBar.barTintColor = UIColor.clear
let setupOperation = {
if includingStatusBar {
self.navigationBarBackgroundView?.isHidden = false
if self.navigationBarBackgroundView == nil {
self.setupBackgroundView()
}
self.navigationBarBackgroundView?.backgroundColor = color
} else {
self.navigationBarBackgroundView?.isHidden = true
self.navigationBar.backgroundColor = color
}
}
if animated {
UIView.animate(withDuration: 0.3) {
setupOperation()
}
} else {
setupOperation()
}
}
private func setupBackgroundView() {
var frame = navigationBar.frame
frame.origin.y = 0
frame.size.height = 64
navigationBarBackgroundView = UIView(frame: frame)
navigationBarBackgroundView?.translatesAutoresizingMaskIntoConstraints = true
navigationBarBackgroundView?.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin]
navigationBarBackgroundView?.isUserInteractionEnabled = false
view.insertSubview(navigationBarBackgroundView!, aboveSubview: navigationBar)
}
}
It basically makes the navigation bar background transparent and uses another UIView as the background. You can call the setNavigationBarBackground
method of your navigation controller to set the navigation bar background color together with the status bar.
Keep in mind that you have to then use the setNavigationBar(hidden: Bool, animated: Bool)
method in the extension when you want to hide the navigation bar otherwise the view that was used as the background will still be visible.
I think this is enough to get you on a nice path:
Sub a()
Dim btn As Button
Application.ScreenUpdating = False
ActiveSheet.Buttons.Delete
Dim t As Range
For i = 2 To 6 Step 2
Set t = ActiveSheet.Range(Cells(i, 3), Cells(i, 3))
Set btn = ActiveSheet.Buttons.Add(t.Left, t.Top, t.Width, t.Height)
With btn
.OnAction = "btnS"
.Caption = "Btn " & i
.Name = "Btn" & i
End With
Next i
Application.ScreenUpdating = True
End Sub
Sub btnS()
MsgBox Application.Caller
End Sub
It creates the buttons and binds them to butnS(). In the btnS() sub, you should show your dialog, etc.
The core of async programming is the Task and Task objects, which model asynchronous operations. They are supported by the async and await keywords. The model is fairly simple in most cases:
For I/O-bound code, you await an operation which returns a Task or Task inside of an async method.
For CPU-bound code, you await an operation which is started on a background thread with the Task.Run method.
The await keyword is where the magic happens. It yields control to the caller of the method that performed await, and it ultimately allows a UI to be responsive or a service to be elastic.
I/O-Bound Example: Downloading data from a web service
private readonly HttpClient _httpClient = new HttpClient();
downloadButton.Clicked += async (o, e) =>
{
// This line will yield control to the UI as the request
// from the web service is happening.
//
// The UI thread is now free to perform other work.
var stringData = await _httpClient.GetStringAsync(URL);
DoSomethingWithData(stringData);
};
CPU-bound Example: Performing a Calculation for a Game
private DamageResult CalculateDamageDone()
{
// Code omitted:
//
// Does an expensive calculation and returns
// the result of that calculation.
}
calculateButton.Clicked += async (o, e) =>
{
// This line will yield control to the UI while CalculateDamageDone()
// performs its work. The UI thread is free to perform other work.
var damageResult = await Task.Run(() => CalculateDamageDone());
DisplayDamage(damageResult);
};
Examples above showed how you can use async and await for I/O-bound and CPU-bound work. It's key that you can identify when a job you need to do is I/O-bound or CPU-bound, because it can greatly affect the performance of your code and could potentially lead to misusing certain constructs.
Here are two questions you should ask before you write any code:
Will your code be "waiting" for something, such as data from a database?
- If your answer is "yes", then your work is I/O-bound.
Will your code be performing a very expensive computation?
- If you answered "yes", then your work is CPU-bound.
If the work you have is I/O-bound, use async and await without Task.Run. You should not use the Task Parallel Library. The reason for this is outlined in the Async in Depth article.
If the work you have is CPU-bound and you care about responsiveness, use async and await but spawn the work off on another thread with Task.Run. If the work is appropriate for concurrency and parallelism, you should also consider using the Task Parallel Library.
If you are comfortable mixing and matching between function and class syntax you can declare constants after the class (the constants are 'lifted') . Note that Visual Studio Code will struggle to auto-format the mixed syntax, (though it works).
class MyClass {_x000D_
// ..._x000D_
_x000D_
}_x000D_
MyClass.prototype.consts = { _x000D_
constant1: 33,_x000D_
constant2: 32_x000D_
};_x000D_
mc = new MyClass();_x000D_
console.log(mc.consts.constant2);
_x000D_
In python: help(my_list.append)
for example, will give you the docstring of the function.
>>> my_list = []
>>> help(my_list.append)
Help on built-in function append:
append(...)
L.append(object) -- append object to end
Assign a value when declaring the variable.
DECLARE @result VARCHAR(1000) ='';
SELECT @result = CAST(StudentId AS VARCHAR) + ',' FROM Student WHERE condition = xyz
Seems easiest to just add a
GET
/api/members/count
and return the total count of members
In c/cpp there is no shortcut but to initialize all the arrays with the zero subscript.Ex:
int arr[10] = {0};
But in java there is a magic tool called Arrays.fill() which will fill all the values in an array with the integer of your choice.Ex:
import java.util.Arrays;
public class Main
{
public static void main(String[] args)
{
int ar[] = {2, 2, 1, 8, 3, 2, 2, 4, 2};
Arrays.fill(ar, 10);
System.out.println("Array completely filled" +
" with 10\n" + Arrays.toString(ar));
}
}
create host file = manifest.json
html tag head
<link rel="manifest" href="/manifest.json">
file
manifest.json
{
"name": "news",
"short_name": "news",
"description": "des news application day",
"categories": [
"news",
"business"
],
"theme_color": "#ffffff",
"background_color": "#ffffff",
"display": "standalone",
"orientation": "natural",
"lang": "fa",
"dir": "rtl",
"start_url": "/?application=true",
"gcm_sender_id": "482941778795",
"DO_NOT_CHANGE_GCM_SENDER_ID": "Do not change the GCM Sender ID",
"icons": [
{
"src": "https://s100.divarcdn.com/static/thewall-assets/android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "https://s100.divarcdn.com/static/thewall-assets/android-chrome-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"related_applications": [
{
"platform": "play",
"url": "https://play.google.com/store/apps/details?id=ir.divar"
}
],
"prefer_related_applications": true
}
I usually use the Timer function to pause the application. Insert this code to yours
T0 = Timer
Do
Delay = Timer - T0
Loop Until Delay >= 1 'Change this value to pause time for a certain amount of seconds
I see users in comments wondering how to disable cell editing while allowing row deletion : I managed to do this by setting all columns individually to read only, instead of the DataGrid itself.
<DataGrid IsReadOnly="False">
<DataGrid.Columns>
<DataGridTextColumn IsReadOnly="True"/>
<DataGridTextColumn IsReadOnly="True"/>
</DataGrid.Columns>
</DataGrid>
In my case, I was doing:
curl <blabla> | jq | grep <blibli>
With jq .
it worked: curl <blabla> | jq . | grep <blibli>
onChange is when something within a field changes eg, you write something in a text input.
onBlur is when you take focus away from a field eg, you were writing in a text input and you have clicked off it.
So really they are almost the same thing but for onChange to behave the way onBlur does something in that input needs to change.
Additionally, return values are compatible with asynchronous design paradigms.
You cannot designate a function "async" if it uses ref or out parameters.
In summary, Return Values allow method chaining, cleaner syntax (by eliminating the necessity for the caller to declare additional variables), and allow for asynchronous designs without the need for substantial modification in the future.
To add on to the other answers here, if you would like to create a new object of a third different type with a where clause (e.g. one that is not your Entity Framework object) you can do this:
public IEnumerable<ThirdNonEntityClass> demoMethod(IEnumerable<int> property1Values)
{
using(var entityFrameworkObjectContext = new EntityFrameworkObjectContext )
{
var result = entityFrameworkObjectContext.SomeClass
.Join(entityFrameworkObjectContext.SomeOtherClass,
sc => sc.property1,
soc => soc.property2,
(sc, soc) => new {sc, soc})
.Where(s => propertyValues.Any(pvals => pvals == es.sc.property1)
.Select(s => new ThirdNonEntityClass
{
dataValue1 = s.sc.dataValueA,
dataValue2 = s.soc.dataValueB
})
.ToList();
}
return result;
}
Pay special attention to the intermediate object that is created in the Where and Select clauses.
Note that here we also look for any joined objects that have a property1 that matches one of the ones in the input list.
I know this is a bit more complex than what the original asker was looking for, but hopefully it will help someone.
instead of using " + " operator
print( "Alireza" + 1980)
Use comma " , " operator
print( "Alireza" , 1980)
Another nice thing about @HostBinding
is that you can combine it with @Input
if your binding relies directly on an input, eg:
@HostBinding('class.fixed-thing')
@Input()
fixed: boolean;
I found that although the shims from answers above worked, they did not match the behaviour of desktop browsers' implementations of btoa()
and atob()
:
const btoa = function(str){ return Buffer.from(str).toString('base64'); }
// returns "4pyT", yet in desktop Chrome would throw an error.
btoa('?');
// returns "fsO1w6bCvA==", yet in desktop Chrome would return "fvXmvA=="
btoa(String.fromCharCode.apply(null, new Uint8Array([0x7e, 0xf5, 0xe6, 0xbc])));
As it turns out, Buffer
instances represent/interpret strings encoded in UTF-8 by default. By contrast, in desktop Chrome, you can't even input a string that contains characters outside of the latin1 range into btoa()
, as it will throw an exception: Uncaught DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.
Therefore, you need to explicitly set the encoding type to latin1
in order for your Node.js shim to match the encoding type of desktop Chrome:
const btoaLatin1 = function(str) { return Buffer.from(str, 'latin1').toString('base64'); }
const atobLatin1 = function(b64Encoded) {return Buffer.from(b64Encoded, 'base64').toString('latin1');}
const btoaUTF8 = function(str) { return Buffer.from(str, 'utf8').toString('base64'); }
const atobUTF8 = function(b64Encoded) {return Buffer.from(b64Encoded, 'base64').toString('utf8');}
btoaLatin1('?'); // returns "Ew==" (would be preferable for it to throw error because this is undecodable)
atobLatin1(btoa('?')); // returns "\u0019" (END OF MEDIUM)
btoaUTF8('?'); // returns "4pyT"
atobUTF8(btoa('?')); // returns "?"
// returns "fvXmvA==", just like desktop Chrome
btoaLatin1(String.fromCharCode.apply(null, new Uint8Array([0x7e, 0xf5, 0xe6, 0xbc])));
// returns "fsO1w6bCvA=="
btoaUTF8(String.fromCharCode.apply(null, new Uint8Array([0x7e, 0xf5, 0xe6, 0xbc])));
A little variation with a more compact lookup table and using C++17 features:
std::string base64_decode(const std::string_view in) {
// table from '+' to 'z'
const uint8_t lookup[] = {
62, 255, 62, 255, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255,
255, 0, 255, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
255, 255, 255, 255, 63, 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51};
static_assert(sizeof(lookup) == 'z' - '+' + 1);
std::string out;
int val = 0, valb = -8;
for (uint8_t c : in) {
if (c < '+' || c > 'z')
break;
c -= '+';
if (lookup[c] >= 64)
break;
val = (val << 6) + lookup[c];
valb += 6;
if (valb >= 0) {
out.push_back(char((val >> valb) & 0xFF));
valb -= 8;
}
}
return out;
}
If you don't have std::string_view, try instead std::experimental::string_view.
To get the DB path for iOS, the simplest way is to:
(lldb)
) and type: po RLMRealm.defaultRealmPath
Tada...you have the path to your realm database
To GET first paragraph of an article:
https://en.wikipedia.org/w/api.php?action=query&titles=Belgrade&prop=extracts&format=json&exintro=1
I have created short Wikipedia API docs for my own needs. There are working examples on how to get article(s), image(s) and similar.
Add the image to Your project by clicking File -> "Add Files to ...".
Then choose the image in ImageView properties (Utilities -> Attributes Inspector).
Starting with Python 3.5, the '@' is used as a dedicated infix symbol for MATRIX MULTIPLICATION (PEP 0465 -- see https://www.python.org/dev/peps/pep-0465/)
int o1 = date1.IndexOf("-");
int o2 = date1.IndexOf("-",o1 + 1);
string str11 = date1.Substring(0,o1);
string str12 = date1.Substring(o1 + 1, o2 - o1 - 1);
string str13 = date1.Substring(o2 + 1);
int o21 = date2.IndexOf("-");
int o22 = date2.IndexOf("-", o1 + 1);
string str21 = date2.Substring(0, o1);
string str22 = date2.Substring(o1 + 1, o2 - o1 - 1);
string str23 = date2.Substring(o2 + 1);
if (Convert.ToInt32(str11) > Convert.ToInt32(str21))
{
}
else if (Convert.ToInt32(str12) > Convert.ToInt32(str22))
{
}
else if (Convert.ToInt32(str12) == Convert.ToInt32(str22) && Convert.ToInt32(str13) > Convert.ToInt32(str23))
{
}
As already mentioned if you can use await
. If you need to run the code synchronously like you mention .GetAwaiter().GetResult()
, .Result
or .Wait()
is a risk for deadlocks as many have said in comments/answers. Since most of us like oneliners you can use these for .Net 4.5<
Acquiring a value via an async method:
var result = Task.Run(() => asyncGetValue()).Result;
Syncronously calling an async method
Task.Run(() => asyncMethod()).Wait();
No deadlock issues will occur due to the use of Task.Run
.
Source:
https://stackoverflow.com/a/32429753/3850405
Update:
Could cause a deadlock if the calling thread is from the threadpool. The following happens: A new task is queued to the end of the queue, and the threadpool thread which would eventually execute the Task is blocked until the Task is executed.
Source:
https://medium.com/rubrikkgroup/understanding-async-avoiding-deadlocks-e41f8f2c6f5d
You seem to be using Windows Forms. Look at the SelectedIndex or SelectedItem properties.
if (this.combo1.SelectedItem == MY_OBJECT)
{
// do stuff
}
jQuery Version
$(function() {_x000D_
$('#bookmarkme').click(function() {_x000D_
if (window.sidebar && window.sidebar.addPanel) { // Mozilla Firefox Bookmark_x000D_
window.sidebar.addPanel(document.title, window.location.href, '');_x000D_
} else if (window.external && ('AddFavorite' in window.external)) { // IE Favorite_x000D_
window.external.AddFavorite(location.href, document.title);_x000D_
} else if (window.opera && window.print) { // Opera Hotlist_x000D_
this.title = document.title;_x000D_
return true;_x000D_
} else { // webkit - safari/chrome_x000D_
alert('Press ' + (navigator.userAgent.toLowerCase().indexOf('mac') != -1 ? 'Command/Cmd' : 'CTRL') + ' + D to bookmark this page.');_x000D_
}_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<a id="bookmarkme" href="#" rel="sidebar" title="bookmark this page">Bookmark This Page</a>
_x000D_
you can also use Path from scala io to read and process files.
import scalax.file.Path
Now you can get file path using this:-
val filePath = Path("path_of_file_to_b_read", '/')
val lines = file.lines(includeTerminator = true)
You can also Include terminators but by default it is set to false..
Actually, you can, even though accepted answer saying that you can't.
There is a _JAVA_OPTIONS
environment variable, more about it here
In response to Thomas Browne's comment, because lnmx's answer only works for subtracting a date, here is a modification of his code that works for subtracting time from a time.Time type.
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
fmt.Println("now:", now)
count := 10
then := now.Add(time.Duration(-count) * time.Minute)
// if we had fix number of units to subtract, we can use following line instead fo above 2 lines. It does type convertion automatically.
// then := now.Add(-10 * time.Minute)
fmt.Println("10 minutes ago:", then)
}
Produces:
now: 2009-11-10 23:00:00 +0000 UTC
10 minutes ago: 2009-11-10 22:50:00 +0000 UTC
Not to mention, you can also use time.Hour
or time.Second
instead of time.Minute
as per your needs.
Playground: https://play.golang.org/p/DzzH4SA3izp
The JDK Date
API is horribly broken unfortunately. I recommend using Joda Time library.
Joda Time has a concept of time Interval:
Interval interval = new Interval(oldTime, new Instant());
EDIT: By the way, Joda has two concepts: Interval
for representing an interval of time between two time instants (represent time between 8am and 10am), and a Duration
that represents a length of time without the actual time boundaries (e.g. represent two hours!)
If you only care about time comparisions, most Date
implementations (including the JDK one) implements Comparable
interface which allows you to use the Comparable.compareTo()
The Jayrock RPC library is a great tool for doing this in a nice familliar way for C# developers. It allows you to create a .NET class with the methods you require, and add this class as a script (in a roundabout way) to your page. You can then create a js object of your type and call methods as you would any other object.
It essentially hides away ajax implementation and presents RPC in a familliar format. Mind you the best option really is to use ASP.NET MVC and use jQuery ajax calls to action methods - much more concise and less messing about!
As was written above, if the language you use has a JSON-library coming with it, use it to try decoding the string and catch the exception/error if it fails! If the language does not (just had such a case with FreeMarker) the following regex could at least provide some very basic validation (it's written for PHP/PCRE to be testable/usable for more users). It's not as foolproof as the accepted solution, but also not that scary =):
~^\{\s*\".*\}$|^\[\n?\{\s*\".*\}\n?\]$~s
short explanation:
// we have two possibilities in case the string is JSON
// 1. the string passed is "just" a JSON object, e.g. {"item": [], "anotheritem": "content"}
// this can be matched by the following regex which makes sure there is at least a {" at the
// beginning of the string and a } at the end of the string, whatever is inbetween is not checked!
^\{\s*\".*\}$
// OR (character "|" in the regex pattern)
// 2. the string passed is a JSON array, e.g. [{"item": "value"}, {"item": "value"}]
// which would be matched by the second part of the pattern above
^\[\n?\{\s*\".*\}\n?\]$
// the s modifier is used to make "." also match newline characters (can happen in prettyfied JSON)
if I missed something that would break this unintentionally, I'm grateful for comments!
You're looking for the SyndicationFeed
class, which does exactly that.
make sure you have these permissions:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Then make some activity and register a LocationListener
package com.example.location;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
public class LocationActivity extends SherlockFragmentActivity implements LocationListener {
private GoogleMap map;
private LocationManager locationManager;
private static final long MIN_TIME = 400;
private static final float MIN_DISTANCE = 1000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this); //You can also use LocationManager.GPS_PROVIDER and LocationManager.PASSIVE_PROVIDER
}
@Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
map.animateCamera(cameraUpdate);
locationManager.removeUpdates(this);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) { }
@Override
public void onProviderEnabled(String provider) { }
@Override
public void onProviderDisabled(String provider) { }
}
map.xml
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>