You should create custom helper for just changing string format except using controller call.
import sys
sys.path
Building on VonC's answer to deal with file removals and additions, use the following commands and scripts:
> git config --global diff.tool winmerge
> git config --global difftool.winmerge.cmd "winmerge.sh \"$LOCAL\" \"$REMOTE\" \"$BASE\""
> git config --global difftool.prompt false
Which is the same as putting this in your global .gitconfig
:
[diff]
tool = winmerge
[difftool "winmerge"]
cmd = winmerge.bat "$LOCAL" "$REMOTE" "$BASE"
[difftool]
prompt = false
Then put the following in winmerge.sh
which must be on your path:
#!/bin/sh
NULL="/dev/null"
if [ "$2" = "$NULL" ] ; then
echo "removed: $3"
elif [ "$1" = "$NULL" ] ; then
echo "added: $3"
else
echo "changed: $3"
"C:/Program Files (x86)/WinMerge/WinMergeU.exe" -e -ub -dl "Base" -dr "Mine" "$1" "$2"
fi
You can't move a mouse but can lock it. Note: that you must call requestPointerLock in click event.
Small Example:
var canvas = document.getElementById('mycanvas');
canvas.requestPointerLock = canvas.requestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
canvas.requestPointerLock();
Documentation and full code example:
https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API
Not sure what your asking!
However
SELECT GETDATE()
Will get you the current date and time
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
Will get you just the date with time set to 00:00:00
You should be able to use join
, which joins on the index as default. Given your desired result, you must use outer
as the join type.
>>> df1.join(df2, how='outer')
V1 V2
A 1/1/2012 12 15
2/1/2012 14 NaN
3/1/2012 NaN 21
B 1/1/2012 15 24
2/1/2012 8 9
C 1/1/2012 17 NaN
2/1/2012 9 NaN
D 1/1/2012 NaN 7
2/1/2012 NaN 16
Signature: _.join(other, on=None, how='left', lsuffix='', rsuffix='', sort=False) Docstring: Join columns with other DataFrame either on index or on a key column. Efficiently Join multiple DataFrame objects by index at once by passing a list.
Windows Users need to set below paths:
..\Anaconda3
..\Anaconda3\scripts
..\Anaconda3\Library\bin
Per user:
System wide (requires restart):
Try adding C:\path\to\java\jre\bin
to your system environment variable PATH and run again. That worked for me!
This works cross-browser, provides more accessibility and comes with less markup. ditch the div. Wrap the label
label{
display: block;
height: 35px;
line-height: 35px;
border: 1px solid #000;
}
input{margin-top:15px; height:20px}
<label for="name">Name: <input type="text" id="name" /></label>
This is what worked for me:
Log on SSIS with Windows authentication.
1. Open services and find MSSQL NT Service account name and copy it:
2. Open folder from which SQL server should read from. Security - Group or user names tab - Add and paste there copied account:**
Your BULK INSERT
query should run fine now.
If problem persists try adding SQL Server Agent account to folder permissions in same way.
Make sure you restart MSSQL server in services after you are done.
One very nasty gotcha which just wasted a bit of my time debugging - you may find yourself prompted by auto-complete to try using doesContain
which seems to work.
Except, doesContain
uses an id comparison instead of the hash comparison used by objectForKey
so if you have a dictionary with string keys it will return NO to a doesContain
.
NSMutableDictionary* keysByName = [[NSMutableDictionary alloc] init];
keysByName[@"fred"] = @1;
NSString* test = @"fred";
if ([keysByName objectForKey:test] != nil)
NSLog(@"\nit works for key lookups"); // OK
else
NSLog(@"\nsod it");
if (keysByName[test] != nil)
NSLog(@"\nit works for key lookups using indexed syntax"); // OK
else
NSLog(@"\nsod it");
if ([keysByName doesContain:@"fred"])
NSLog(@"\n doesContain works literally");
else
NSLog(@"\nsod it"); // this one fails because of id comparison used by doesContain
<div id='element_123_wrapper_text'>My sample DIV</div>
The Operator ^ - Match elements that starts with given value
div[id^="element_123"] {
}
The Operator $ - Match elements that ends with given value
div[id$="wrapper_text"] {
}
The Operator * - Match elements that have an attribute containing a given value
div[id*="wrapper_text"] {
}
For an incoming request like /v1/location/1234
, as you can imagine it would be difficult for Web API to automatically figure out if the value of the segment corresponding to '1234' is related to appid
and not to deviceid
.
I think you should change your route template to be like
[Route("v1/location/{deviceOrAppid?}", Name = "AddNewLocation")]
and then parse the deiveOrAppid
to figure out the type of id.
Also you need to make the segments in the route template itself optional otherwise the segments are considered as required. Note the ?
character in this case.
For example:
[Route("v1/location/{deviceOrAppid?}", Name = "AddNewLocation")]
The following sample code works well (locale need to be obtained dynamically)
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.DecimalFormat;
import java.text.ParsePosition;
import java.util.Locale;
class TestBigDecimal {
public static void main(String[] args) {
String str = "0,00";
Locale in_ID = new Locale("in","ID");
//Locale in_ID = new Locale("en","US");
DecimalFormat nf = (DecimalFormat)NumberFormat.getInstance(in_ID);
nf.setParseBigDecimal(true);
BigDecimal bd = (BigDecimal)nf.parse(str, new ParsePosition(0));
System.out.println("bd value : " + bd);
}
}
var values = {};
$('td input').each(function(){
values[$(this).attr('name')] = $(this).val();
}
Haven't tested, but that should do it...
The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.
According to this Google blogpost:
It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.
When referencing the mipmap- folders ensure you are using the following reference:
android:icon="@mipmap/ic_launcher"
The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.
Use %in%
as follows
A$C %in% B$C
Which will tell you which values of column C of A are in B.
What is returned is a logical vector. In the specific case of your example, you get:
A$C %in% B$C
# [1] TRUE FALSE TRUE TRUE
Which you can use as an index to the rows of A
or as an index to A$C
to get the actual values:
# as a row index
A[A$C %in% B$C, ] # note the comma to indicate we are indexing rows
# as an index to A$C
A$C[A$C %in% B$C]
[1] 1 3 4 # returns all values of A$C that are in B$C
We can negate it too:
A$C[!A$C %in% B$C]
[1] 2 # returns all values of A$C that are NOT in B$C
2 %in% B$C # "is the value 2 in B$C ?"
# FALSE
A$C[2] %in% B$C # "is the 2nd element of A$C in B$C ?"
# FALSE
One more solution would be to use a intersection
.
one = [1, 2, 3]
two = [9, 8, 5, 3, 2, 1]
set(one).intersection(set(two)) == set(one)
The intersection of the sets would contain of set one
(OR)
one = [1, 2, 3]
two = [9, 8, 5, 3, 2, 1]
set(one) & (set(two)) == set(one)
const http = require('http');
const url = require('url');
http.createServer((req,res)=>{
const parseObj = url.parse(req.url,true);
const users = [{id:1,name:'soura'},{id:2,name:'soumya'}]
if(parseObj.pathname == '/user-details' && req.method == "GET") {
let Id = parseObj.query.id;
let user_details = {};
users.forEach((data,index)=>{
if(data.id == Id){
user_details = data;
}
})
res.writeHead(200,{'x-auth-token':'Auth Token'})
res.write(JSON.stringify(user_details)) // Json to String Convert
res.end();
}
}).listen(8000);
I have used the above code in my existing project.
If copy-dependencies, unpack, pack, etc., are important for your project you shouldn't ignore it. You have to enclose your <plugins>
in <pluginManagement>
tested with Eclipse Indigo SR1, maven 2.2.1
Please use -t
to see which command is actually being ran
I just tweaked Virender answer to do same:
git ls-files --deleted -z | xargs -t -0 git rm
My solution keeps the date the same no matter what timezone is set on the client-side. Maybe someone will find it useful.
My use case:
I'm creating a todo app, where you set date of your task. This date should remain constant no matter what timezone you're in.
Example. You want to call your friend at 8 am on June 25th.
You create this task 5 days before (June 20th) while you're in China.
Then, on the same day, you fly to New York for a few days.
Then on June 25th, while you're still in New York, you wake up at 7:30 am (which means you should receive task notification in 30 mins (even tho it's 1:30 pm already in China where you were when creating the task)
So the task is ignoring the timezone. It means 'I want to do it at 8 am in whatever timezone I'll be in'.
What I do is let's say 'I assume you're always in London Timezone - UTC'.
What it means is - when the user picks some date in her/his Timezone - I convert this date to the same date in UTC. ie. You pick 8 am in China, but I convert it to 8 am in UTC.
Then - next time you open the app - I read the date saved in UTC and convert it to the same date in your current timezone - eg. I convert 8 am in UTC to 8 am in the New York timezone.
This solution means that the date can mean something else depending on where you are when setting it and where you're reading it, but it remains constant in a way that it 'feels' like you're always in the same timezone.
Let's write some code:
First - we have 2 main functions for converting from/to UTC ignoring timezone:
export function convertLocalDateToUTCIgnoringTimezone(date: Date) {
const timestamp = Date.UTC(
date.getFullYear(),
date.getMonth(),
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds(),
date.getMilliseconds(),
);
return new Date(timestamp);
}
export function convertUTCToLocalDateIgnoringTimezone(utcDate: Date) {
return new Date(
utcDate.getUTCFullYear(),
utcDate.getUTCMonth(),
utcDate.getUTCDate(),
utcDate.getUTCHours(),
utcDate.getUTCMinutes(),
utcDate.getUTCSeconds(),
utcDate.getUTCMilliseconds(),
);
}
Then, I save/read this date like:
function saveTaskDate(localDate: Date) {
// I convert your local calendar date so it looks like you've picked it being in UTC somewhere around London
const utcDate = convertLocalDateToUTCIgnoringTimezone(localDate);
api.saveTaskDate(utcDate);
}
function readTaskDate(taskUtcDate: Date) {
// I convert this UTC date to 'look in your local timezone' as if you were now in UTC somewhere around london
const localDateWithSameDayAsUTC = convertUTCToLocalDateIgnoringTimezone(taskUtcDate);
// this date will have the same calendar day as the one you've picked previously
// no matter where you were saving it and where you are now
}
Simply, you can use FormCollection
like:
[HttpPost]
public ActionResult SubmitAction(FormCollection collection)
{
// Get Post Params Here
string var1 = collection["var1"];
}
You can also use a class, that is mapped with Form values, and asp.net mvc engine automagically fills it:
//Defined in another file
class MyForm
{
public string var1 { get; set; }
}
[HttpPost]
public ActionResult SubmitAction(MyForm form)
{
string var1 = form1.Var1;
}
div { margin: auto; }
This will center your div.
Div by itself is a blockelement. Therefor you need to define the style to the div how to behave.
Personally I don't use final on method parameters, because it adds too much clutter to parameter lists. I prefer to enforce that method parameters are not changed through something like Checkstyle.
For local variables I use final whenever possible, I even let Eclipse do that automatically in my setup for personal projects.
I would certainly like something stronger like C/C++ const.
Using merge is risky and tricky, so it's a dirty workaround in your case. You need to remember at least that when you pass an entity object to merge, it stops being attached to the transaction and instead a new, now-attached entity is returned. This means that if anyone has the old entity object still in their possession, changes to it are silently ignored and thrown away on commit.
You are not showing the complete code here, so I cannot double-check your transaction pattern. One way to get to a situation like this is if you don't have a transaction active when executing the merge and persist. In that case persistence provider is expected to open a new transaction for every JPA operation you perform and immediately commit and close it before the call returns. If this is the case, the merge would be run in a first transaction and then after the merge method returns, the transaction is completed and closed and the returned entity is now detached. The persist below it would then open a second transaction, and trying to refer to an entity that is detached, giving an exception. Always wrap your code inside a transaction unless you know very well what you are doing.
Using container-managed transaction it would look something like this. Do note: this assumes the method is inside a session bean and called via Local or Remote interface.
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void storeAccount(Account account) {
...
if (account.getId()!=null) {
account = entityManager.merge(account);
}
Transaction transaction = new Transaction(account,"other stuff");
entityManager.persist(account);
}
This is my solution with prepared statements and stored procedure is returning several rows not only one value.
<?php
require 'config.php';
header('Content-type:application/json');
$connection->set_charset('utf8');
$mIds = $_GET['ids'];
$stmt = $connection->prepare("CALL sp_takes_string_returns_table(?)");
$stmt->bind_param("s", $mIds);
$stmt->execute();
$result = $stmt->get_result();
$response = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($response);
$stmt->close();
$connection->close();
Not just mvn
, for any util, you can find out yourself by giving yum whatprovides {command_name}
You'll find the junit launch commands in .metadata/.plugins/org.eclipse.debug.core/.launches, assuming your Eclipse works like mine does. The files are named {TestClass}.launch.
You will probably also need the .classpath file in the project directory that contains the test class.
Like the run configurations, they're XML files (even if they don't have an xml extension).
@RobinL as mentioned in previous comments, you can use chart.series[n].setData(). First you need to make sure you’ve assigned a chart instance to the chart variable, that way it adopts all the properties and methods you need to access and manipulate the chart.
I’ve also used the second parameter of setData() and had it false, to prevent automatic rendering of the chart. This was because I have multiple data series, so I’ll rather update each of them, with render=false, and then running chart.redraw(). This multiplied performance (I’m having 10,000-100,000 data points and refreshing the data set every 50 milliseconds).
With the help of xpath locator also, you can achieve the same.
Your statement would be:
driver.findElement(By.xpath(".//a[contains(@href,'long')]")).click();
And for clicking all the links contains long in the URL, you can use:-
List<WebElement> linksList = driver.findElements(By.xpath(".//a[contains(@href,'long')]"));
for (WebElement webElement : linksList){
webElement.click();
}
To clarify an already posted solution due to questions in the comments
import numpy
array = numpy.array([49, 51, 53, 56])
array = array - 13
will output:
array([36, 38, 40, 43])
Life is too short to spend it on messing with paths, etc.
Since I had Homebrew installed on the iMac, I just ran this command:
brew install gradle
The Ionic3 project started to build successfully.
It's simple:
array = []
will set array
to be an empty list. (They're called lists in Python, by the way, not arrays)
If that doesn't work for you, edit your question to include a code sample that demonstrates your problem.
Steps to fix Root mount (That i followed as i changed permission with ec2-user folder and the authorization key file) This process will be similar to detach and attach a pen-drive
Below are some other scenarios you may encounter -
- You're using an SSH private key but the corresponding public key is not in the authorized_keys file.
- You don't have permissions for your authorized_keys file.
- You don't have permissions for the .ssh folder.
- Your authorized_keys file or .ssh folder isn't named correctly.
- Your authorized_keys file or .ssh folder was deleted.
Steps to fix them
Now after you login to new ec2 run below steps
sudo mount /dev/mapper/rootvg-home /mnt
Now we have fixed our volume with the issue that we faced. Mostly it could be user permission issue - Umount /mnt to unmounts it - Now go to the console and point to the volume attached to new instance and detach it - After detached, attached it to your new volume as /dev/sda1
With that said you should be able to login successfully
Use the (ngModelChange)
event to detect changes on the model
Microsoft Excel for Mac 2011 v 14.5.9
What about the following for doing a range incremented by days:
for d in map( lambda x: startDate+datetime.timedelta(days=x), xrange( (stopDate-startDate).days ) ):
# Do stuff here
For a generic version:
for d in map( lambda x: startTime+x*stepTime, xrange( (stopTime-startTime).total_seconds() / stepTime.total_seconds() ) ):
# Do stuff here
Note that .total_seconds() is only supported after python 2.7 If you are stuck with an earlier version you can write your own function:
def total_seconds( td ):
return float(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
An all-pairs shortest path algorithm will compute the shortest paths between all vertices in a graph. This will allow paths to be pre-computed instead of requiring a path to be calculated each time someone wants to find the shortest path between a source and a destination. The Floyd-Warshall algorithm is an all-pairs shortest path algorithm.
If you don't want to show controls then try this code
<audio autoplay>
<source src="song.ogg" type="audio/ogg">
Your browser does not support the audio element.
</audio>
It's a long pointer to a constant, wide string (i.e. a string of wide characters).
Since it's a wide string, you want to make your constant look like: L"TestWindow"
. I wouldn't create the intermediate a
either, I'd just pass L"TestWindow"
for the parameter:
ghTest = FindWindowEx(NULL, NULL, NULL, L"TestWindow");
If you want to be pedantically correct, an "LPCTSTR" is a "text" string -- a wide string in a Unicode build and a narrow string in an ANSI build, so you should use the appropriate macro:
ghTest = FindWindow(NULL, NULL, NULL, _T("TestWindow"));
Few people care about producing code that can compile for both Unicode and ANSI character sets though, and if you don't getting it to really work correctly can be quite a bit of extra work for little gain. In this particular case, there's not much extra work, but if you're manipulating strings, there's a whole set of string manipulation macros that resolve to the correct functions.
You don't need floats. In fact, they're useless because floats are ignored in flexbox.
You also don't need CSS positioning.
There are several flex methods available. auto
margins have been mentioned in another answer.
Here are two other options:
justify-content: space-between
and the order
property.justify-content: space-between
and reverse the order of the divs..parent {_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
}_x000D_
_x000D_
.parent:first-of-type > div:last-child { order: -1; }_x000D_
_x000D_
p { background-color: #ddd;}
_x000D_
<p>Method 1: Use <code>justify-content: space-between</code> and <code>order-1</code></p>_x000D_
_x000D_
<div class="parent">_x000D_
<div class="child" style="float:right"> Ignore parent? </div>_x000D_
<div>another child </div>_x000D_
</div>_x000D_
_x000D_
<hr>_x000D_
_x000D_
<p>Method 2: Use <code>justify-content: space-between</code> and reverse the order of _x000D_
divs in the mark-up</p>_x000D_
_x000D_
<div class="parent">_x000D_
<div>another child </div>_x000D_
<div class="child" style="float:right"> Ignore parent? </div>_x000D_
</div>
_x000D_
Please follow the below steps
1). First, navigate to the /etc/postgresql/{your pg version}/main directory.
My version is 10 Then:
cd /etc/postgresql/10/main
2). Here resides the pg_hba.conf file needs to do some changes here you may need sudo access for this.
sudo nano pg_hba.conf
3). Scroll down the file till you find this –
# Database administrative login by Unix domain socket
local all postgres peer
4). Here change the peer to md5 as follows.
# Database administrative login by Unix domain socket
local all all md5
peer means it will trust the authenticity of UNIX user hence does not
prompt for the password. md5 means it will always ask for a password, and validate it after hashing with MD5.
5).Now save the file and restart the Postgres server.
sudo service postgresql restart
Now it should be ok.
The skipping elements bug in this (code from above)
var len = cells.length;
for(var i = 0; i < len; i++) {
if(cells[i].className.toLowerCase() == "column") {
cells[i].parentNode.removeChild(cells[i]);
}
}
can be fixed by just running the loop backwards as follows (so that the temporary array is not needed)
var len = cells.length;
for(var i = len-1; i >-1; i--) {
if(cells[i].className.toLowerCase() == "column") {
cells[i].parentNode.removeChild(cells[i]);
}
}
This will grab records with strings (in the fieldName column) that are 10 characters long:
select * from table where length(fieldName)=10
ApplicationId must be of type UniqueIdentifier
. Your code works fine if you do:
DECLARE @TTEST TABLE
(
TEST UNIQUEIDENTIFIER
)
DECLARE @UNIQUEX UNIQUEIDENTIFIER
SET @UNIQUEX = NEWID();
INSERT INTO @TTEST
(TEST)
VALUES
(@UNIQUEX);
SELECT * FROM @TTEST
Therefore I would say it is safe to assume that ApplicationId
is not the correct data type.
It requires installing a 3rd-party module but the package iteration_utilities
contains a unique_everseen
1 function that can remove all duplicates while preserving the order:
>>> from iteration_utilities import unique_everseen
>>> list(unique_everseen(['a', 'b', 'c', 'd'] + ['a', 'c', 'd']))
['a', 'b', 'c', 'd']
In case you want to avoid the overhead of the list addition operation you can use itertools.chain
instead:
>>> from itertools import chain
>>> list(unique_everseen(chain(['a', 'b', 'c', 'd'], ['a', 'c', 'd'])))
['a', 'b', 'c', 'd']
The unique_everseen
also works if you have unhashable items (for example lists) in the lists:
>>> from iteration_utilities import unique_everseen
>>> list(unique_everseen([['a'], ['b'], 'c', 'd'] + ['a', 'c', 'd']))
[['a'], ['b'], 'c', 'd', 'a']
However that will be (much) slower than if the items are hashable.
1 Disclosure: I'm the author of the iteration_utilities
-library.
Here is another fix:
My build system (Gradle) added a required native library (dll) to the Eclipse build path (Right Click on Project -> Properties -> Java Build Path -> Libraries). Telling the build system not to add the native dll library to the Eclipse classpath solved the problem.
One way is to use a script tag to import the variables you want to your views:
<script type="text/javascript">
window.base_url = <?php echo json_encode(base_url()); ?>;
</script>
Here, I wrapped the base_url with json_encode so that it'll automatically escape any characters to valid Javascript. I put base_url to the global Window so you can use it anywhere just by calling base_url, but make sure to put the script tag above any Javascript that calls it. With your given example:
...
$('#style_color').attr("href", base_url + "assets/css/themes/" + color_ + ".css");
Any class which extends Exception
class will be a user defined Checked exception class where as any class which extends RuntimeException
will be Unchecked exception class.
as mentioned in User defined exception are checked or unchecked exceptions
So, not throwing the checked exception(be it user-defined or built-in exception) gives compile time error.
Checked exception are the exceptions that are checked at compile time.
Unchecked exception are the exceptions that are not checked at compiled time
mbstring is a "non-default" extension, that is not enabled by default ; see this page of the manual :
Installation
mbstring is a non-default extension. This means it is not enabled by default. You must explicitly enable the module with the configure option. See the Install section for details
So, you might have to enable that extension, modifying the php.ini file (and restarting Apache, so your modification is taken into account)
I don't use CentOS, but you may have to install the extension first, using something like this (see this page, for instance, which seems to give a solution) :
yum install php-mbstring
(The package name might be a bit different ; so, use yum search to get it :-) )
Clearly! We can make a function to return a CSS class name with following fully example.
CSS
<style>
.Red {
color: Red;
}
.Yellow {
color: Yellow;
}
.Blue {
color: Blue;
}
.Green {
color: Green;
}
.Gray {
color: Gray;
}
.b{
font-weight: bold;
}
</style>
JS
<script>
angular.module('myapp', [])
.controller('ExampleController', ['$scope', function ($scope) {
$scope.MyColors = ['It is Red', 'It is Yellow', 'It is Blue', 'It is Green', 'It is Gray'];
$scope.getClass = function (strValue) {
if (strValue == ("It is Red"))
return "Red";
else if (strValue == ("It is Yellow"))
return "Yellow";
else if (strValue == ("It is Blue"))
return "Blue";
else if (strValue == ("It is Green"))
return "Green";
else if (strValue == ("It is Gray"))
return "Gray";
}
}]);
</script>
And then
<body ng-app="myapp" ng-controller="ExampleController">
<h2>AngularJS ng-class if example</h2>
<ul >
<li ng-repeat="icolor in MyColors" >
<p ng-class="[getClass(icolor), 'b']">{{icolor}}</p>
</li>
</ul>
<hr/>
<p>Other way using : ng-class="{'class1' : expression1, 'class2' : expression2,'class3':expression2,...}"</p>
<ul>
<li ng-repeat="icolor in MyColors">
<p ng-class="{'Red':icolor=='It is Red','Yellow':icolor=='It is Yellow','Blue':icolor=='It is Blue','Green':icolor=='It is Green','Gray':icolor=='It is Gray'}" class="b">{{icolor}}</p>
</li>
</ul>
You can refer to full code page at ng-class if example
An additional option to the ones suggested, is to use the BigInteger
class. Since hex values are often large numbers, such as sha256 or sha512 values, they will easily overflow an int
and a long
. While converting to a byte array is an option as other answers show, BigInterger
, the often forgotten class in java, is an option as well.
String sha256 = "65f4b384672c2776116d8d6533c69d4b19d140ddec5c191ea4d2cfad7d025ca2";
BigInteger value = new BigInteger(sha256, 16);
System.out.println("value = " + value);
// 46115947372890196580627454674591875001875183744738980595815219240926424751266
Considering the thoughts from http://www.thoughtcrime.org/blog/the-cryptographic-doom-principle/ (in short: FIRST encrypt, THEN authenticate. Afterwards FIRST verify, THEN decrypt) I have implemented the following solution in node.js:
function encrypt(text,password){
var cipher = crypto.createCipher(algorithm,password)
var crypted = cipher.update(text,'utf8','hex')
crypted += cipher.final('hex');
return crypted;
}
function decrypt(text,password){
var decipher = crypto.createDecipher(algorithm,password)
var dec = decipher.update(text,'hex','utf8')
dec += decipher.final('utf8');
return dec;
}
function hashText(text){
var hash = crypto.createHash('md5').update(text).digest("hex");
//console.log(hash);
return hash;
}
function encryptThenAuthenticate(plainText,pw)
{
var encryptedText = encrypt(plainText,pw);
var hash = hashText(encryptedText);
return encryptedText+"$"+hash;
}
function VerifyThenDecrypt(encryptedAndAuthenticatedText,pw)
{
var encryptedAndHashArray = encryptedAndAuthenticatedText.split("$");
var encrypted = encryptedAndHashArray[0];
var hash = encryptedAndHashArray[1];
var hash2Compare = hashText(encrypted);
if (hash === hash2Compare)
{
return decrypt(encrypted,pw);
}
}
It can be tested with:
var doom = encryptThenAuthenticate("The encrypted text",user.cryptoPassword);
console.log(VerifyThenDecrypt(doom,user.cryptoPassword));
Hope this helps :-)
$resource was meant to retrieve data from an endpoint, manipulate it and send it back. You've got some of that in there, but you're not really leveraging it for what it was made to do.
It's fine to have custom methods on your resource, but you don't want to miss out on the cool features it comes with OOTB.
EDIT: I don't think I explained this well enough originally, but $resource
does some funky stuff with returns. Todo.get()
and Todo.query()
both return the resource object, and pass it into the callback for when the get completes. It does some fancy stuff with promises behind the scenes that mean you can call $save()
before the get()
callback actually fires, and it will wait. It's probably best just to deal with your resource inside of a promise then()
or the callback method.
var Todo = $resource('/api/1/todo/:id');
//create a todo
var todo1 = new Todo();
todo1.foo = 'bar';
todo1.something = 123;
todo1.$save();
//get and update a todo
var todo2 = Todo.get({id: 123});
todo2.foo += '!';
todo2.$save();
//which is basically the same as...
Todo.get({id: 123}, function(todo) {
todo.foo += '!';
todo.$save();
});
//get a list of todos
Todo.query(function(todos) {
//do something with todos
angular.forEach(todos, function(todo) {
todo.foo += ' something';
todo.$save();
});
});
//delete a todo
Todo.$delete({id: 123});
Likewise, in the case of what you posted in the OP, you could get a resource object and then call any of your custom functions on it (theoretically):
var something = src.GetTodo({id: 123});
something.foo = 'hi there';
something.UpdateTodo();
I'd experiment with the OOTB implementation before I went and invented my own however. And if you find you're not using any of the default features of $resource
, you should probably just be using $http
on it's own.
As of Angular 1.2, resources support promises. But they didn't change the rest of the behavior.
To leverage promises with $resource
, you need to use the $promise
property on the returned value.
var Todo = $resource('/api/1/todo/:id');
Todo.get({id: 123}).$promise.then(function(todo) {
// success
$scope.todos = todos;
}, function(errResponse) {
// fail
});
Todo.query().$promise.then(function(todos) {
// success
$scope.todos = todos;
}, function(errResponse) {
// fail
});
Just keep in mind that the $promise
property is a property on the same values it was returning above. So you can get weird:
var todo = Todo.get({id: 123}, function() {
$scope.todo = todo;
});
Todo.get({id: 123}, function(todo) {
$scope.todo = todo;
});
Todo.get({id: 123}).$promise.then(function(todo) {
$scope.todo = todo;
});
var todo = Todo.get({id: 123});
todo.$promise.then(function() {
$scope.todo = todo;
});
//ul[@class="featureList" and li//text()[contains(., "Model")]]
You can call the super class's constructor like this
class A(object):
def __init__(self, number):
print "parent", number
class B(A):
def __init__(self):
super(B, self).__init__(5)
b = B()
NOTE:
This will work only when the parent class inherits object
go to your project folder via cmd. run the following command
composer update
it will install the missing vendor folder and files in your project.
but in some cases, it gives an error like "Your configuration does not allow connection to ....." in cmd.
for that go to your composer.json file,
change "secure-http": true
to "secure-http": false
but in some cases (as was in my case) you may not find such line in your file. for that do the following action:
change "config": {
"preferred-install": "dist"
}
to
"config": {
"preferred-install": "dist",
"secure-http": false
}
and run again composer update
command.
hope this will solve problem.
Here is my solution.
Lets say you have two TextViews
and put them on a LinearLayout
(named ll
). You'll put this LinerLayout
on another LinerLayout
.
< lm Linear Layout>
< ll Linear Layout>
<name Text view>
</name Text view>
<surname Text view>
</surname Text view>
</ll Linear Layout>
</lm Linear Layout>
When you want to create this structure you need to give parent as inheritance.
If you want use it in an onCreate
method this
will enough.
Otherwise here is solition:
LinerLayout lm = new LinearLayout(this); // You can use getApplicationContext() also
LinerLayout ll = new LinearLayout(lm.getContext());
TextView name = new TextView(ll.getContext());
TextView surname = new TextView(ll.getContext());
json_decode will return the same array that was originally encoded. For instanse, if you
$array = json_decode($json, true);
echo $array['countryId'];
OR
$obj= json_decode($json);
echo $obj->countryId;
These both will echo 84. I think json_encode and json_decode function names are self-explanatory...
Use a .gitignore file. This allows you to ignore certain files. http://git-scm.com/docs/gitignore
Here's an example Eclipse one, which handles your classpath and project files: https://github.com/github/gitignore/blob/master/Global/Eclipse.gitignore
You can indeed not define the filter execution order using @WebFilter
annotation. However, to minimize the web.xml
usage, it's sufficient to annotate all filters with just a filterName
so that you don't need the <filter>
definition, but just a <filter-mapping>
definition in the desired order.
For example,
@WebFilter(filterName="filter1")
public class Filter1 implements Filter {}
@WebFilter(filterName="filter2")
public class Filter2 implements Filter {}
with in web.xml
just this:
<filter-mapping>
<filter-name>filter1</filter-name>
<url-pattern>/url1/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>filter2</filter-name>
<url-pattern>/url2/*</url-pattern>
</filter-mapping>
If you'd like to keep the URL pattern in @WebFilter
, then you can just do like so,
@WebFilter(filterName="filter1", urlPatterns="/url1/*")
public class Filter1 implements Filter {}
@WebFilter(filterName="filter2", urlPatterns="/url2/*")
public class Filter2 implements Filter {}
but you should still keep the <url-pattern>
in web.xml
, because it's required as per XSD, although it can be empty:
<filter-mapping>
<filter-name>filter1</filter-name>
<url-pattern />
</filter-mapping>
<filter-mapping>
<filter-name>filter2</filter-name>
<url-pattern />
</filter-mapping>
Regardless of the approach, this all will fail in Tomcat until version 7.0.28 because it chokes on presence of <filter-mapping>
without <filter>
. See also Using Tomcat, @WebFilter doesn't work with <filter-mapping> inside web.xml
String is given as immutable by Sun micro systems,because string can used to store as key in map collection. StringBuffer is mutable .That is the reason,It cannot be used as key in map object
I've found the sticky footer solution a bit painful on responsive sites, given that the height of your nav and footer can differ depending on the device. If you only care about working on modern browsers, you can accomplish your goal using a bit of Javascript.
If this is your HTML:
<div class="nav">
</div>
<div class="wrapper">
</div>
<div class="footer">
</div>
Then use this JQuery on every page:
$(function(){
/* Sets the minimum height of the wrapper div to ensure the footer reaches the bottom */
function setWrapperMinHeight() {
$('.wrapper').css('minHeight', window.innerHeight - $('.nav').height() - $('.footer').height());
}
/* Make sure the main div gets resized on ready */
setWrapperMinHeight();
/* Make sure the wrapper div gets resized whenever the screen gets resized */
window.onresize = function() {
setWrapperMinHeight();
}
});
The Hungarian notation was abused, particularly by Microsoft, leading to prefixes longer than the variable name, and showing it is quite rigid, particularly when you change the types (the infamous lparam/wparam, of different type/size in Win16, identical in Win32).
Thus, both due to this abuse, and its use by M$, it was put down as useless.
At my work, we code in Java, but the founder cames from MFC world, so use similar code style (aligned braces, I like this!, capitals to method names, I am used to that, prefix like m_ to class members (fields), s_ to static members, etc.).
And they said all variables should have a prefix showing its type (eg. a BufferedReader is named brData). Which shown as being a bad idea, as the types can change but the names doesn't follow, or coders are not consistent in the use of these prefixes (I even see aBuffer, theProxy, etc.!).
Personally, I chose for a few prefixes that I find useful, the most important being b to prefix boolean variables, as they are the only ones where I allow syntax like if (bVar)
(no use of autocast of some values to true or false).
When I coded in C, I used a prefix for variables allocated with malloc, as a reminder it should be freed later. Etc.
So, basically, I don't reject this notation as a whole, but took what seems fitting for my needs.
And of course, when contributing to some project (work, open source), I just use the conventions in place!
This works for me.
<div style="position: relative;width:100%;">
<div style="position:absolute;left:0px;background-color:red;width:25%;height:100px;">
This will be on the left
</div>
<div style="position:absolute;right:0px;background-color:blue;width:25%;height:100px;">
This will be on the right
</div>
</div>
Simply alter your table, no need to any thing. just run this query on database.
ALTER TABLE table_name
CONVERT TO CHARACTER SET utf8
it will definately work.
In my case git push
was trying to push more that just the current branch, therefore, I got this error since the other branches were not in sync.
To fix that you could use: git config --global push.default simple
That will make git to only push the current branch.
This will only work on more recent versions of git. i.e.: won't work on 1.7.9.5
I am using Python 3.6 and using a comma between Exception and e does not work. I need to use the following syntax (just for anyone wondering)
try:
connection = manager.connect("I2Cx")
except KeyError as e:
print(e.message)
#if defined(CONDITION1) || defined(CONDITION2)
should work. :)
#ifdef
is a bit less typing, but doesn't work well with more complex conditions
This code should work:
var connect = require("connect");
var app = connect.createServer().use(connect.static(__dirname + '/public'));
app.listen(8180);
Also in connect 2.0 .createServer() method deprecated. Use connect() instead.
var connect = require("connect");
var app = connect().use(connect.static(__dirname + '/public'));
app.listen(8180);
What about jQuery Hotkeys?
jQuery Hotkeys lets you watch for keyboard events anywhere in your code supporting almost any key combination.
To bind Ctrl+c to a function (f
), for example:
$(document).bind('keydown', 'ctrl+c', f);
Windows 7 ( not tested on other versions )
More Info which might help with other versions ... http://www.computerhope.com/issues/ch000549.htm
To get the root view defined in your xml file, without action bar, you can use this:
View root = ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);
So, to change color to white:
root.setBackgroundResource(Color.WHITE);
This worked for me.
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
public Class someClass {
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
private LocalDateTime sinceDate;
}
Here are all of the previous answers summarized:
The code should look like this:
import sys
def hello(a, b):
print "hello and that's your sum:"
sum = a+b
print sum
if __name__== "__main__":
hello(int(sys.argv[1]), int(sys.argv[2]))
Then run the code with this command:
python hello.py 1 1
I write following function which convert base64 in direct way (without conversion to string at the middlestep). IDEA
=
char, remove one/two numbers from output arrayBelow solution allows to process large input base64 strings. Similar function for convert bytes to base64 without btoa is HERE
function base64ToBytesArr(str) {
const abc = [..."ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"]; // base64 alphabet
let result = [];
for(let i=0; i<str.length/4; i++) {
let chunk = [...str.slice(4*i,4*i+4)]
let bin = chunk.map(x=> abc.indexOf(x).toString(2).padStart(6,0)).join('');
let bytes = bin.match(/.{1,8}/g).map(x=> +('0b'+x));
result.push(...bytes.slice(0,3 - (str[4*i+2]=="=") - (str[4*i+3]=="=")));
}
return result;
}
// --------
// TEST
// --------
let test = "Alice's Adventure in Wonderland.";
console.log('test string:', test.length, test);
let b64_btoa = btoa(test);
console.log('encoded string:', b64_btoa);
let decodedBytes = base64ToBytesArr(b64_btoa); // decode base64 to array of bytes
console.log('decoded bytes:', JSON.stringify(decodedBytes));
let decodedTest = decodedBytes.map(b => String.fromCharCode(b) ).join``;
console.log('Uint8Array', JSON.stringify(new Uint8Array(decodedBytes)));
console.log('decoded string:', decodedTest.length, decodedTest);
_x000D_
Use the chrome.runtime.id
property from the chrome.runtime API.
Header files can contain any valid C code, since they are injected into the compilation unit by the pre-processor prior to compilation.
If a header file contains a function, and is included by multiple .c
files, each .c
file will get a copy of that function and create a symbol for it. The linker will complain about the duplicate symbols.
It is technically possible to create static
functions in a header file for inclusion in multiple .c
files. Though this is generally not done because it breaks from the convention that code is found in .c
files and declarations are found in .h
files.
See the discussions in C/C++: Static function in header file, what does it mean? for more explanation.
Access 2010 has both stored procedures, and also has table triggers. And, both features are available even when you not using a server (so, in 100% file based mode).
If you using SQL Server with Access, then of course the stored procedures are built using SQL Server and not Access.
For Access 2010, you open up the table (non-design view), and then choose the table tab. You see options there to create store procedures and table triggers.
For example:
Note that the stored procedure language is its own flavor just like Oracle or SQL Server (T-SQL). Here is example code to update an inventory of fruits as a result of an update in the fruit order table
Keep in mind these are true engine-level table triggers. In fact if you open up that table with VB6, VB.NET, FoxPro or even modify the table on a computer WITHOUT Access having been installed, the procedural code and the trigger at the table level will execute. So, this is a new feature of the data engine jet (now called ACE) for Access 2010. As noted, this is procedural code that runs, not just a single statement.
Window -> Show View -> Other -> Studio/Remote
(Drag this tabbed window wherever)
Click the add FTP button (see below); #profit
Some basic differences can be written in short:
MVC:
Traditional MVC is where there is a
MVP:
Similar to traditional MVC but Controller is replaced by Presenter. But the Presenter, unlike Controller is responsible for changing the view as well. The view usually does not call the presenter.
MVVM
The difference here is the presence of View Model. It is kind of an implementation of Observer Design Pattern, where changes in the model are represented in the view as well, by the VM. Eg: If a slider is changed, not only the model is updated but the data which may be a text, that is displayed in the view is updated as well. So there is a two-way data binding.
This is my Python function:
def add_nulls(num, cnt=2):
cnt = cnt - len(str(num))
nulls = '0' * cnt
return '%s%s' % (nulls, num)
If you use Hadoop version 2.6.1 above, while the command works, it complains that its depreciated. I actually could not use the hadoop dfsadmin -safemode leave
because I was running Hadoop in a Docker container and that command magically fails when run in the container, so what I did was this. I checked doc and found dfs.safemode.threshold.pct
in documentation that says
Specifies the percentage of blocks that should satisfy the minimal replication requirement defined by dfs.replication.min. Values less than or equal to 0 mean not to wait for any particular percentage of blocks before exiting safemode. Values greater than 1 will make safe mode permanent.
so I changed the hdfs-site.xml
into the following (In older Hadoop versions, apparently you need to do it in hdfs-default.xml
:
<configuration>
<property>
<name>dfs.safemode.threshold.pct</name>
<value>0</value>
</property>
</configuration>
var a = 10;
myFunction(a);
function myFunction(a){
window['a'] = 20; // or window.a
}
alert("Value of 'a' outside the function " + a); //outputs 20
With window['variableName'] or window.variableName you can modify the value of a global variable inside a function.
The ioctl
function is useful for implementing a device driver to set the configuration on the device. e.g. a printer that has configuration options to check and set the font family, font size etc. ioctl
could be used to get the current font as well as set the font to a new one. A user application uses ioctl
to send a code to a printer telling it to return the current font or to set the font to a new one.
int ioctl(int fd, int request, ...)
fd
is file descriptor, the one returned by open
;request
is request code. e.g GETFONT
will get the current font from the printer, SETFONT
will set the font on the printer;void *
. Depending on the second argument, the third may or may not be present,
e.g. if the second argument is SETFONT
, the third argument can be the font name such as "Arial"
;int request
is not just a macro. A user application is required to generate a request code and the device driver module to determine which configuration on device must be played with. The application sends the request code using ioctl
and then uses the request code in the device driver module to determine which action to perform.
A request code has 4 main parts
1. A Magic number - 8 bits
2. A sequence number - 8 bits
3. Argument type (typically 14 bits), if any.
4. Direction of data transfer (2 bits).
If the request code is SETFONT
to set font on a printer, the direction for data transfer will be from user application to device driver module (The user application sends the font name "Arial"
to the printer).
If the request code is GETFONT
, direction is from printer to the user application.
In order to generate a request code, Linux provides some predefined function-like macros.
1._IO(MAGIC, SEQ_NO)
both are 8 bits, 0 to 255, e.g. let us say we want to pause printer.
This does not require a data transfer. So we would generate the request code as below
#define PRIN_MAGIC 'P'
#define NUM 0
#define PAUSE_PRIN __IO(PRIN_MAGIC, NUM)
and now use ioctl
as
ret_val = ioctl(fd, PAUSE_PRIN);
The corresponding system call in the driver module will receive the code and pause the printer.
__IOW(MAGIC, SEQ_NO, TYPE)
MAGIC
and SEQ_NO
are the same as above, and TYPE
gives the type of the next argument, recall the third argument of ioctl
is void *
. W in __IOW
indicates that the data flow is from user application to driver module. As an example,
suppose we want to set the printer font to "Arial"
.#define PRIN_MAGIC 'S'
#define SEQ_NO 1
#define SETFONT __IOW(PRIN_MAGIC, SEQ_NO, unsigned long)
further,
char *font = "Arial";
ret_val = ioctl(fd, SETFONT, font);
Now font
is a pointer, which means it is an address best represented as unsigned long
, hence the third part of _IOW
mentions type as such. Also, this address of font is passed to corresponding system call implemented in device driver module as unsigned long
and we need to cast it to proper type before using it. Kernel space can access user space and hence this works. other two function-like macros are __IOR(MAGIC, SEQ_NO, TYPE)
and __IORW(MAGIC, SEQ_NO, TYPE)
where the data flow will be from kernel space to user space and both ways respectively.
Please let me know if this helps!
this takes 7, 10 and 11 digit, removes additional characters and adds dashes by going right to left through the string. change the dash to a space or dot.
$raw_phone = preg_replace('/\D/', '', $raw_phone);
$temp = str_split($raw_phone);
$phone_number = "";
for ($x=count($temp)-1;$x>=0;$x--) {
if ($x === count($temp) - 5 || $x === count($temp) - 8 || $x === count($temp) - 11) {
$phone_number = "-" . $phone_number;
}
$phone_number = $temp[$x] . $phone_number;
}
echo $phone_number;
Elements that are not being rendered (be it through visibility: hidden
, display: none
, opacity: 0.0
, whatever) will not indicate focus. The browser will not draw a focus border around nothing.
If you want the text to be focusable, that's completely doable. You can wrap the whole thing in an element that can receive focus (for example, a hyperlink), or allow another tag to have focus using the tabindex
property:
<label tabindex="0" class="checkbox">
<input type="checkbox" value="valueofcheckbox" style="display:none" checked="checked" />Option Text
</label>
In this case, the <label>
tag above is actually receiving focus and everything within it will have a focus border when it's in focus.
I do question what your goal is. If you're using a hidden checkbox to internally track some sort of state, you might be better off using a <input type="hidden" />
tag instead.
Try:
return DateTime.Now.Subtract(new DateTime(1970, 1,1)).TotalMilliseconds
Edit: true UTC is better, but then we need to be consistent
return DateTime.UtcNow
.Subtract(new DateTime(1970,1,1,0,0,0,DateTimeKind.Utc))
.TotalMilliseconds;
Although, on second thoughts it does not matter, as long as both dates are in the same time zone.
If you want to replace multiple values in a data frame, looping through all columns might help.
Say you want to replace ""
and 100
:
na_codes <- c(100, "")
for (i in seq_along(df)) {
df[[i]][df[[i]] %in% na_codes] <- NA
}
There is this extensions that adds an event listener to attribute changes.
Usage:
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript"
src="https://cdn.rawgit.com/meetselva/attrchange/master/js/attrchange.js"></script>
Bind attrchange handler function to selected elements
$(selector).attrchange({
trackValues: true, /* Default to false, if set to true the event object is
updated with old and new value.*/
callback: function (event) {
//event - event object
//event.attributeName - Name of the attribute modified
//event.oldValue - Previous value of the modified attribute
//event.newValue - New value of the modified attribute
//Triggered when the selected elements attribute is added/updated/removed
}
});
This Kotlin state machine library has PlantUML export feature, it is not integrated with Android Studio but it is easy to visualize state machine structure on PlantUML web site.
For the odd positions, you probably want:
>>>> list_ = list(range(10))
>>>> print list_[1::2]
[1, 3, 5, 7, 9]
>>>>
[For Reference]ThreadLocal cannot solve update problems of shared object. It is recommended to use a staticThreadLocal object which is shared by all operations in the same thread. [Mandatory]remove() method must be implemented by ThreadLocal variables, especially when using thread pools in which threads are often reused. Otherwise, it may affect subsequent business logic and cause unexpected problems such as memory leak.
You don't give a reproducible example but your warning message tells you exactly what the problem is.
memb
only has a length of 10. I'm guessing the length of dih_y2$MemberID
isn't a multiple of 10. When using ==
, R spits out a warning if it isn't a multiple to let you know that it's probably not doing what you're expecting it to do. ==
does element-wise checking for equality. I suspect what you want to do is find which of the elements of dih_y2$MemberID
are also in the vector memb
. To do this you would want to use the %in%
operator.
dih_col <- which(dih_y2$MemeberID %in% memb)
Bypass SSL Certificate....
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
// Pass the handler to httpclient(from you are calling api)
var client = new HttpClient(clientHandler)
They are equivalent, from the standard (emphasis mine) (7.1.3.2):
A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name. It has the same semantics as if it were introduced by the typedef specifier. In particular, it does not define a new type and it shall not appear in the type-id.
One more reason I found (vague as it may sound). The below did not work.
LinearLayout vertical
LinearLayout height fillparent + weight
LinearLayout height fillparent + weight
LinearLayout height fillparent + weight
EndLinearLayout
What did work was
RelativeLayout
LinearLayout vertical
LinearLayout height fillparent + weight
LinearLayout height fillparent + weight
LinearLayout height fillparent + weight
EndLinearLayout
EndRelativeLayout
It sounds vague by a root layout with Linear and weights under it did not work. And when I say "did not work", I mean, that after I viewed the graphical layout between various resolutions the screen consistency broke big time.
We achieved in angular like below.
<input type="file" formControlName="FileUpload" click)="handleFileInput($event.target.files)" />
/>
this.uploadPanel = false;
handleFileInput(files: FileList) {
this.fileToUpload = files.item(0);
console.log("ggg" + files);
this.uploadPanel = true;
}
@HostListener("window:focus", ["$event"])
onFocus(event: FocusEvent): void {
if (this.uploadPanel == true) {
console.log("cancel clicked")
this.addSlot
.get("FileUpload")
.setValidators([
Validators.required,
FileValidator.validate,
requiredFileType("png")
]);
this.addSlot.get("FileUpload").updateValueAndValidity();
}
}
This error is caused by:
Y = Dataset.iloc[:,18].values
Indexing is out of bounds here most probably because there are less than 19 columns in your Dataset, so column 18 does not exist. The following code you provided doesn't use Y at all, so you can just comment out this line for now.
According to the documentation, the different algorithms used by SecureRandom are, in order of preference:
Since you asked about Linux, I'm ignoring the Windows implementation, and also SunPKCS11 which is only really available on Solaris, unless you installed it yourself — and then you wouldn't be asking this question.
According to those same documentation, what these algorithms use are
SHA1PRNG
Initial seeding is currently done via a combination of system attributes and the java.security entropy gathering device.
NativePRNG
nextBytes()
uses /dev/urandom
generateSeed()
uses /dev/random
NativePRNGBlocking
nextBytes()
and generateSeed()
use /dev/random
NativePRNGNonBlocking
nextBytes()
and generateSeed()
use /dev/urandom
That means if you use SecureRandom random = new SecureRandom()
, it goes down that list until it finds one that works, which will typically be NativePRNG. And that means that it seeds itself from /dev/random
(or uses that if you explicitly generate a seed), then uses /dev/urandom
for getting the next bytes, ints, double, booleans, what-have-yous.
Since /dev/random
is blocking (it blocks until it has enough entropy in the entropy pool), that may impede performance.
One solution to that is using something like haveged to generate enough entropy, another solution is using /dev/urandom
instead. While you could set that for the entire jvm, a better solution is doing it for this specific instance of SecureRandom
, by using SecureRandom random = SecureRandom.getInstance("NativePRNGNonBlocking")
. Note that that method can throw a NoSuchAlgorithmException if NativePRNGNonBlocking is unavailable, so be prepared to fallback to the default.
SecureRandom random;
try {
random = SecureRandom.getInstance("NativePRNGNonBlocking");
} catch (NoSuchAlgorithmException nsae) {
random = new SecureRandom();
}
Also note that on other *nix systems, /dev/urandom
may behave differently.
/dev/urandom
random enough?Conventional wisdom has it that only /dev/random
is random enough. However, some voices differ. In "The Right Way to Use SecureRandom" and "Myths about /dev/urandom", it is argued that /dev/urandom/
is just as good.
The users over on the Information Security stack agree with that. Basically, if you have to ask, /dev/urandom
is fine for your purpose.
Just an update to above answers :
If you want to have see changes in the click event, i.e. Color of your UIVIew shud change whenever user clicks the UIView then make changes as below...
class ClickableUIView: UIView {
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = touches.first {
let currentPoint = touch.locationInView(self)
// do something with your currentPoint
}
self.backgroundColor = UIColor.magentaColor()//Color when UIView is clicked.
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = touches.first {
let currentPoint = touch.locationInView(self)
// do something with your currentPoint
}
self.backgroundColor = UIColor.magentaColor()//Color when UIView is clicked.
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = touches.first {
let currentPoint = touch.locationInView(self)
// do something with your currentPoint
}
self.backgroundColor = UIColor.whiteColor()//Color when UIView is not clicked.
}//class closes here
Also, call this Class from Storyboard & ViewController as:
@IBOutlet weak var panVerificationUIView:ClickableUIView!
here is the link for a similar question
CSS select all previous siblings for a star rating
So I post my solution using bits of everyones responses and anyone can use it as reference and possibliy recommend improvements.
// Just to check input value
// Consts
const starRadios = document.querySelectorAll('input[name="rating"]');
// EventListeners
starRadios.forEach((radio) => radio.addEventListener('change', getStarRadioValue));
// Get star radio value
function getStarRadioValue(event) {
alert(event.target.value)
// Do something with it
};
_x000D_
.star-rating {
font-size: 1.5rem;
unicode-bidi: bidi-override;
direction: rtl;
text-align: left;
}
.star-rating.editable label:hover {
cursor: pointer;
}
.star-rating.editable .icon-star:hover,
.star-rating.editable .icon-star:hover ~ .icon-star {
background-color: #fb2727 !important;
}
.icon-star {
position: relative;
background-color: #72747d;
width: 32px;
height: 32px;
display: inline-block;
transition: background-color 0.3s ease;
}
.icon-star.filled {
background-color: #fb2727;
}
.icon-star > label {
display: inline-block;
width: 100%;
height: 100%;
left: 0;
top: 0;
position: absolute;
}
.icon-star > label > input[type="radio"] {
position: absolute;
top: 0;
left: 0;
transform: translateY(50%) translateX(50%);
display: none;
}
_x000D_
<div class="star-rating editable">
<span class="icon-star">
<label>
<input type="radio" name="rating" value="5" />
</label>
</span>
<span class="icon-star">
<label>
<input type="radio" name="rating" value="4" />
</label>
</span>
<span class="icon-star">
<label>
<input type="radio" name="rating" value="3" />
</label>
</span>
<span class="icon-star">
<label>
<input type="radio" name="rating" value="2" />
</label>
</span>
<span class="icon-star">
<label>
<input type="radio" name="rating" value="1" />
</label>
</span>
</div>
_x000D_
From CSS-Tricks... there is a one step way to do this without z-indexing and adding pseudo elements-- requires linear gradient which I think means you need CSS3 support
.tinted-image {
background-image:
/* top, transparent red */
linear-gradient(
rgba(255, 0, 0, 0.45),
rgba(255, 0, 0, 0.45)
),
/* your image */
url(image.jpg);
}
I've tried doing the request you need using an iframe to show the result for latitude, longitude, and zoom needed:
<iframe
width="300"
height="170"
frameborder="0"
scrolling="no"
marginheight="0"
marginwidth="0"
src="https://maps.google.com/maps?q='+YOUR_LAT+','+YOUR_LON+'&hl=es&z=14&output=embed"
>
</iframe>
<br />
<small>
<a
href="https://maps.google.com/maps?q='+data.lat+','+data.lon+'&hl=es;z=14&output=embed"
style="color:#0000FF;text-align:left"
target="_blank"
>
See map bigger
</a>
</small>
The solution I end up using most is based off of Tomas Petricek's answer. I usually want to do something with both the attribute and property.
var props = from p in this.GetType().GetProperties()
let attr = p.GetCustomAttributes(typeof(MyAttribute), true)
where attr.Length == 1
select new { Property = p, Attribute = attr.First() as MyAttribute};
img.UriSource = new Uri("pack://application:,,,/images/" + fileName, UriKind.Absolute);
\d
is a digit (a character in the range 0-9), and +
means 1 or more times. So, \d+
is 1 or more digits.
This is about as simple as regular expressions get. You should try reading up on regular expressions a little bit more. Google has a lot of results for regular expression tutorial, for instance. Or you could try using a tool like the free Regex Coach that will let you enter a regular expression and sample text, then indicate what (if anything) matches the regex.
pip freeze lists all installed packages even if not by pip/easy_install. On CentOs/Redhat a package installed through rpm is found.
All I wanted were 1) English only and 2) just enough to build a legacy desktop project written in C. No Azure, no mobile development, no .NET, and no other components that I don't know what to do with.
[Note: Options are in multiple lines for readability, but they should be in 1 line]
vs_community__xxxxxxxxxx.xxxxxxxxxx.exe
--lang en-US
--layout ".\Visual Studio Cummunity 2017"
--add Microsoft.VisualStudio.Workload.NativeDesktop
--includeRecommended
I chose "NativeDesktop" from "workload and component ID" site (https://docs.microsoft.com/en-us/visualstudio/install/workload-component-id-vs-community).
The result was about 1.6GB downloaded files and 5GB when installed. I'm sure I could have removed a few unnecessary components to save space, but the list was rather long, so I stopped there.
"--includeRecommended" was the key ingredient for me, which included Windows SDK along with other essential things for building the legacy project.
Dim a As Range, b As Range
Set a = Selection
For Each b In a.Rows
MsgBox b.Address
Next
Find a file using wildcard and getting filename:
Resolve-Path "Package.1.0.191.*.zip" | Split-Path -leaf
Read Byte by Byte and check that each byte against '\n'
if it is not, then store it into buffer
if it is '\n'
add '\0'
to buffer and then use atoi()
You can read a single byte like this
char c;
read(fd,&c,1);
See read()
Here is a jquery plugin that allows you to inject CSS:
https://github.com/kajic/jquery-injectCSS
Example:
$.injectCSS({
"#my-window": {
"position": "fixed",
"z-index": 102,
"display": "none",
"top": "50%",
"left": "50%"
}
});
You could use the unique filter from AngularUI (source code available here: AngularUI unique filter) and use it directly in the ng-options (or ng-repeat).
<select ng-model="orderProp" ng-options="place.category for place in places | unique:'category'">
<option value="0">Default</option>
// unique options from the categories
</select>
Concat is the right answer, but for some reason a handrolled thing is getting the most votes. If you like that answer, perhaps you'd like this more general solution even more:
IEnumerable<byte> Combine(params byte[][] arrays)
{
foreach (byte[] a in arrays)
foreach (byte b in a)
yield return b;
}
which would let you do things like:
byte[] c = Combine(new byte[] { 0, 1, 2 }, new byte[] { 3, 4, 5 }).ToArray();
With Visual Studio 2019, running a .net core 3.1 project, you will need to install the latest test framework to resolve the error.
Easiest way to accomplish this is by hovering the browser over a [Test] annotation (underlined in red) and select suggested fixes. The one needed is to "search for and install the latest test framework."
grep command can be used
CA = mydata[grep("CA", mydata$sCode, ]
nrow(CA)
For folks interested in using JDOM, but afraid that hasn't been updated in a while (especially not leveraging Java generics), there is a fork called CoffeeDOM which exactly addresses these aspects and modernizes the JDOM API, read more here:
http://cdmckay.org/blog/2011/05/20/introducing-coffeedom-a-jdom-fork-for-java-5/
and download it from the project page at:
You don't need any extra dependencies for this! Depending on whether you need to optimize for performance or not, there are two good solutions:
URL.hostname
for readabilityIn the Babel era, the cleanest and easiest solution is to use URL.hostname
.
const getHostname = (url) => {
// use URL constructor and return hostname
return new URL(url).hostname;
}
// tests
console.log(getHostname("https://stackoverflow.com/questions/8498592/extract-hostname-name-from-string/"));
console.log(getHostname("https://developer.mozilla.org/en-US/docs/Web/API/URL/hostname"));
_x000D_
URL.hostname
is part of the URL API, supported by all major browsers except IE (caniuse). Use a URL polyfill if you need to support legacy browsers.
Using this solution will also give you access to other URL properties and methods. This will be useful if you also want to extract the URL's pathname or query string params, for example.
URL.hostname
is faster than using the anchor solution or parseUri. However it's still much slower than gilly3's regex:
const getHostnameFromRegex = (url) => {
// run against regex
const matches = url.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
// extract hostname (will be null if no match is found)
return matches && matches[1];
}
// tests
console.log(getHostnameFromRegex("https://stackoverflow.com/questions/8498592/extract-hostname-name-from-string/"));
console.log(getHostnameFromRegex("https://developer.mozilla.org/en-US/docs/Web/API/URL/hostname"));
_x000D_
Test it yourself on this jsPerf
If you need to process a very large number of URLs (where performance would be a factor), use RegEx. Otherwise, use URL.hostname
.
Here is another Linq
approach which extracts the first number out of a string.
string input = "123 foo 456";
int result = 0;
bool success = int.TryParse(new string(input
.SkipWhile(x => !char.IsDigit(x))
.TakeWhile(x => char.IsDigit(x))
.ToArray()), out result);
Examples:
string input = "123 foo 456"; // 123
string input = "foo 456"; // 456
string input = "123 foo"; // 123
If you are looking for swift code:
var titleLabel = UILabel()
titleLabel.font = UIFont(name: "HelveticaNeue-UltraLight",
size: 20.0)
I came up with this three liner.
Essentially, here's what it does:
inp = pd.read_csv('filename.csv') # read input. Add read_csv arguments as needed
columns = pd.DataFrame({'column_names': inp.columns, 'datatypes': inp.dtypes})
columns.to_csv(inp+'columns_list.csv', encoding='utf-8') # encoding is optional
This made my life much easier in trying to generate schemas on the fly. Hope this helps
On Ubuntu 20.04:
sudo apt install subversion
To get the first and last date of Last Month
;
$dateBegin = strtotime("first day of last month");
$dateEnd = strtotime("last day of last month");
echo date("D-F-Y", $dateBegin);
echo "<br>";
echo date("D-F-Y", $dateEnd);
NSString *stringreplace=[yourString stringByReplacingOccurrencesOfString:@"search" withString:@"new_string"];
With one group in the pattern, you can only get one exact result in that group. If your capture group gets repeated by the pattern (you used the +
quantifier on the surrounding non-capturing group), only the last value that matches it gets stored.
You have to use your language's regex implementation functions to find all matches of a pattern, then you would have to remove the anchors and the quantifier of the non-capturing group (and you could omit the non-capturing group itself as well).
Alternatively, expand your regex and let the pattern contain one capturing group per group you want to get in the result:
^([A-Z]+),([A-Z]+),([A-Z]+)$
This is so simple to do on a PC: Windows OS: Send the os a command to change the text: import os
os.system('color a') #green text
print 'I like green'
raw_input('do you?')
private void TurnOnAutocomplete()
{
textBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
textBox.AutoCompleteSource = AutoCompleteSource.CustomSource;
AutoCompleteStringCollection collection = new AutoCompleteStringCollection();
string[] arrayOfWowrds = new string[];
try
{
//Read in data Autocomplete list to a string[]
string[] arrayOfWowrds = new string[];
}
catch (Exception err)
{
MessageBox.Show(err.Message, "File Missing", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
collection.AddRange(arrayOFWords);
textBox.AutoCompleteCustomSource = collection;
}
You only need to call this once after you have your data needed for the autocomplete list. Once bound it stays with the textBox. You do not need to or want to call it every time the text is changed in the textBox, that will kill your program.
Yes. Empty or incomplete headers or response body typically caused by broken connections or server side crash can cause 502 errors if accessed via a gateway or proxy.
For more information about the network errors
The array is being re-indexed when you do a .splice()
, which means you'll skip over an index when one is removed, and your cached .length
is obsolete.
To fix it, you'd either need to decrement i
after a .splice()
, or simply iterate in reverse...
var i = Auction.auctions.length
while (i--) {
...
if (...) {
Auction.auctions.splice(i, 1);
}
}
This way the re-indexing doesn't affect the next item in the iteration, since the indexing affects only the items from the current point to the end of the Array, and the next item in the iteration is lower than the current point.
Basically we had to enable TLS 1.2 for .NET 4.x. Making this registry changed worked for me, and stopped the event log filling up with the Schannel error.
More information on the answer can be found here
Enable TLS 1.2 at the system (SCHANNEL) level:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2]
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001
(equivalent keys are probably also available for other TLS versions)
Tell .NET Framework to use the system TLS versions:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001
This may not be desirable for edge cases where .NET Framework 4.x applications need to have different protocols enabled and disabled than the OS does.
def is_prime(num):
"""Returns True if the number is prime
else False."""
if num == 0 or num == 1:
return False
for x in range(2, num):
if num % x == 0:
return False
else:
return True
>> filter(is_prime, range(1, 20))
[2, 3, 5, 7, 11, 13, 17, 19]
We will get all the prime numbers upto 20 in a list. I could have used Sieve of Eratosthenes but you said you want something very simple. ;)
If you are concerned about memory footprint, the Python standard library contains the array module; these arrays contain elements of the same type.
SELECT A.ABC_ID, A.VAL FROM A WHERE NOT EXISTS
(SELECT * FROM B WHERE B.ABC_ID = A.ABC_ID AND B.VAL = A.VAL)
or
SELECT A.ABC_ID, A.VAL FROM A WHERE VAL NOT IN
(SELECT VAL FROM B WHERE B.ABC_ID = A.ABC_ID)
or
SELECT A.ABC_ID, A.VAL LEFT OUTER JOIN B
ON A.ABC_ID = B.ABC_ID AND A.VAL = B.VAL FROM A WHERE B.VAL IS NULL
Please note that these queries do not require that ABC_ID be in table B at all. I think that does what you want.
SVG has properties width
and height
. They return an object SVGAnimatedLength
with two properties: animVal
and baseVal
. This interface is used for animation, where baseVal
is the value before animation. From what I can see, this method returns consistent values in both Chrome and Firefox, so I think it can also be used to get calculated size of SVG.
Ok, finally found the solution.
Probably due to lack of experience with ReactJS and web development...
var Task = React.createClass({
render: function() {
var percentage = this.props.children + '%';
....
<div className="ui-progressbar-value ui-widget-header ui-corner-left" style={{width : percentage}}/>
...
I created the percentage variable outside in the render function.
To restore all those deleted files in a folder, enter the following command.
git ls-files -d | xargs git checkout --
Running any shell command inside $(...)
will help to store the output in a variable. So using that we can convert the files to array with IFS
.
IFS=' ' read -r -a array <<< $(ls /path/to/dir)
Get or set the length of vectors (including lists) and factors, and of any other R object for which a method has been defined.
Get the length of each element of a list or atomic vector (is.atomic) as an integer or numeric vector.
Alternatively there's the application called LiveReload...
I suggest using a custom Adapter, first create a Xml-file, for example layout/customlistview.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" >
<ImageView
android:id="@+id/image"
android:layout_alignParentRight="true"
android:paddingRight="4dp" />
<TextView
android:id="@+id/title"
android:layout_toLeftOf="@id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="23sp"
android:maxLines="1" />
<TextView
android:id="@+id/subtitle"
android:layout_toLeftOf="@id/image" android:layout_below="@id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Assuming you have a custom class like this
public class CustomClass {
private long id;
private String title, subtitle, picture;
public CustomClass () {
}
public CustomClass (long id, String title, String subtitle, String picture) {
this.id = id;
this.title= title;
this.subtitle= subtitle;
this.picture= picture;
}
//add getters and setters
}
And a CustomAdapter.java
uses the xml-layout
public class CustomAdapter extends ArrayAdapter {
private Context context;
private int resource;
private LayoutInflater inflater;
public CustomAdapter (Context context, List<CustomClass> values) { // or String[][] or whatever
super(context, R.layout.customlistviewitem, values);
this.context = context;
this.resource = R.layout.customlistview;
this.inflater = LayoutInflater.from(context);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = (RelativeLayout) inflater.inflate(resource, null);
CustomClass item = (CustomClass) getItem(position);
TextView textviewTitle = (TextView) convertView.findViewById(R.id.title);
TextView textviewSubtitle = (TextView) convertView.findViewById(R.id.subtitle);
ImageView imageview = (ImageView) convertView.findViewById(R.id.image);
//fill the textviews and imageview with the values
textviewTitle = item.getTtile();
textviewSubtitle = item.getSubtitle();
if (item.getAfbeelding() != null) {
int imageResource = context.getResources().getIdentifier("drawable/" + item.getImage(), null, context.getPackageName());
Drawable image = context.getResources().getDrawable(imageResource);
}
imageview.setImageDrawable(image);
return convertView;
}
}
Did you manage to do it? Feel free to ask if you want more info on something :)
EDIT: Changed the adapter to suit a List instead of just a List
I see answer for sql server, well here it is for MySql using a transaction
Dim sql As String = "INSERT INTO Empleado (nombres, apepaterno, apematerno, direccion, colonia, cp, municipio, estado, tel, cel, correo, idrol, relojchecadorid, relojchecadorid2, `activo`,`extras`,`rfc`,`nss`,`curp`,`imagen`,sueldoXHra, IMSSCotiza, thumb) VALUES (@nombres, @apepaterno, @apematerno, @direccion, @colonia, @cp, @municipio, @estado, @tel, @cel, @correo, @idrol, @relojchecadorid, @relojchecadorid2, @activo, @extras, @rfc, @nss, @curp, @imagen,@sueldoXHra,@IMSSCotiza, @thumb)"
Using connection As IDbConnection = New MySqlConnection(getConnectionString())
connection.Open()
Using transaction = connection.BeginTransaction
Dim res = connection.Execute(sql, New With {reg.nombres, reg.apepaterno, reg.apematerno, reg.direccion, reg.colonia, reg.cp, reg.municipio, reg.estado, reg.tel, reg.cel, reg.correo, reg.idrol, reg.relojchecadorid, reg.relojchecadorid2, reg.activo, reg.extras, reg.rfc, reg.nss, reg.curp, reg.imagen, reg.thumb, reg.sueldoXHra, reg.IMSSCotiza}, commandTimeout:=180, transaction:=transaction)
lastInsertedId = connection.ExecuteScalar("SELECT LAST_INSERT_ID();", transaction:=transaction)
If res > 0 Then
transaction.Commit()
return true
end if
End Using
End Using
In order to make <tbody>
element scrollable, we need to change the way it's displayed on the page i.e. using display: block;
to display that as a block level element.
Since we change the display
property of tbody
, we should change that property for thead
element as well to prevent from breaking the table layout.
So we have:
thead, tbody { display: block; }
tbody {
height: 100px; /* Just for the demo */
overflow-y: auto; /* Trigger vertical scroll */
overflow-x: hidden; /* Hide the horizontal scroll */
}
Web browsers display the thead
and tbody
elements as row-group (table-header-group
and table-row-group
) by default.
Once we change that, the inside tr
elements doesn't fill the entire space of their container.
In order to fix that, we have to calculate the width of tbody
columns and apply the corresponding value to the thead
columns via JavaScript.
Here is the jQuery version of above logic:
// Change the selector if needed
var $table = $('table'),
$bodyCells = $table.find('tbody tr:first').children(),
colWidth;
// Get the tbody columns width array
colWidth = $bodyCells.map(function() {
return $(this).width();
}).get();
// Set the width of thead columns
$table.find('thead tr').children().each(function(i, v) {
$(v).width(colWidth[i]);
});
And here is the output (on Windows 7 Chrome 32):
As the Original Poster needed, we could expand the table
to 100% of width
of its container, and then using a relative (Percentage) width
for each columns of the table.
table {
width: 100%; /* Optional */
}
tbody td, thead th {
width: 20%; /* Optional */
}
Since the table has a (sort of) fluid layout, we should adjust the width of thead
columns when the container resizes.
Hence we should set the columns' widths once the window is resized:
// Adjust the width of thead cells when *window* resizes
$(window).resize(function() {
/* Same as before */
}).resize(); // Trigger the resize handler once the script runs
The output would be:
I've tested the two above methods on Windows 7 via the new versions of major Web Browsers (including IE10+) and it worked.
However, it doesn't work properly on IE9 and below.
That's because in a table layout, all elements should follow the same structural properties.
By using display: block;
for the <thead>
and <tbody>
elements, we've broken the table structure.
One approach is to redesign the (entire) table layout. Using JavaScript to create a new layout on the fly and handle and/or adjust the widths/heights of the cells dynamically.
For instance, take a look at the following examples:
This approach uses two nested tables with a containing div. The first table
has only one cell which has a div
, and the second table is placed inside that div
element.
Check the Vertical scrolling tables at CSS Play.
This works on most of web browsers. We can also do the above logic dynamically via JavaScript.
Since the purpose of adding vertical scroll bar to the <tbody>
is displaying the table header at the top of each row, we could position the thead
element to stay fixed
at the top of the screen instead.
Here is a Working Demo of this approach performed by Julien.
It has a promising web browser support.
And here a pure CSS implementation by Willem Van Bockstal.
Here is the old answer. Of course I've added a new method and refined the CSS declarations.
In this case, the table
should have a fixed width
(including the sum of columns' widths and the width of vertical scroll-bar).
Each column should have a specific width and the last column of thead
element needs a greater width which equals to the others' width + the width of vertical scroll-bar.
Therefore, the CSS would be:
table {
width: 716px; /* 140px * 5 column + 16px scrollbar width */
border-spacing: 0;
}
tbody, thead tr { display: block; }
tbody {
height: 100px;
overflow-y: auto;
overflow-x: hidden;
}
tbody td, thead th {
width: 140px;
}
thead th:last-child {
width: 156px; /* 140px + 16px scrollbar width */
}
Here is the output:
In this approach, the table
has a width of 100%
and for each th
and td
, the value of width
property should be less than 100% / number of cols
.
Also, we need to reduce the width of thead
as value of the width of vertical scroll-bar.
In order to do that, we need to use CSS3 calc()
function, as follows:
table {
width: 100%;
border-spacing: 0;
}
thead, tbody, tr, th, td { display: block; }
thead tr {
/* fallback */
width: 97%;
/* minus scroll bar width */
width: -webkit-calc(100% - 16px);
width: -moz-calc(100% - 16px);
width: calc(100% - 16px);
}
tr:after { /* clearing float */
content: ' ';
display: block;
visibility: hidden;
clear: both;
}
tbody {
height: 100px;
overflow-y: auto;
overflow-x: hidden;
}
tbody td, thead th {
width: 19%; /* 19% is less than (100% / 5 cols) = 20% */
float: left;
}
Here is the Online Demo.
Note: This approach will fail if the content of each column breaks the line, i.e. the content of each cell should be short enough.
In the following, there are two simple example of pure CSS solution which I created at the time I answered this question.
Here is the jsFiddle Demo v2.
Old version: jsFiddle Demo v1
I had the same problem, my aspnet button's click was not firing. It turns out that some where on other part of the page has an input with html "required" attribute on.
This might be sound strange, but once I remove the required attribute, the button just works normally.
For getting all the info about the cordova package use this command:
npm info cordova
The answer depends on the presence of other shapes, level of noise if any and invariance you want to provide for (e.g. rotation, scaling, etc). These requirements will define not only the algorithm but also required pre-procesing stages to extract features.
Template matching that was suggested above works well when shapes aren't rotated or scaled and when there are no similar shapes around; in other words, it finds a best translation in the image where template is located:
double minVal, maxVal;
Point minLoc, maxLoc;
Mat image, template, result; // template is your shape
matchTemplate(image, template, result, CV_TM_CCOEFF_NORMED);
minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc); // maxLoc is answer
Geometric hashing is a good method to get invariance in terms of rotation and scaling; this method would require extraction of some contour points.
Generalized Hough transform can take care of invariance, noise and would have minimal pre-processing but it is a bit harder to implement than other methods. OpenCV has such transforms for lines and circles.
In the case when number of shapes is limited calculating moments or counting convex hull vertices may be the easiest solution: openCV structural analysis
Try:
Type type = Type.GetType(inputString); //target type
object o = Activator.CreateInstance(type); // an instance of target type
YourType your = (YourType)o;
Jon Skeet is right as usually :)
Update: You can specify assembly containing target type in various ways, as Jon mentioned, or:
YourType your = (YourType)Activator.CreateInstance("AssemblyName", "NameSpace.MyClass");
You can use TEXT
type, which is not limited to 64KB.
select * into newtable from oldtable
Compact form for short commands (no 'echo'):
IF "%ID%"=="0" ( ... & ... & ... ) ELSE ^
IF "%ID%"=="1" ( ... ) ELSE ^
IF "%ID%"=="2" ( ... ) ELSE ^
REM default case...
After ^
must be an immediate line end, no spaces.
git fetch --prune
-p, --prune
After fetching, remove any remote-tracking branches which no longer exist on the remote. prune options
If you have two unix timestamps, you can use this function (made a little more verbose for the sake of clarity):
// Calculate number of days between two unix timestamps
// ------------------------------------------------------------
var daysBetween = function(timeStampA, timeStampB) {
var oneDay = 24 * 60 * 60 * 1000; // hours * minutes * seconds * milliseconds
var firstDate = new Date(timeStampA * 1000);
var secondDate = new Date(timeStampB * 1000);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
return diffDays;
};
Example:
daysBetween(1096580303, 1308713220); // 2455
As an extension to Hiale's solution, you could provide a different or modified version that supports processes that have multiple main windows.
First, amend the structure to allow storing of multiple handles:
struct handle_data {
unsigned long process_id;
std::vector<HWND> handles;
};
Second, amend the callback function:
BOOL CALLBACK enum_windows_callback(HWND handle, LPARAM lParam)
{
handle_data& data = *(handle_data*)lParam;
unsigned long process_id = 0;
GetWindowThreadProcessId(handle, &process_id);
if (data.process_id != process_id || !is_main_window(handle)) {
return TRUE;
}
// change these 2 lines to allow storing of handle and loop again
data.handles.push_back(handle);
return TRUE;
}
Finally, amend the returns on the main function:
std::vector<HWD> find_main_window(unsigned long process_id)
{
handle_data data;
data.process_id = process_id;
EnumWindows(enum_windows_callback, (LPARAM)&data);
return data.handles;
}
If you are in a loop, let's say that you loop through a list of punctuation characters that you want to remove, you can do something like this:
private const string PunctuationChars = ".,!?$";
foreach (var word in words)
{
var word_modified = word;
var modified = false;
foreach (var punctuationChar in PunctuationChars)
{
if (word.IndexOf(punctuationChar) > 0)
{
modified = true;
word_modified = word_modified.Replace("" + punctuationChar, "");
}
}
//////////MORE CODE
}
The trick being the following:
word_modified.Replace("" + punctuationChar, "");
Adding more to Jason's more generalized way of retrieving the POST data or GET data
from flask_restful import reqparse
def parse_arg_from_requests(arg, **kwargs):
parse = reqparse.RequestParser()
parse.add_argument(arg, **kwargs)
args = parse.parse_args()
return args[arg]
form_field_value = parse_arg_from_requests('FormFieldValue')
Instead of NOW()
you can use UNIX_TIMESTAMP()
also:
$update_query = "UPDATE db.tablename
SET insert_time=UNIX_TIMESTAMP()
WHERE username='$somename'";
You're right, it's localhost\SQLEXPRESS
(just no $
) and yes, it's the same for both 2005 and 2008 express versions.
After trying everything, Yowsup library worked for me. The bug that I was facing was recently fixed. Anyone trying to do something with Whatsapp should try it.
As @Raheel Answered it will fine but if you are working with Laravel 7/6
Then Eloquent whereIn
Query.
Example1:
$users = User::wherein('id',[1,2,3])->get();
Example2:
$users = DB::table('users')->whereIn('id', [1, 2, 3])->get();
Example3:
$ids = [1,2,3];
$users = User::wherein('id',$ids)->get();
You can use :nth-last-child()
; in fact, besides :nth-last-of-type()
I don't know what else you could use. I'm not sure what you mean by "dynamic", but if you mean whether the style applies to the new second last child when more children are added to the list, yes it will. Interactive fiddle.
ul li:nth-last-child(2)
Here is a BFS recursive traversal Python implementation, working for a graph with no cycle.
def bfs_recursive(level):
'''
@params level: List<Node> containing the node for a specific level.
'''
next_level = []
for node in level:
print(node.value)
for child_node in node.adjency_list:
next_level.append(child_node)
if len(next_level) != 0:
bfs_recursive(next_level)
class Node:
def __init__(self, value):
self.value = value
self.adjency_list = []
This should about cut it (i'll leave the error handling to you):
int slashIndex = url.lastIndexOf('/');
int dotIndex = url.lastIndexOf('.', slashIndex);
String filenameWithoutExtension;
if (dotIndex == -1) {
filenameWithoutExtension = url.substring(slashIndex + 1);
} else {
filenameWithoutExtension = url.substring(slashIndex + 1, dotIndex);
}
Java 6, now support TLS 1.2, check out below
http://www.oracle.com/technetwork/java/javase/overview-156328.html#R160_121
With some error catching. Specifically, most of the functions presented require $end to exist, when in fact in my case I needed it to be optional. Use this is $end is optional, and evaluate for FALSE if $start doesn't exist at all:
function get_string_between( $string, $start, $end ){
$string = " " . $string;
$start_ini = strpos( $string, $start );
$end = strpos( $string, $end, $start+1 );
if ($start && $end) {
return substr( $string, $start_ini + strlen($start), strlen( $string )-( $start_ini + $end ) );
} elseif ( $start && !$end ) {
return substr( $string, $start_ini + strlen($start) );
} else {
return FALSE;
}
}
When you are using Google Chrome you can use/abuse the Google Filesystem API
for this. Here you can create a file with a specified name and write the content of a blob to it. Then you can return the result to the user.
I have not found a good way for Firefox yet; probably a small piece of Flash like downloadify
is required to name a blob.
IE10 has a msSaveBlob()
function in the BlobBuilder
.
Maybe this is more for downloading a blob, but it is related.
pyMedia's sound example does just that. This should be all you need.
import time, wave, pymedia.audio.sound as sound
f= wave.open( 'YOUR FILE NAME', 'rb' )
sampleRate= f.getframerate()
channels= f.getnchannels()
format= sound.AFMT_S16_LE
snd= sound.Output( sampleRate, channels, format )
s= f.readframes( 300000 )
snd.play( s )
I used this function as a form validation tool, and I didn't want users to be able to write exponential function, so I came up with this function:
<script>
function isNumber(value, acceptScientificNotation) {
if(true !== acceptScientificNotation){
return /^-{0,1}\d+(\.\d+)?$/.test(value);
}
if (true === Array.isArray(value)) {
return false;
}
return !isNaN(parseInt(value, 10));
}
console.log(isNumber("")); // false
console.log(isNumber(false)); // false
console.log(isNumber(true)); // false
console.log(isNumber("0")); // true
console.log(isNumber("0.1")); // true
console.log(isNumber("12")); // true
console.log(isNumber("-12")); // true
console.log(isNumber(-45)); // true
console.log(isNumber({jo: "pi"})); // false
console.log(isNumber([])); // false
console.log(isNumber([78, 79])); // false
console.log(isNumber(NaN)); // false
console.log(isNumber(Infinity)); // false
console.log(isNumber(undefined)); // false
console.log(isNumber("0,1")); // false
console.log(isNumber("1e-1")); // false
console.log(isNumber("1e-1", true)); // true
</script>
string = string.replace(/[\W_]/g, "_");
See the following snippet, is this what you want?
body {
background: silver;
padding: 0 10px;
}
#content:after {
height: 10px;
display: block;
width: 100px;
background: #808080;
border-right: 1px white;
content: '';
}
#footer:before {
display: block;
content: '';
background: silver;
height: 10px;
margin-top: -20px;
margin-left: 101px;
}
#content {
background: white;
}
#footer {
padding-top: 10px;
background: #404040;
}
p {
padding: 100px;
text-align: center;
}
#footer p {
color: white;
}
_x000D_
<body>
<div id="content"><p>#content</p></div>
<div id="footer"><p>#footer</p></div>
</body>
_x000D_
Not out of the box in Sql Server Management Studio, but it is a feature of the very good SSMS Tools Pack
A workaround - at least for the minimum size: You can use grid to manage the frames contained in root and make them follow the grid size by setting sticky='nsew'. Then you can use root.grid_rowconfigure and root.grid_columnconfigure to set values for minsize like so:
from tkinter import Frame, Tk
class MyApp():
def __init__(self):
self.root = Tk()
self.my_frame_red = Frame(self.root, bg='red')
self.my_frame_red.grid(row=0, column=0, sticky='nsew')
self.my_frame_blue = Frame(self.root, bg='blue')
self.my_frame_blue.grid(row=0, column=1, sticky='nsew')
self.root.grid_rowconfigure(0, minsize=200, weight=1)
self.root.grid_columnconfigure(0, minsize=200, weight=1)
self.root.grid_columnconfigure(1, weight=1)
self.root.mainloop()
if __name__ == '__main__':
app = MyApp()
But as Brian wrote (in 2010 :D) you can still resize the window to be smaller than the frame if you don't limit its minsize.
You can use this to work cmd in C#:
ProcessStartInfo proStart = new ProcessStartInfo();
Process pro = new Process();
proStart.FileName = "cmd.exe";
proStart.WorkingDirectory = @"D:\...";
string arg = "/c your_argument";
proStart.Arguments = arg;
proStart.WindowStyle = ProcessWindowStyle.Hidden;
pro.StartInfo = pro;
pro.Start();
Don't forget to write /c before your argument !!
I'm not sure if it's worth it, but you can emulate Java's named loops with a few simple macros:
#define LOOP_NAME(name) \
if ([[maybe_unused]] constexpr bool _namedloop_InvalidBreakOrContinue = false) \
{ \
[[maybe_unused]] CAT(_namedloop_break_,name): break; \
[[maybe_unused]] CAT(_namedloop_continue_,name): continue; \
} \
else
#define BREAK(name) goto CAT(_namedloop_break_,name)
#define CONTINUE(name) goto CAT(_namedloop_continue_,name)
#define CAT(x,y) CAT_(x,y)
#define CAT_(x,y) x##y
Example usage:
#include <iostream>
int main()
{
// Prints:
// 0 0
// 0 1
// 0 2
// 1 0
// 1 1
for (int i = 0; i < 3; i++) LOOP_NAME(foo)
{
for (int j = 0; j < 3; j++)
{
std::cout << i << ' ' << j << '\n';
if (i == 1 && j == 1)
BREAK(foo);
}
}
}
Another example:
#include <iostream>
int main()
{
// Prints:
// 0
// 1
// 0
// 1
// 0
// 1
int count = 3;
do LOOP_NAME(foo)
{
for (int j = 0; j < 3; j++)
{
std::cout << ' ' << j << '\n';
if (j == 1)
CONTINUE(foo);
}
}
while(count-- > 1);
}
This is how you do it in Visual Studio 2010.
Because it is finicky, this can be quite painful, actually, because you are trying to do something so incredibly simple, but it isn't straight forward and there are many gotchas that Visual Studio doesn't tell you about. If at any point you feel angry or like you want to sink your teeth into a 2 by 4 and scream, by all means, please do so.
Gotchas:
1) Open VIEW > RESOURCE VIEW (in the middle of the VIEW menu), or press Ctrl+Shift+E to get it to appear.
2) In Resource view, right click the project name and say ADD > RESOURCE...
3) Assuming you have already generated an .ico file yourself, choose Icon from the list of crap that appears, then click IMPORT.
4) At this dialog *.ico
files aren't listed, and you can't use a regular PNG or JPG image as an icon, so change the file filter to *.ico
using the dropdown. Misleading UI, I know, I know.
5) If you compile your project now, it will automatically stick the .ico with the lowest ID (as listed in resource.h
) as the icon of your .exe file.
6) If you load a bunch of ICO files into the project for whatever reason, be sure the .ico you want Visual Studio to use has the lowest id in resource.h
. You can edit this file manually with no problems
Eg.
//resource.h
#define IDI_ICON1 102
#define IDI_ICON2 103
IDI_ICON1 is used
//resource.h
#define IDI_ICON1 106
#define IDI_ICON2 103
Now IDI_ICON2 is used.
Try to add display:inline;
to the CSS property of a button.
The warning is issued since you are using backslashes in your strings. If you want to avoid the message, type this command "set standard_conforming_strings=on;". Then use "E" before your string including backslashes that you want postgresql to intrepret.
What worked for me was:
git config --global fetch.prune true
Now it keeps on running prune automatically.
You forgot the () at the end. It is not a variable, but a function and when there are not parameters, you still need the () at the end.
For future coding practices, I would highly recommend reforming the code a little bit as this can become frustrating to read:
public string LastName
{ get { return lastName; } set { lastName = value; } }
If there is any kind of processing which happens in here (thankfully doesn't happen here), it will become very confusing. If you're going to pass your code onto someone else, I would recommend:
public string LastName
{
get
{
return lastName;
}
set
{
lastName = value;
}
}
It's a lot longer, but it's much easier to read when glancing at a huge section of code.
I had some ajax commands I wanted to run with a delay in between. Here is a simple example of one way to do that. I am prepared to be ripped to shreds though for my unconventional approach. :)
// Show current seconds and milliseconds
// (I know there are other ways, I was aiming for minimal code
// and fixed width.)
function secs()
{
var s = Date.now() + ""; s = s.substr(s.length - 5);
return s.substr(0, 2) + "." + s.substr(2);
}
// Log we're loading
console.log("Loading: " + secs());
// Create a list of commands to execute
var cmds =
[
function() { console.log("A: " + secs()); },
function() { console.log("B: " + secs()); },
function() { console.log("C: " + secs()); },
function() { console.log("D: " + secs()); },
function() { console.log("E: " + secs()); },
function() { console.log("done: " + secs()); }
];
// Run each command with a second delay in between
var ms = 1000;
cmds.forEach(function(cmd, i)
{
setTimeout(cmd, ms * i);
});
// Log we've loaded (probably logged before first command)
console.log("Loaded: " + secs());
You can copy the code block and paste it into a console window and see something like:
Loading: 03.077
Loaded: 03.078
A: 03.079
B: 04.075
C: 05.075
D: 06.075
E: 07.076
done: 08.076
In some cases margin="0 auto" won't cut the mustard when center aligning a html email in Outlook 2007, 2010, 2013.
Try the following:
Wrap your content in another table with style="table-layout: fixed;" and align=“center”.
<!-- WRAPPING TABLE -->
<table cellpadding="0" cellspacing="0" border="0" style="table-layout: fixed;" align="center">
<tr>
<td>
<!-- YOUR TABLES AND EMAIL CONTENT GOES HERE -->
</td>
</tr>
</table>
A little late for the party, here's how I do it
./shutdown.sh
/work/Catalina/...
./startup.sh
/webapps
and start it.If anybody is looking for Java firestore sdk solution to add items in array field:
List<String> list = java.util.Arrays.asList("A", "B");
Object[] fieldsToUpdate = list.toArray();
DocumentReference docRef = getCollection().document("docId");
docRef.update(fieldName, FieldValue.arrayUnion(fieldsToUpdate));
To delete items from array user: FieldValue.arrayRemove()
An other possible solution:
for(Object it : set.toArray()) { /* Create a copy */
Integer element = (Integer)it;
if(element % 2 == 0)
set.remove(element);
}
Or:
Integer[] copy = new Integer[set.size()];
set.toArray(copy);
for(Integer element : copy) {
if(element % 2 == 0)
set.remove(element);
}
Write to a file test.txt:
String filepath ="/mnt/sdcard/test.txt";
FileOutputStream fos = null;
try {
fos = new FileOutputStream(filepath);
byte[] buffer = "This will be writtent in test.txt".getBytes();
fos.write(buffer, 0, buffer.length);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(fos != null)
fos.close();
}
Read from file test.txt:
String filepath ="/mnt/sdcard/test.txt";
FileInputStream fis = null;
try {
fis = new FileInputStream(filepath);
int length = (int) new File(filepath).length();
byte[] buffer = new byte[length];
fis.read(buffer, 0, length);
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(fis != null)
fis.close();
}
Note: don't forget to add these two permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
None of these solutions worked for me - but by deleting the contents of bin and obj folders everything was cool again.
I had this same problem, common also to other borwsers like Firefox. Finally I discovered that dynamically create an element with animated gif inside at form submit did not animate, so I developed the following workaorund.
1) At document.ready()
, each FORM found in page, receive position:relative
property and then to each one is attached an invisible DIV.bg-overlay
.
2) After this, assuming that each submit value of my website is identified by btn-primary
css class, again at document.ready()
, I look for these buttons, traverse to the FORM parent of each one, and at form submit, I fire showOverlayOnFormExecution(this,true);
function, passing clicked button and a boolean that toggle visibility of DIV.bg-overlay
.
$(document).ready(function() {
//Append LOADING image to all forms
$('form').css('position','relative').append('<div class="bg-overlay" style="display:none;"><img src="/images/loading.gif"></div>');
//At form submit, fires a specific function
$('form .btn-primary').closest('form').submit(function (e) {
showOverlayOnFormExecution(this,true);
});
});
CSS for DIV.bg-overlay
is the following:
.bg-overlay
{
width:100%;
height:100%;
position:absolute;
top:0;
left:0;
background:rgba(255,255,255,0.6);
z-index:100;
}
.bg-overlay img
{
position:absolute;
left:50%;
top:50%;
margin-left:-40px; //my loading images is 80x80 px. This is done to center it horizontally and vertically.
margin-top:-40px;
max-width:auto;
max-height:80px;
}
3) At any form submit, the following function is fired to show a semi-white background overlay all over it (that deny ability to interact again with form) and an animated gif inside it (that visually show a loading action).
function showOverlayOnFormExecution(clicked_button, showOrNot)
{
if(showOrNot == 1)
{
//Add "content" of #bg-overlay_container (copying it) to the confrm that contains clicked button
$(clicked_button).closest('form').find('.bg-overlay').show();
}
else
$('form .bg-overlay').hide();
}
Showing animated gif at form submit, instead of appending it at this event, solves "gif animation freeze" problem of various browsers (as said, I found this problem in IE and Firefox, not in Chrome)
List <String> list = new ArrayList();
list.add("behold");
list.add("bend");
list.add("bet");
list.add("bear");
list.add("beat");
list.add("become");
list.add("begin");
List <String> listClone = new ArrayList<String>();
for (String string : list) {
if(string.matches("(?i)(bea).*")){
listClone.add(string);
}
}
System.out.println(listClone);
Move all of your state and your handleClick
function from Header
to your MainWrapper
component.
Then pass values as props to all components that need to share this functionality.
class MainWrapper extends React.Component {
constructor() {
super();
this.state = {
sidbarPushCollapsed: false,
profileCollapsed: false
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({
sidbarPushCollapsed: !this.state.sidbarPushCollapsed,
profileCollapsed: !this.state.profileCollapsed
});
}
render() {
return (
//...
<Header
handleClick={this.handleClick}
sidbarPushCollapsed={this.state.sidbarPushCollapsed}
profileCollapsed={this.state.profileCollapsed} />
);
Then in your Header's render() method, you'd use this.props
:
<button type="button" id="sidbarPush" onClick={this.props.handleClick} profile={this.props.profileCollapsed}>
I had, pretty much, the same problem. I was able to see that PDO was enabled but I had no available drivers (using PHP 7-RC4). I managed to resolve the issue by adding the php_pdo_mysql extension to those which were enabled.
Hope this helps!
public class SmsListener extends BroadcastReceiver{
private SharedPreferences preferences;
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
Bundle bundle = intent.getExtras(); //---get the SMS message passed in---
SmsMessage[] msgs = null;
String msg_from;
if (bundle != null){
//---retrieve the SMS message received---
try{
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for(int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
msg_from = msgs[i].getOriginatingAddress();
String msgBody = msgs[i].getMessageBody();
}
}catch(Exception e){
// Log.d("Exception caught",e.getMessage());
}
}
}
}
}
Note: In your manifest file add the BroadcastReceiver-
<receiver android:name=".listener.SmsListener">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
Add this permission:
<uses-permission android:name="android.permission.RECEIVE_SMS" />
I had the same issue and atom-goto-definition (package name goto-definition) worked like charm for me. Please try once. You can download directly from Atom.
This package is DEPRECATED. Please check it in Github.
To reload opener window with all parameters (not all be sent with window.location.href method and method with form.submit() is maybe one step to late) i prefer to use window.history method.
window.opener.history.go(0);
You can use a LENGTH(that_string)
minus the number of characters
you want to remove in the SUBSTRING()
select perhaps or use the TRIM()
function.
In your XML set Background
attribute to any colour White(#FFFFFF)
shade or Black(#000000)
shade.if you want transparency just put 80 before the actual hash code.
#80000000
You will have to open the file in one way or another if you want to access the data within it. Obviously, one way is to open it in your Excel application instance, e.g.:-
(untested code)
Dim wbk As Workbook
Set wbk = Workbooks.Open("C:\myworkbook.xls")
' now you can manipulate the data in the workbook anyway you want, e.g. '
Dim x As Variant
x = wbk.Worksheets("Sheet1").Range("A6").Value
Call wbk.Worksheets("Sheet2").Range("A1:G100").Copy
Call ThisWorbook.Worksheets("Target").Range("A1").PasteSpecial(xlPasteValues)
Application.CutCopyMode = False
' etc '
Call wbk.Close(False)
Another way to do it would be to use the Excel ADODB provider to open a connection to the file and then use SQL to select data from the sheet you want, but since you are anyway working from within Excel I don't believe there is any reason to do this rather than just open the workbook. Note that there are optional parameters for the Workbooks.Open() method to open the workbook as read-only, etc.
Use Math.Round(double);
I have used it myself. It actually rounds off the decimal places.
d = 19.82;
ans = Math.round(d);
System.out.println(ans);
// Output : 20
d = 19.33;
ans = Math.round(d);
System.out.println(ans);
// Output : 19
Hope it Helps :-)