The simple answer:
doing a MOV RBX, 3 and MUL RBX is expensive; just ADD RBX, RBX twice
ADD 1 is probably faster than INC here
MOV 2 and DIV is very expensive; just shift right
64-bit code is usually noticeably slower than 32-bit code and the alignment issues are more complicated; with small programs like this you have to pack them so you are doing parallel computation to have any chance of being faster than 32-bit code
If you generate the assembly listing for your C++ program, you can see how it differs from your assembly.
Sybase has the same case syntax as SQL Server:
Supports conditional SQL expressions; can be used anywhere a value expression can be used.
case
when search_condition then expression
[when search_condition then expression]...
[else expression]
end
case expression
when expression then expression
[when expression then expression]...
[else expression]
end
begins the case expression.
precedes the search condition or the expression to be compared.
is used to set conditions for the results that are selected. Search conditions for case expressions are similar to the search conditions in a where clause. Search conditions are detailed in the Transact-SQL User’s Guide.
precedes the expression that specifies a result value of case.
is a column name, a constant, a function, a subquery, or any combination of column names, constants, and functions connected by arithmetic or bitwise operators. For more information about expressions, see “Expressions” in.
select disaster,
case
when disaster = "earthquake"
then "stand in doorway"
when disaster = "nuclear apocalypse"
then "hide in basement"
when monster = "zombie apocalypse"
then "hide with Chuck Norris"
else
then "ask mom"
end
from endoftheworld
The Dim keyword is optional, when we are using it with modifiers- Public, Protected, Friend, Protected Friend,Private,Shared,Shadows,Static,ReadOnly etc.
e.g. - Static nTotal As Integer
For reference type, we have to use new keyword to create the new instance of the class or structure. e.g. Dim lblTop As New System.Windows.Forms.Label
.
Dim statement can be used with out a datatype when you set Option Infer to On. In that case the compiler infers the data type of a variable from the type of its initialization expression. Example :
Option Infer On
Module SampleMod
Sub Main()
Dim nExpVar = 5
The above statement is equivalent to- Dim nExpVar As Integer
You can always use the plot()
function like so:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
ys = [i+x+(i*x)**2 for i in range(10)]
plt.figure()
for y in ys:
plt.plot(x, y, 'o')
plt.show()
In general this error message means that you have tried to use indexing on a function. You can reproduce this error message with, for example
mean[1]
## Error in mean[1] : object of type 'closure' is not subsettable
mean[[1]]
## Error in mean[[1]] : object of type 'closure' is not subsettable
mean$a
## Error in mean$a : object of type 'closure' is not subsettable
The closure mentioned in the error message is (loosely) the function and the environment that stores the variables when the function is called.
In this specific case, as Joshua mentioned, you are trying to access the url
function as a variable. If you define a variable named url
, then the error goes away.
As a matter of good practise, you should usually avoid naming variables after base-R functions. (Calling variables data
is a common source of this error.)
There are several related errors for trying to subset operators or keywords.
`+`[1]
## Error in `+`[1] : object of type 'builtin' is not subsettable
`if`[1]
## Error in `if`[1] : object of type 'special' is not subsettable
If you're running into this problem in shiny
, the most likely cause is that you're trying to work with a reactive
expression without calling it as a function using parentheses.
library(shiny)
reactive_df <- reactive({
data.frame(col1 = c(1,2,3),
col2 = c(4,5,6))
})
While we often work with reactive expressions in shiny as if they were data frames, they are actually functions that return data frames (or other objects).
isolate({
print(reactive_df())
print(reactive_df()$col1)
})
col1 col2
1 1 4
2 2 5
3 3 6
[1] 1 2 3
But if we try to subset it without parentheses, then we're actually trying to index a function, and we get an error:
isolate(
reactive_df$col1
)
Error in reactive_df$col1 : object of type 'closure' is not subsettable
All the random methods end up calling random.random()
so the best way is to call it directly:
[int(1000*random.random()) for i in xrange(10000)]
For example,
random.randint
calls random.randrange
.random.randrange
has a bunch of overhead to check the range before returning istart + istep*int(self.random() * n)
.NumPy is much faster still of course.
The accepted answer doesn't work for UILocalNotification. For some reason, %%%%
(4 percent signs) or the unicode character '\uFF05
' only work for this.
So to recap, when formatting your string you may use %%
. However, if your string is part of a UILocalNotification, use %%%%
or \uFF05
.
Blinking text with HTML and CSS only
<span class="blinking">I am blinking!!!</span>
And Now CSS code
.blinking{
animation:blinkingText 0.8s infinite;
}
@keyframes blinkingText{
0%{ color: #000; }
49%{ color: transparent; }
50%{ color: transparent; }
99%{ color:transparent; }
100%{ color: #000; }
}
I wrote a class to handle this, as it seems to be a recurring need in my various projects:
https://github.com/koush/UrlImageViewHelper
UrlImageViewHelper will fill an ImageView with an image that is found at a URL.
The sample will do a Google Image Search and load/show the results asynchronously.
UrlImageViewHelper will automatically download, save, and cache all the image urls the BitmapDrawables. Duplicate urls will not be loaded into memory twice. Bitmap memory is managed by using a weak reference hash table, so as soon as the image is no longer used by you, it will be garbage collected automatically.
Here I used the replace()
function.
function titleCase(str){
return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
The Joda-Time project is in maintenance-mode, now supplanted by java.time classes.
java.time.Instant
class.LocalDateTime
java.sql.Timestamp
Capture current moment in UTC.
Instant.now()
To store that moment in database:
myPreparedStatement.setObject( … , Instant.now() ) // Writes an `Instant` to database.
To retrieve that moment from datbase:
myResultSet.getObject( … , Instant.class ) // Instantiates a `Instant`
To adjust the wall-clock time to that of a particular time zone.
instant.atZone( z ) // Instantiates a `ZonedDateTime`
LocalDateTime
is the wrong classOther Answers are correct, but they fail to point out that LocalDateTime
is the wrong class for your purpose.
In both java.time and Joda-Time, a LocalDateTime
purposely lacks any concept of time zone or offset-from-UTC. As such, it does not represent a moment, and is not a point on the timeline. A LocalDateTime
represents a rough idea about potential moments along a range of about 26-27 hours.
Use a LocalDateTime
for either when the zone/offset is unknown (not a good situation), or when the zone-offset is indeterminate. For example, “Christmas starts at first moment of December 25, 2018” would be represented as a LocalDateTime
.
Use a ZonedDateTime
to represent a moment in a particular time zone. For example, Christmas starting in any particular zone such as Pacific/Auckland
or America/Montreal
would be represented with a ZonedDateTime
object.
For a moment always in UTC, use Instant
.
Instant instant = Instant.now() ; // Capture the current moment in UTC.
Apply a time zone. Same moment, same point on the timeline, but viewed with a different wall-clock time.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ; // Same moment, different wall-clock time.
So, if I can just convert between LocalDate and LocalDateTime,
No, wrong strategy. If you have a date-only value, and you want a date-time value, you must specify a time-of-day. That time-of-day may not be valid on that date for a particular zone – in which case ZonedDateTime
class automatically adjusts the time-of-day as needed.
LocalDate ld = LocalDate.of( 2018 , Month.JANUARY , 23 ) ;
LocalTime lt = LocalTime.of( 14 , 0 ) ; // 14:00 = 2 PM.
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
If you want the first moment of the day as your time-of-day, let java.time determine that moment. Do not assume the day starts at 00:00:00. Anomalies such as Daylight Saving Time (DST) mean the day may start at another time such as 01:00:00.
ZonedDateTime zdt = ld.atStartOfDay( z ) ;
java.sql.Timestamp
is the wrong classThe java.sql.Timestamp
is part of the troublesome old date-time classes that are now legacy, supplanted entirely by the java.time classes. That class was used to represent a moment in UTC with a resolution of nanoseconds. That purpose is now served with java.time.Instant
.
getObject
/setObject
As of JDBC 4.2 and later, your JDBC driver can directly exchange java.time objects with the database by calling:
For example:
myPreparedStatement.setObject( … , instant ) ;
… and …
Instant instant = myResultSet.getObject( … , Instant.class ) ;
If you must interface with old code not yet updated to java.time, convert back and forth using new methods added to the old classes.
Instant instant = myJavaSqlTimestamp.toInstant() ; // Going from legacy class to modern class.
…and…
java.sql.Timestamp myJavaSqlTimestamp = java.sql.Timestamp.from( instant ) ; // Going from modern class to legacy class.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
There is a way to remove a child element via SimpleXml. The code looks for a element, and does nothing. Otherwise it adds the element to a string. It then writes out the string to a file. Also note that the code saves a backup before overwriting the original file.
$username = $_GET['delete_account'];
echo "DELETING: ".$username;
$xml = simplexml_load_file("users.xml");
$str = "<?xml version=\"1.0\"?>
<users>";
foreach($xml->children() as $child){
if($child->getName() == "user") {
if($username == $child['name']) {
continue;
} else {
$str = $str.$child->asXML();
}
}
}
$str = $str."
</users>";
echo $str;
$xml->asXML("users_backup.xml");
$myFile = "users.xml";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $str);
fclose($fh);
There is no difference between the two, one is just a shorthand for the second.
The v- prefix serves as a visual cue for identifying Vue-specific attributes in your templates. This is useful when you are using Vue.js to apply dynamic behavior to some existing markup, but can feel verbose for some frequently used directives. At the same time, the need for the v- prefix becomes less important when you are building an SPA where Vue.js manages every template.
<!-- full syntax -->
<a v-on:click="doSomething"></a>
<!-- shorthand -->
<a @click="doSomething"></a>
Source: official documentation.
The solution you are looking for is in Angular's official tutorial. In this tutorial Phones are loaded from a JSON file using Angulars $http service . In the code below we use $http.get to load a phones.json file saved in the phones directory:
var phonecatApp = angular.module('phonecatApp', []);
phonecatApp.controller('PhoneListCtrl', function ($scope, $http) {
$http.get('phones/phones.json').success(function(data) {
$scope.phones = data;
});
$scope.orderProp = 'age';
});
We then iterate over the phones:
<table>
<tbody ng-repeat="i in phones">
<tr><td>{{i.name}}</td><td>{{$index}}</td></tr>
<tr ng-repeat="e in i.details">
<td>{{$index}}</td>
<td>{{e.foo}}</td>
<td>{{e.bar}}</td></tr>
</tbody>
</table>
A couple of answers that should work above but this is how i would write it.
Also, i wouldn't declare controllers inside templates. It's better to declare them on your routes imo.
add-text.tpl.html
<div ng-controller="myController">
<form ng-submit="addText(myText)">
<input type="text" placeholder="Let's Go" ng-model="myText">
<button type="submit">Add</button>
</form>
<ul>
<li ng-repeat="text in arrayText">{{ text }}</li>
</ul>
</div>
app.js
(function() {
function myController($scope) {
$scope.arrayText = ['hello', 'world'];
$scope.addText = function(myText) {
$scope.arrayText.push(myText);
};
}
angular.module('app', [])
.controller('myController', myController);
})();
I wrote the following code to convert an image from sdcard to a Base64 encoded string to send as a JSON object.And it works great:
String filepath = "/sdcard/temp.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
fis = new FileInputStream(imagefile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);
byte[] b = baos.toByteArray();
encImage = Base64.encodeToString(b, Base64.DEFAULT);
You'll want to use the process.argv
array to access the command-line arguments to get the filename and the FileSystem module (fs) to read the file. For example:
// Make sure we got a filename on the command line.
if (process.argv.length < 3) {
console.log('Usage: node ' + process.argv[1] + ' FILENAME');
process.exit(1);
}
// Read the file and print its contents.
var fs = require('fs')
, filename = process.argv[2];
fs.readFile(filename, 'utf8', function(err, data) {
if (err) throw err;
console.log('OK: ' + filename);
console.log(data)
});
To break that down a little for you process.argv
will usually have length two, the zeroth item being the "node" interpreter and the first being the script that node is currently running, items after that were passed on the command line. Once you've pulled a filename from argv then you can use the filesystem functions to read the file and do whatever you want with its contents. Sample usage would look like this:
$ node ./cat.js file.txt
OK: file.txt
This is file.txt!
[Edit] As @wtfcoder mentions, using the "fs.readFile()
" method might not be the best idea because it will buffer the entire contents of the file before yielding it to the callback function. This buffering could potentially use lots of memory but, more importantly, it does not take advantage of one of the core features of node.js - asynchronous, evented I/O.
The "node" way to process a large file (or any file, really) would be to use fs.read()
and process each available chunk as it is available from the operating system. However, reading the file as such requires you to do your own (possibly) incremental parsing/processing of the file and some amount of buffering might be inevitable.
To be consistent with what is probably the most likely source of generating a time span (computing the difference of 2 times or date-times), you may want to store a .NET TimeSpan
as a SQL Server DateTime
Type.
This is because in SQL Server, the difference of 2 DateTime
's (Cast
to Float
's and then Cast
back to a DateTime
) is simply a DateTime
relative to Jan. 1, 1900. Ex. A difference of +0.1 second would be January 1, 1900 00:00:00.100 and -0.1 second would be Dec. 31, 1899 23:59:59.900.
To convert a .NET TimeSpan
to a SQL Server DateTime
Type, you would first convert it to a .NET DateTime
Type by adding it to a DateTime
of Jan. 1, 1900. Of course, when you read it into .NET from SQL Server, you would first read it into a .NET DateTime
and then subtract Jan. 1, 1900 from it to convert it to a .NET TimeSpan
.
For use cases where the time spans are being generated from SQL Server DateTime
's and within SQL Server (i.e. via T-SQL) and SQL Server is prior to 2016, depending on your range and precision needs, it may not be practical to store them as milliseconds (not to mention Ticks
) because the Int
Type returned by DateDiff
(vs. the BigInt
from SS 2016+'s DateDiff_Big
) overflows after ~24 days worth of milliseconds and ~67 yrs. of seconds. Whereas, this solution will handle time spans with precision down to 0.1 seconds and from -147 to +8,099 yrs..
WARNINGS:
This would only work if the difference relative to Jan. 1, 1900 would result in a value within the range of a SQL Server DateTime
Type (Jan. 1, 1753 to Dec. 31, 9999 aka -147 to +8,099 yrs.). We don't have to worry near as much on the .NET TimeSpan
side, since it can hold ~29 k to +29 k yrs. I didn't mention the SQL Server DateTime2
Type (whose range, on the negative side, is much greater than SQL Server DateTime
's), because: a) it cannot be converted to a numeric via a simple Cast
and b) DateTime
's range should suffice for the vast majority of use cases.
SQL Server DateTime
differences computed via the Cast
- to - Float
- and - back method does not appear to be accurate beyond 0.1 seconds.
import datetime
a = '2010-01-31'
datee = datetime.datetime.strptime(a, "%Y-%m-%d")
datee.month
Out[9]: 1
datee.year
Out[10]: 2010
datee.day
Out[11]: 31
I'd use request for this:
request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))
Or if you don't need to save to a file first, and you just need to read the CSV into memory, you can do the following:
var request = require('request');
request.get('http://www.whatever.com/my.csv', function (error, response, body) {
if (!error && response.statusCode == 200) {
var csv = body;
// Continue with your processing here.
}
});
etc.
you must use [ngModel] instead of two way model binding with [(ngModel)]. then use manual change event with (ngModelChange). this is public rule for all two way input in components.
because pipe on event emitter is wrong.
Google's Android Developer site has instructions on how to "Add Google Play Services to Your Project", and they are also relevant to how to upgrade the Play Services version. There is even a drop down menu to view instructions for either Eclipse, Android Studio, or "Something else". That would be the best place to view instructions in case they change. The page is here:
http://developer.android.com/google/play-services/setup.html
But since most of the answers here are for Eclipse, here is a brief summary for upgrading Play Services with Android Studio
You can find the version number for the version of play-services that you have downloaded on your development machine by looking in your \sdk\extras\google\m2repository\com\google\android\gms\play-services folder, as explained here: How do I match a Google Play Services revision with an install version?
Here's a reasonable alternative if you don't have control over defining the exceptions. Use the name of the exception variable to categorize the exceptions when they are caught. Then check for the exception variable after the try/catch block.
$ABError = null;
try {
// something
} catch (AError $ABError) { // let the exception fall through
} catch (BError $ABError) { // let the exception fall through
} catch (Exception $e) {
handler2($e);
}
if ($ABError) {
handler1($ABError);
}
This somewhat odd looking approach is probably only worth it if there is a lot of duplication between catch block implementations.
Just to clear some things up here. The answer that was accepted does not do the same as PHP in_array.
To do the same as PHP in_array use following expression:
{% if myVar in myArray %}
If you want to negate this you should use this:
{% if myVar not in myArray %}
I did test your code and the only problem I could see was the lack of permission given to the directory you try to write the file in to.
Give "write" permission to the directory you need to put the file. In your case it is the current directory.
Use "chmod" in linux.
Add "Everyone" with "write" enabled to the security tab of the directory if you are in Windows.
The above answers didn't work for me. Possibly the option names were changed since '11, but the following did the trick for me:
ChartJsProvider.setOptions
scaleBeginAtZero: true
I suggest keeping your icons separate from FontAwesome and create and maintain your own custom library. Personally, I think it is much easier to maintain keeping FontAwesome separate if you are going to be creating your own icon library. You can then have FontAwesome loaded into your site from a CDN and never have to worry about keeping it up-to-date.
When creating your own custom icons, create each icon via Adobe Illustrator or similar software. Once your icons are created, save each individually in SVG
format on your computer.
Next, head on over to IcoMoon: http://icomoon.io , which has the best font generating software (in my opinion), and it's free. IcoMoon will allow you to import your individual svg-saved fonts into a font library, then generate your custom icon glyph library in eot
, ttf
, woff
, and svg
. One format IcoMoon does not generate is woff2
.
After generating your icon pack at IcoMoon, head over to FontSquirrel: http://fontsquirrel.com and use their font generator. Use your ttf
file generated at IcoMoon. In the newly generated icon pack created, you'll now have your icon pack in woff2
format.
Make sure the files for eot
, ttf
, svg
, woff
, and woff2
are all the same name. You are generating an icon pack from two different websites/software, and they do name their generated output differently.
You'll have CSS generated for your icon pack at both locations. But the CSS generated at IcoMoon will not include the woff2
format in your @font-face {}
declaration. Make sure to add that when you're adding your CSS to your project:
@font-face {
font-family: 'customiconpackname';
src: url('../fonts/customiconpack.eot?lchn8y');
src: url('../fonts/customiconpack.eot?lchn8y#iefix') format('embedded-opentype'),
url('../fonts/customiconpack.ttf?lchn8y') format('truetype'),
url('../fonts/customiconpack.woff2?lchn8y') format('woff'),
url('../fonts/customiconpack.woff?lchn8y') format('woff'),
url('../fonts/customiconpack.svg?lchn8y#customiconpack') format('svg');
font-weight: normal;
font-style: normal;
}
Keep in mind that you can get the glyph unicode values of each icon in your icon pack using the IcoMoon software. These values can be helpful in assigning your icons via CSS, as in (assuming we're using the font-family
declared in the example @font-face {...}
above):
selector:after {
font-family: 'customiconpackname';
content: '\e953';
}
You can also get the glyph unicode value e953
if you open the font-pack-generated svg
file in a text editor. E.g.:
<glyph unicode="" glyph-name="eye" ... />
I found the smoothest way to achieve this was using Pageant as the SSH agent and plink.
You need to have a putty session configured for the hostname that is used in your remote.
You will also need plink.exe which can be downloaded from the same site as putty.
And you need Pageant running with your key loaded. I have a shortcut to pageant in my startup folder that loads my SSH key when I log in.
When you install git-scm you can then specify it to use tortoise/plink rather than OpenSSH.
The net effect is you can open git-bash whenever you like and push/pull without being challenged for passphrases.
Same applies with putty and WinSCP sessions when pageant has your key loaded. It makes life a hell of a lot easier (and secure).
Apart from the other already mentioned valid use cases std::weak_ptr
is an awesome tool in a multithreaded environment, because
std::shared_ptr
in conjunction with std::weak_ptr
is safe against dangling pointers - in opposite to std::unique_ptr
in conjunction with raw pointers std::weak_ptr::lock()
is an atomic operation (see also About thread-safety of weak_ptr)Consider a task to load all images of a directory (~10.000) simultaneously into memory (e.g. as a thumbnail cache). Obviously the best way to do this is a control thread, which handles and manages the images, and multiple worker threads, which load the images. Now this is an easy task. Here's a very simplified implementation (join()
etc is omitted, the threads would have to be handled differently in a real implementation etc)
// a simplified class to hold the thumbnail and data
struct ImageData {
std::string path;
std::unique_ptr<YourFavoriteImageLibData> image;
};
// a simplified reader fn
void read( std::vector<std::shared_ptr<ImageData>> imagesToLoad ) {
for( auto& imageData : imagesToLoad )
imageData->image = YourFavoriteImageLib::load( imageData->path );
}
// a simplified manager
class Manager {
std::vector<std::shared_ptr<ImageData>> m_imageDatas;
std::vector<std::unique_ptr<std::thread>> m_threads;
public:
void load( const std::string& folderPath ) {
std::vector<std::string> imagePaths = readFolder( folderPath );
m_imageDatas = createImageDatas( imagePaths );
const unsigned numThreads = std::thread::hardware_concurrency();
std::vector<std::vector<std::shared_ptr<ImageData>>> splitDatas =
splitImageDatas( m_imageDatas, numThreads );
for( auto& dataRangeToLoad : splitDatas )
m_threads.push_back( std::make_unique<std::thread>(read, dataRangeToLoad) );
}
};
But it becomes much more complicated, if you want to interrupt the loading of the images, e.g. because the user has chosen a different directory. Or even if you want to destroy the manager.
You'd need thread communication and have to stop all loader threads, before you may change your m_imageDatas
field. Otherwise the loaders would carry on loading until all images are done - even if they are already obsolete. In the simplified example, that wouldn't be too hard, but in a real environment things can be much more complicated.
The threads would probably be part of a thread pool used by multiple managers, of which some are being stopped, and some aren't etc. The simple parameter imagesToLoad
would be a locked queue, into which those managers push their image requests from different control threads with the readers popping the requests - in an arbitrary order - at the other end. And so the communication becomes difficult, slow and error-prone. A very elegant way to avoid any additional communication in such cases is to use std::shared_ptr
in conjunction with std::weak_ptr
.
// a simplified reader fn
void read( std::vector<std::weak_ptr<ImageData>> imagesToLoad ) {
for( auto& imageDataWeak : imagesToLoad ) {
std::shared_ptr<ImageData> imageData = imageDataWeak.lock();
if( !imageData )
continue;
imageData->image = YourFavoriteImageLib::load( imageData->path );
}
}
// a simplified manager
class Manager {
std::vector<std::shared_ptr<ImageData>> m_imageDatas;
std::vector<std::unique_ptr<std::thread>> m_threads;
public:
void load( const std::string& folderPath ) {
std::vector<std::string> imagePaths = readFolder( folderPath );
m_imageDatas = createImageDatas( imagePaths );
const unsigned numThreads = std::thread::hardware_concurrency();
std::vector<std::vector<std::weak_ptr<ImageData>>> splitDatas =
splitImageDatasToWeak( m_imageDatas, numThreads );
for( auto& dataRangeToLoad : splitDatas )
m_threads.push_back( std::make_unique<std::thread>(read, dataRangeToLoad) );
}
};
This implementation is nearly as easy as the first one, doesn't need any additional thread communication, and could be part of a thread pool/queue in a real implementation. Since the expired images are skipped, and non-expired images are processed, the threads never would have to be stopped during normal operation. You could always safely change the path or destroy your managers, since the reader fn checks, if the owning pointer isn't expired.
To display the all details for each news post title ie. "news.id" which is the primary key, you need to use GROUP BY clause for "news.id"
SELECT news.id, users.username, news.title, news.date,
news.body, COUNT(comments.id)
FROM news
LEFT JOIN users
ON news.user_id = users.id
LEFT JOIN comments
ON comments.news_id = news.id
GROUP BY news.id
<a href="javascript:;" onclick="window.location = 'http://example.com/submit.php?url=' + escape(document.location.href);'">Go</a>;
This works better in my case if you have object or multi-dimensional array. It will shows only first items, other will be just ignored in loop.
.filter('limitItems', function () {
return function (items) {
var result = {}, i = 1;
angular.forEach(items, function(value, key) {
if (i < 5) {
result[key] = value;
}
i = i + 1;
});
return result;
};
});
Change 5 on what you want.
<?php
$sessionDetails = $this->Session->read('Auth.User');
if (!empty($sessionDetails)) {
$loginFlag = 1;
# code...
}else{
$loginFlag = 0;
}
?>
<script type="text/javascript">
var sessionValue = '<?php echo $loginFlag; ?>';
if (sessionValue = 0) {
//model show
}
</script>
The best thing to do is to install the Tampermonkey extension.
This will allow you to easily install Greasemonkey scripts, and to easily manage them. Also it makes it easier to install userscripts directly from sites like OpenUserJS, MonkeyGuts, etc.
Finally, it unlocks most all of the GM functionality that you don't get by installing a GM script directly with Chrome. That is, more of what GM on Firefox can do, is available with Tampermonkey.
But, if you really want to install a GM script directly, it's easy a right pain on Chrome these days...
You can still drag a file to the extensions page and it will work... Until you restart Chrome. Then it will be permanently disabled. See Continuing to "protect" Chrome users from malicious extensions for more information. Again, Tampermonkey is the smart way to go. (Or switch browsers altogether to Opera or Firefox.)
Chrome is changing the way extensions are installed. Userscripts are pared-down extensions on Chrome but. Starting in Chrome 21, link-click behavior is disabled for userscripts. To install a user script, drag the **.user.js* file into the Extensions page (chrome://extensions
in the address input).
Merely drag your **.user.js* files into any Chrome window. Or click on any Greasemonkey script-link.
You'll get an installation warning:
Click Continue.
You'll get a confirmation dialog:
Click Add.
Notes:
By default, Chrome installs scripts in the Extensions folder1, full of cryptic names and version numbers. And, if you try to manually add a script under this folder tree, it will be wiped the next time Chrome restarts.
To control the directories and filenames to something more meaningful, you can:
Create a directory that's convenient to you, and not where Chrome normally looks for extensions. For example, Create: C:\MyChromeScripts\
.
For each script create its own subdirectory. For example, HelloWorld
.
In that subdirectory, create or copy the script file. For example, Save this question's code as: HelloWorld.user.js
.
You must also create a manifest file in that subdirectory, it must be named: manifest.json
.
For our example, it should contain:
{
"manifest_version": 2,
"content_scripts": [ {
"exclude_globs": [ ],
"include_globs": [ "*" ],
"js": [ "HelloWorld.user.js" ],
"matches": [ "https://stackoverflow.com/*",
"https://stackoverflow.com/*"
],
"run_at": "document_end"
} ],
"converted_from_user_script": true,
"description": "My first sensibly named script!",
"name": "Hello World",
"version": "1"
}
The manifest.json
file is automatically generated from the meta-block by Chrome, when an user script is installed. The values of @include
and @exclude
meta-rules are stored in include_globs
and exclude_globs
, @match
(recommended) is stored in the matches
list. "converted_from_user_script": true
is required if you want to use any of the supported GM_*
methods.
Now, in Chrome's Extension manager (URL = chrome://extensions/), Expand "Developer mode".
Click the Load unpacked extension... button.
For the folder, paste in the folder for your script, In this example it is: C:\MyChromeScripts\HelloWorld
.
Your script is now installed, and operational!
If you make any changes to the script source, hit the Reload link for them to take effect:
1 The folder defaults to:
Windows XP: Chrome : %AppData%\..\Local Settings\Application Data\Google\Chrome\User Data\Default\Extensions\ Chromium: %AppData%\..\Local Settings\Application Data\Chromium\User Data\Default\Extensions\ Windows Vista/7/8: Chrome : %LocalAppData%\Google\Chrome\User Data\Default\Extensions\ Chromium: %LocalAppData%\Chromium\User Data\Default\Extensions\ Linux: Chrome : ~/.config/google-chrome/Default/Extensions/ Chromium: ~/.config/chromium/Default/Extensions/ Mac OS X: Chrome : ~/Library/Application Support/Google/Chrome/Default/Extensions/ Chromium: ~/Library/Application Support/Chromium/Default/Extensions/
Although you can change it by running Chrome with the --user-data-dir=
option.
Sounds like you need to change the path to your java
executable to match the newest version.
Basically, installing the latest Java does not necessarily mean your machine is configured to use the latest version. You didn't mention any platform details, so that's all I can say.
If you simply want to reduce your button image:
yourButton.contentMode = UIViewContentModeScaleAspectFit;
yourButton.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
It's method syntax (which I find easier to read) but this might do it
Updated post comment
Use .FirstOrDefault()
instead of .First()
With regard to the dates average, you may have to drop that ordering for the moment as I am unable to get to an IDE at the moment
var groupByReference = context.Measurements
.GroupBy(m => m.Reference)
.Select(g => new {Creation = g.FirstOrDefault().CreationTime,
// Avg = g.Average(m => m.CreationTime.Ticks),
Items = g })
.OrderBy(x => x.Creation)
// .ThenBy(x => x.Avg)
.Take(numOfEntries)
.ToList();
Try this
SELECT *
FROM categories
LEFT JOIN user_category_subscriptions
ON user_category_subscriptions.category_id = categories.category_id
WHERE user_category_subscriptions.user_id = 1
or user_category_subscriptions.user_id is null
$('#btnSubmit').click(function(){
alert("button");
});
or
//Use this code if button is appended in the DOM
$(document).on('click','#btnSubmit',function(){
alert("button");
});
See documentation for more information:
https://api.jquery.com/click/
Use the oncontextmenu
event.
Here's an example:
<div oncontextmenu="javascript:alert('success!');return false;">
Lorem Ipsum
</div>
And using event listeners (credit to rampion from a comment in 2011):
el.addEventListener('contextmenu', function(ev) {
ev.preventDefault();
alert('success!');
return false;
}, false);
Don't forget to return false, otherwise the standard context menu will still pop up.
If you are going to use a function you've written rather than javascript:alert("Success!")
, remember to return false in BOTH the function AND the oncontextmenu
attribute.
Use Date object:
var time = Date.parse('02.02.1999');
document.writeln(time);
Give: 917902800000
Yes, you can. Download the plugin (*.hpi file) and put it in the following directory:
<jenkinsHome>/plugins/
Afterwards you will need to restart Jenkins.
you can use the below code to bring focus to a div, in this example the page scrolls to the <div id="navigation">
$('html, body').animate({ scrollTop: $('#navigation').offset().top }, 'slow');
And now a keys iterator for range-based for loop.
template<typename C>
class keys_it
{
typename C::const_iterator it_;
public:
using key_type = typename C::key_type;
using pointer = typename C::key_type*;
using difference_type = std::ptrdiff_t;
keys_it(const typename C::const_iterator & it) : it_(it) {}
keys_it operator++(int ) /* postfix */ { return it_++ ; }
keys_it& operator++( ) /* prefix */ { ++it_; return *this ; }
const key_type& operator* ( ) const { return it_->first ; }
const key_type& operator->( ) const { return it_->first ; }
keys_it operator+ (difference_type v ) const { return it_ + v ; }
bool operator==(const keys_it& rhs) const { return it_ == rhs.it_; }
bool operator!=(const keys_it& rhs) const { return it_ != rhs.it_; }
};
template<typename C>
class keys_impl
{
const C & c;
public:
keys_impl(const C & container) : c(container) {}
const keys_it<C> begin() const { return keys_it<C>(std::begin(c)); }
const keys_it<C> end () const { return keys_it<C>(std::end (c)); }
};
template<typename C>
keys_impl<C> keys(const C & container) { return keys_impl<C>(container); }
Usage:
std::map<std::string,int> my_map;
// fill my_map
for (const std::string & k : keys(my_map))
{
// do things
}
That's what i was looking for. But nobody had it, it seems.
You get my OCD code alignment as a bonus.
As an exercise, write your own for values(my_map)
The following solution works only for single page reports. Refer to comments for more details.
ReportViewer is a server control and thus can not be used within a razor view. However you can add a ASPX view page, view user control or traditional web form that containing a ReportViewer into the application.
You will need to ensure that you have added the relevant handler into your web.config.
If you use a ASPX view page or view user control you will need to set AsyncRendering to false to get the report to display properly.
Update:
Added more sample code. Note there are no meaningful changes required in Global.asax.
Web.Config
Mine ended up as follows:
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=152368
-->
<configuration>
<appSettings>
<add key="webpages:Version" value="1.0.0.0"/>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
<add assembly="Microsoft.ReportViewer.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages"/>
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
<handlers>
<add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
Controller
The controller actions are very simple.
As a bonus the File() action returns the output of "TestReport.rdlc" as a PDF file.
using System.Web.Mvc;
using Microsoft.Reporting.WebForms;
...
public class PDFController : Controller
{
public ActionResult Index()
{
return View();
}
public FileResult File()
{
ReportViewer rv = new Microsoft.Reporting.WebForms.ReportViewer();
rv.ProcessingMode = ProcessingMode.Local;
rv.LocalReport.ReportPath = Server.MapPath("~/Reports/TestReport.rdlc");
rv.LocalReport.Refresh();
byte[] streamBytes = null;
string mimeType = "";
string encoding = "";
string filenameExtension = "";
string[] streamids = null;
Warning[] warnings = null;
streamBytes = rv.LocalReport.Render("PDF", null, out mimeType, out encoding, out filenameExtension, out streamids, out warnings);
return File(streamBytes, mimeType, "TestReport.pdf");
}
public ActionResult ASPXView()
{
return View();
}
public ActionResult ASPXUserControl()
{
return View();
}
}
ASPXView.apsx
The ASPXView is as follows.
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<%@ Register Assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title>ASPXView</title>
</head>
<body>
<div>
<script runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
ReportViewer1.LocalReport.ReportPath = Server.MapPath("~/Reports/TestReport.rdlc");
ReportViewer1.LocalReport.Refresh();
}
</script>
<form id="Form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<rsweb:reportviewer id="ReportViewer1" runat="server" height="500" width="500" AsyncRendering="false"></rsweb:reportviewer>
</form>
</div>
</body>
</html>
ViewUserControl1.ascx
The ASPX user control looks like:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%@ Register Assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>
<script runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
ReportViewer1.LocalReport.ReportPath = Server.MapPath("~/Reports/TestReport.rdlc");
ReportViewer1.LocalReport.Refresh();
}
</script>
<form id="Form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<rsweb:ReportViewer ID="ReportViewer1" runat="server" AsyncRendering="false"></rsweb:ReportViewer>
</form>
ASPXUserControl.cshtml
Razor view. Requires ViewUserControl1.ascx.
@{
ViewBag.Title = "ASPXUserControl";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>ASPXUserControl</h2>
@Html.Partial("ViewUserControl1")
References
Try:
mysql -u username -p database_name < file.sql
Check MySQL Options.
Note: It is better to use the full path of the SQL file file.sql
.
As with many questions lately, Java 8 to the rescue:
Java 8 added a new static method to java.lang.String
which does exactly what you want:
public static String join(CharSequence delimeter, CharSequence... elements);
Using it:
String s = String.join(", ", new String[] {"Hello", "World", "!"});
Results in:
"Hello, World, !"
If you want to delete an item from the repository, but keep it locally as an unversioned file/folder, use Extended Context Menu ? Delete (keep local). You have to hold the Shift key while right clicking on the item in the explorer list pane (right pane) in order to see this in the extended context menu.
Delete completely:
right mouse click ? Menu ? Delete
Delete & Keep local:
Shift + right mouse click ? Menu ? Delete
You can also use 'name' instead of 'href' for a cleaner url:
$('a[name^=#]').click(function(){
var target = $(this).attr('name');
if (target == '#')
$('html, body').animate({scrollTop : 0}, 600);
else
$('html, body').animate({
scrollTop: $(target).offset().top - 100
}, 600);
});
less than 2 seconds per user usually - ie users that see slower responses than this think the system is slow.
Now you tell me how many users you have connected.
If I understand your questions correctly, all you need to do is add the .Where(m => m.r.u.UserId == 1):
var UserInRole = db.UserProfiles.
Join(db.UsersInRoles, u => u.UserId, uir => uir.UserId,
(u, uir) => new { u, uir }).
Join(db.Roles, r => r.uir.RoleId, ro => ro.RoleId, (r, ro) => new { r, ro })
.Where(m => m.r.u.UserId == 1)
.Select (m => new AddUserToRole
{
UserName = m.r.u.UserName,
RoleName = m.ro.RoleName
});
Hope that helps.
There are two common approaches for this:
Specify http-proxy-
options in your /etc/.subversion/servers or %APPDATA%\Subversion\servers file,
Use --config-option
command-line option to specify the same http-proxy-
options in single command-line you run. For example,
svn checkout ^
--config-option servers:global:http-proxy-host=<PROXY-HOST> ^
--config-option servers:global:http-proxy-port=<PORT> <REPO-URL> <LWC-DIR>
If you are on Windows, you can also write http-proxy-
options to Windows Registry. It's pretty handy if you need to apply proxy settings in Active Directory environment via Group Policy Objects.
It's simple. You can create your own ViewModel class for Login - LoginViewModel. You can create view var dialog = new UserView(); inside your LoginViewModel. And you can set-up Command LoginCommand into button.
<Button Name="btnLogin" IsDefault="True" Content="Login" Command="{Binding LoginCommand}" />
and
<Button Name="btnCancel" IsDefault="True" Content="Login" Command="{Binding CancelCommand}" />
ViewModel class:
public class LoginViewModel
{
Window dialog;
public bool ShowLogin()
{
dialog = new UserView();
dialog.DataContext = this; // set up ViewModel into View
if (dialog.ShowDialog() == true)
{
return true;
}
return false;
}
ICommand _loginCommand
public ICommand LoginCommand
{
get
{
if (_loginCommand == null)
_loginCommand = new RelayCommand(param => this.Login());
return _loginCommand;
}
}
public void CloseLoginView()
{
if (dialog != null)
dialog.Close();
}
public void Login()
{
if(CheckLogin()==true)
{
CloseLoginView();
}
else
{
// write error message
}
}
public bool CheckLogin()
{
// ... check login code
return true;
}
}
Prefix the variable name with env
:
$env:path
For example, if you want to print the value of environment value "MINISHIFT_USERNAME", then command will be:
$env:MINISHIFT_USERNAME
You can also enumerate all variables via the env
drive:
Get-ChildItem env:
user:Array[]=[1,2,3];
if(this.user.length)
{
console.log("user has contents");
}
else{
console.log("user is empty");
}
I will keep my accepted answer as the "simple and obvious way to do it" - however, that does not cover overlapping occurrences. Finding out those can be done naively, with multiple checking of the slices - as in: sum("GCAAAAAGH"[i:].startswith("AAA") for i in range(len("GCAAAAAGH")))
(which yields 3) - it can be done by trick use of regular expressions, as can be seen at Python regex find all overlapping matches? - and it can also make for fine code golfing - This is my "hand made" count for overlappingocurrences of patterns in a string which tries not to be extremely naive (at least it does not create new string objects at each interaction):
def find_matches_overlapping(text, pattern):
lpat = len(pattern) - 1
matches = []
text = array("u", text)
pattern = array("u", pattern)
indexes = {}
for i in range(len(text) - lpat):
if text[i] == pattern[0]:
indexes[i] = -1
for index, counter in list(indexes.items()):
counter += 1
if text[i] == pattern[counter]:
if counter == lpat:
matches.append(index)
del indexes[index]
else:
indexes[index] = counter
else:
del indexes[index]
return matches
def count_matches(text, pattern):
return len(find_matches_overlapping(text, pattern))
I wrote this lib to find once component boundary size change (resize) in Angular, may this help other people. You may put it on the root component, will do the same thing as window resize.
Step 1: Import the module
import { BoundSensorModule } from 'angular-bound-sensor';
@NgModule({
(...)
imports: [
BoundSensorModule,
],
})
export class AppModule { }
Step 2: Add the directive like below
<simple-component boundSensor></simple-component>
Step 3: Receive the boundary size details
import { HostListener } from '@angular/core';
@Component({
selector: 'simple-component'
(...)
})
class SimpleComponent {
@HostListener('resize', ['$event'])
onResize(event) {
console.log(event.detail);
}
}
forEach: If you want to perform an action on the elements of an Array and it is same as you use for loop. The result of this method does not give us an output buy just loop through the elements.
map: If you want to perform an action on the elements of an array and also you want to store the output of your action into an Array. This is similar to for loop within a function that returns the result after each iteration.
Hope this helps.
Just thought I'd chime in with some benchmarks for different scenarios to illustrate the previous answers:
And for each scenario, looking up values which appear:
Before each scenario I generated randomly sized lists of random strings, and then fed each list to a hashset. Each scenario ran 10,000 times, essentially:
(test pseudocode)
stopwatch.start
for X times
exists = list.Contains(lookup);
stopwatch.stop
stopwatch.start
for X times
exists = hashset.Contains(lookup);
stopwatch.stop
Tested on Windows 7, 12GB Ram, 64 bit, Xeon 2.8GHz
---------- Testing few small strings ------------
Sample items: (16 total)
vgnwaloqf diwfpxbv tdcdc grfch icsjwk
...
Benchmarks:
1: hashset: late -- 100.00 % -- [Elapsed: 0.0018398 sec]
2: hashset: middle -- 104.19 % -- [Elapsed: 0.0019169 sec]
3: hashset: end -- 108.21 % -- [Elapsed: 0.0019908 sec]
4: list: early -- 144.62 % -- [Elapsed: 0.0026607 sec]
5: hashset: start -- 174.32 % -- [Elapsed: 0.0032071 sec]
6: list: middle -- 187.72 % -- [Elapsed: 0.0034536 sec]
7: list: late -- 192.66 % -- [Elapsed: 0.0035446 sec]
8: list: end -- 215.42 % -- [Elapsed: 0.0039633 sec]
9: hashset: early -- 217.95 % -- [Elapsed: 0.0040098 sec]
10: list: start -- 576.55 % -- [Elapsed: 0.0106073 sec]
---------- Testing many small strings ------------
Sample items: (10346 total)
dmnowa yshtrxorj vthjk okrxegip vwpoltck
...
Benchmarks:
1: hashset: end -- 100.00 % -- [Elapsed: 0.0017443 sec]
2: hashset: late -- 102.91 % -- [Elapsed: 0.0017951 sec]
3: hashset: middle -- 106.23 % -- [Elapsed: 0.0018529 sec]
4: list: early -- 107.49 % -- [Elapsed: 0.0018749 sec]
5: list: start -- 126.23 % -- [Elapsed: 0.0022018 sec]
6: hashset: early -- 134.11 % -- [Elapsed: 0.0023393 sec]
7: hashset: start -- 372.09 % -- [Elapsed: 0.0064903 sec]
8: list: middle -- 48,593.79 % -- [Elapsed: 0.8476214 sec]
9: list: end -- 99,020.73 % -- [Elapsed: 1.7272186 sec]
10: list: late -- 99,089.36 % -- [Elapsed: 1.7284155 sec]
---------- Testing few long strings ------------
Sample items: (19 total)
hidfymjyjtffcjmlcaoivbylakmqgoiowbgxpyhnrreodxyleehkhsofjqenyrrtlphbcnvdrbqdvji...
...
Benchmarks:
1: list: early -- 100.00 % -- [Elapsed: 0.0018266 sec]
2: list: start -- 115.76 % -- [Elapsed: 0.0021144 sec]
3: list: middle -- 143.44 % -- [Elapsed: 0.0026201 sec]
4: list: late -- 190.05 % -- [Elapsed: 0.0034715 sec]
5: list: end -- 193.78 % -- [Elapsed: 0.0035395 sec]
6: hashset: early -- 215.00 % -- [Elapsed: 0.0039271 sec]
7: hashset: end -- 248.47 % -- [Elapsed: 0.0045386 sec]
8: hashset: start -- 298.04 % -- [Elapsed: 0.005444 sec]
9: hashset: middle -- 325.63 % -- [Elapsed: 0.005948 sec]
10: hashset: late -- 431.62 % -- [Elapsed: 0.0078839 sec]
---------- Testing many long strings ------------
Sample items: (5000 total)
yrpjccgxjbketcpmnvyqvghhlnjblhgimybdygumtijtrwaromwrajlsjhxoselbucqualmhbmwnvnpnm
...
Benchmarks:
1: list: early -- 100.00 % -- [Elapsed: 0.0016211 sec]
2: list: start -- 132.73 % -- [Elapsed: 0.0021517 sec]
3: hashset: start -- 231.26 % -- [Elapsed: 0.003749 sec]
4: hashset: end -- 368.74 % -- [Elapsed: 0.0059776 sec]
5: hashset: middle -- 385.50 % -- [Elapsed: 0.0062493 sec]
6: hashset: late -- 406.23 % -- [Elapsed: 0.0065854 sec]
7: hashset: early -- 421.34 % -- [Elapsed: 0.0068304 sec]
8: list: middle -- 18,619.12 % -- [Elapsed: 0.3018345 sec]
9: list: end -- 40,942.82 % -- [Elapsed: 0.663724 sec]
10: list: late -- 41,188.19 % -- [Elapsed: 0.6677017 sec]
---------- Testing few ints ------------
Sample items: (16 total)
7266092 60668895 159021363 216428460 28007724
...
Benchmarks:
1: hashset: early -- 100.00 % -- [Elapsed: 0.0016211 sec]
2: hashset: end -- 100.45 % -- [Elapsed: 0.0016284 sec]
3: list: early -- 101.83 % -- [Elapsed: 0.0016507 sec]
4: hashset: late -- 108.95 % -- [Elapsed: 0.0017662 sec]
5: hashset: middle -- 112.29 % -- [Elapsed: 0.0018204 sec]
6: hashset: start -- 120.33 % -- [Elapsed: 0.0019506 sec]
7: list: late -- 134.45 % -- [Elapsed: 0.0021795 sec]
8: list: start -- 136.43 % -- [Elapsed: 0.0022117 sec]
9: list: end -- 169.77 % -- [Elapsed: 0.0027522 sec]
10: list: middle -- 237.94 % -- [Elapsed: 0.0038573 sec]
---------- Testing many ints ------------
Sample items: (10357 total)
370826556 569127161 101235820 792075135 270823009
...
Benchmarks:
1: list: early -- 100.00 % -- [Elapsed: 0.0015132 sec]
2: hashset: end -- 101.79 % -- [Elapsed: 0.0015403 sec]
3: hashset: early -- 102.08 % -- [Elapsed: 0.0015446 sec]
4: hashset: middle -- 103.21 % -- [Elapsed: 0.0015618 sec]
5: hashset: late -- 104.26 % -- [Elapsed: 0.0015776 sec]
6: list: start -- 126.78 % -- [Elapsed: 0.0019184 sec]
7: hashset: start -- 130.91 % -- [Elapsed: 0.0019809 sec]
8: list: middle -- 16,497.89 % -- [Elapsed: 0.2496461 sec]
9: list: end -- 32,715.52 % -- [Elapsed: 0.4950512 sec]
10: list: late -- 33,698.87 % -- [Elapsed: 0.5099313 sec]
Yes just "selected disabled" in the option.
<select>
<option value="" selected disabled>Please select</option>
<option value="">A</option>
<option value="">B</option>
<option value="">C</option>
</select>
You can also view the answer at
I fixed such a problem by putting a div down the nav link
<div [ngClass]="{'nav-div': tab['active']}"></div>
and giving this css to it.
.nav-div {
width: inherit;
position: relative;
height: 8px;
background: white;
top: 4px
}
and nav link css as
.nav-link {
position: relative;
top: 8px;
&.active {
box-shadow: rgba(0, 0, 0, 0.3) 0 1px 4px -1px;
}
}
Hope this helps!
"put" has been deprecated, refrain from using it, use .of instead
ImmutableMap<String, String> myMap = ImmutableMap.of(
"city1", "Seattle",
"city2", "Delhi"
);
You will want to use the a ternary operator which acts as a shortened IF/Else statement:
echo '<option value="'.$value.'" '.(($value=='United States')?'selected="selected"':"").'>'.$value.'</option>';
To specify more than one namespace to provide prefixes, use something like:
@javax.xml.bind.annotation.XmlSchema(
namespace = "urn:oecd:ties:cbc:v1",
elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED,
xmlns ={@XmlNs(prefix="cbc", namespaceURI="urn:oecd:ties:cbc:v1"),
@XmlNs(prefix="iso", namespaceURI="urn:oecd:ties:isocbctypes:v1"),
@XmlNs(prefix="stf", namespaceURI="urn:oecd:ties:stf:v4")})
... in package-info.java
Well, there is a lot of taste in this one. I think people from a C background are more likely to prefer for(;;), which reads as "forever". If its for work, do what the locals do, if its for yourself, do the one that you can most easily read.
But in my experience, do { } while (1); is almost never used.
You need to delete your old db folder and recreate new one. It will resolve your issue.
Live example of Curl command to send OPTIONS requests: https://reqbin.com/req/c-d8nxa0fl
I commonly like to use a slight variant on the standard for loop. I often use this to run a command on a series of remote hosts. I take advantage of bash's brace expansion to create for loops that allow me to create non-numerical for-loops.
Example:
I want to run the uptime command on frontend hosts 1-5 and backend hosts 1-3:
% for host in {frontend{1..5},backend{1..3}}.mycompany.com
do ssh $host "echo -n $host; uptime"
done
I typically run this as a single-line command with semicolons on the ends of the lines instead of the more readable version above. The key usage consideration are that braces allow you to specify multiple values to be inserted into a string (e.g. pre{foo,bar}post results in prefoopost, prebarpost) and allow counting/sequences by using the double periods (you can use a..z etc.). However, the double period syntax is a new feature of bash 3.0; earlier versions will not support this.
[win] + Pause
;C:\python27\Scripts
to the end of Path
variableYou could implement a generic Pair
if you are sure that you just need to return two values:
public class Pair<U, V> {
/**
* The first element of this <code>Pair</code>
*/
private U first;
/**
* The second element of this <code>Pair</code>
*/
private V second;
/**
* Constructs a new <code>Pair</code> with the given values.
*
* @param first the first element
* @param second the second element
*/
public Pair(U first, V second) {
this.first = first;
this.second = second;
}
//getter for first and second
and then have the method return that Pair
:
public Pair<Object, Object> getSomePair();
Note: This answer predates the Unicode requirement; see the comments.
Just cast it:
CString s;
const TCHAR* x = (LPCTSTR) s;
It works because CString has a cast operator to do exactly this.
Using TCHAR makes your code Unicode-independent; if you're not concerned about Unicode you can simply use char
instead of TCHAR
.
var someParam = xxxxxxx;
commentbtn.click(function(){
alert(someParam );
});
You can combine attribute selectors this way:
$("[attr1=val][attr2=val]")...
so that an element has to satisfy both conditions. Of course you can use this for more than two. Also, don't do [type=checkbox]
. jQuery has a selector for that, namely :checkbox
so the end result is:
$("input:checkbox[name=ProductCode]")...
Attribute selectors are slow however so the recommended approach is to use ID and class selectors where possible. You could change your markup to:
<input type="checkbox" class="ProductCode" name="ProductCode"value="396P4">
<input type="checkbox" class="ProductCode" name="ProductCode"value="401P4">
<input type="checkbox" class="ProductCode" name="ProductCode"value="F460129">
allowing you to use the much faster selector of:
$("input.ProductCode")...
i think i'd try with MAX something like this:
SELECT staff_id, max( date ) from owner.table group by staff_id
then link in your other columns:
select staff_id, site_id, pay_level, latest
from owner.table,
( SELECT staff_id, max( date ) latest from owner.table group by staff_id ) m
where m.staff_id = staff_id
and m.latest = date
You are trying to access non static field directly from static method which is not legal in java. balance is a non static field, so either access it using object reference or make it static.
function outmeInside() {
var output = document.getElementById('preview_product_image');
if (this.height < 600 || this.width < 600) {
output.src = "http://localhost/danieladenew/uploads/no-photo.jpg";
alert("The image you have selected is low resloution image.Your image width=" + this.width + ",Heigh=" + this.height + ". Please select image greater or equal to 600x600,Thanks!");
} else {
output.src = URL.createObjectURL(event.target.files[0]);
}
return;
}
img.src = URL.createObjectURL(event.target.files[0]);
}
this work for multiple image preview and upload . if you have to select for each of the images one by one . Then copy and past into all the preview image function and validate!!!
My problem was that the TFS Build Controller was running as a network service and for some reason I didn't understand why the Visual Studio Build Host service certificates were not being used. I changed the identity of the Visual Studio Build service to something more manageable, made sure it had rights on the TFS server, and manually added the certificates using the MMC.
The problem was also that MSBuild can't add the password protected certificates to the store.
void addToSpecific()
{
int n;
int f=0; //flag
Node *temp=H; //H-Head, T-Tail
if(NULL!=H)
{
cout<<"Enter the Number"<<endl;
cin>>n;
while(NULL!=(temp->getNext()))
{
if(n==(temp->getInfo()))
{
f=1;
break;
}
temp=temp->getNext();
}
}
if(NULL==H)
{
Node *nn=new Node();
nn->setInfo();
nn->setNext(NULL);
T=H=nn;
}
else if(0==f)
{
Node *nn=new Node();
nn->setInfo();
nn->setNext(NULL);
T->setNext(nn);
T=nn;
}
else if(1==f)
{
Node *nn=new Node();
nn->setInfo();
nn->setNext(NULL);
nn->setNext((temp->getNext()));
temp->setNext(nn);
}
}
With Git, you can do practically anything offline, because everybody has their own repository.
Making branches and merging between branches is really easy.
Even if you don't have commit rights for a project, you can still have your own repository online, and publish "push requests" for your patches. Everybody who likes your patches can pull them into their project, including the official maintainers.
It's trivial to fork a project, modify it, and still keep merging in the bugfixes from the HEAD branch.
Git works for the Linux kernel developers. That means it is really fast (it has to be), and scales to thousands of contributors. Git also uses less space (up to 30 times less space for the Mozilla repository).
Git is very flexible, very TIMTOWTDI (There is more than one way to do it). You can use whatever workflow you want, and Git will support it.
Finally, there's GitHub, a great site for hosting your Git repositories.
Drawbacks of Git:
You can use fork()
and system()
so that your program doesn't have to wait until system()
returns.
#include <stdio.h>
#include <stdlib.h>
int main(int argc,char* argv[]){
int status;
// By calling fork(), a child process will be created as a exact duplicate of the calling process.
// Search for fork() (maybe "man fork" on Linux) for more information.
if(fork() == 0){
// Child process will return 0 from fork()
printf("I'm the child process.\n");
status = system("my_app");
exit(0);
}else{
// Parent process will return a non-zero value from fork()
printf("I'm the parent.\n");
}
printf("This is my main program and it will continue running and doing anything i want to...\n");
return 0;
}
This works for me. Got solution from MYSQL webpage
In MySQL run below queries:
FLUSH PRIVILEGES;
ALTER USER 'root'@'localhost' IDENTIFIED BY 'New_Password';
The solutions here are:
None
as your default value (or a nonce object
), and switch on that to create your values at runtime; orlambda
as your default parameter, and call it within a try block to get the default value (this is the sort of thing that lambda abstraction is for).The second option is nice because users of the function can pass in a callable, which may be already existing (such as a type
)
Yes, I try to follow it as closely as possible.
I don't follow any other coding standards.
Basically I solved it by NOT-ing the isReplyFormOpen
value whenever it is clicked:
<a ng-click="isReplyFormOpen = !isReplyFormOpen">Reply</a>
<div ng-init="isReplyFormOpen = false" ng-show="isReplyFormOpen" id="replyForm">
<!-- Form -->
</div>
Also, what helped me understand this particular scenario that you described is the Promise API documentation, specifically where it explains how the promised returned by the then
method will be resolved differently depending on what the handler fn returns:
if the handler function:
- returns a value, the promise returned by then gets resolved with the returned value as its value;
- throws an error, the promise returned by then gets rejected with the thrown error as its value;
- returns an already resolved promise, the promise returned by then gets resolved with that promise's value as its value;
- returns an already rejected promise, the promise returned by then gets rejected with that promise's value as its value.
- returns another pending promise object, the resolution/rejection of the promise returned by then will be subsequent to the resolution/rejection of the promise returned by the handler. Also, the value of the promise returned by then will be the same as the value of the promise returned by the handler.
In PowerShell 5 and PowerShell 5 ISE, it is also possible to use just Shift + Enter for multiline editing (instead of standard backticks `
at the end of each line):
PS> &"C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe" # Shift+Enter
>>> -verb:sync # Shift+Enter
>>> -source:contentPath="c:\workspace\xxx\master\Build\_PublishedWebsites\xxx.Web" # Shift+Enter
>>> -dest:contentPath="c:\websites\xxx\wwwroot,computerName=192.168.1.1,username=administrator,password=xxx"
For transitions you can use the following to detect the end of a transition via jQuery:
$("#someSelector").bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){ ... });
Mozilla has an excellent reference:
For animations it's very similar:
$("#someSelector").bind("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", function(){ ... });
Note that you can pass all of the browser prefixed event strings into the bind() method simultaneously to support the event firing on all browsers that support it.
Update:
Per the comment left by Duck: you use jQuery's .one()
method to ensure the handler only fires once. For example:
$("#someSelector").one("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){ ... });
$("#someSelector").one("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", function(){ ... });
Update 2:
jQuery bind()
method has been deprecated, and on()
method is preferred as of jQuery 1.7
. bind()
You can also use off()
method on the callback function to ensure it will be fired only once. Here is an example which is equivalent to using one()
method:
$("#someSelector")
.on("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd",
function(e){
// do something here
$(this).off(e);
});
References:
check your Connection String Properly. Check that the connection is open.
String CS=ConfigurationManager.COnnectionStrings["DBCS"].connectionString;
if(!IsPostBack)
{enter code here
SqlConnection con = new SqlConnection(CS);
con.Open();
SqlCommand cmd = new SqlCommand("select * from tblCountry", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
//Bind data
}
Look out for this pitfal: http://www.vertstudios.com/blog/avoiding-ajax-newline-pitfall/
Searched several houres before I found there were some linebreaks in the included files.
When I'm just testing a string to see if it is a GUID, I don't really want to create a Guid object that I don't need. So...
public static class GuidEx
{
public static bool IsGuid(string value)
{
Guid x;
return Guid.TryParse(value, out x);
}
}
And here's how you use it:
string testMe = "not a guid";
if (GuidEx.IsGuid(testMe))
{
...
}
td.setAttribute('rowspan',x);
What you actually have is an Activity (even if it looks like a Dialog), therefore you should call setFinishOnTouchOutside(false)
from your activity if you want to keep it open when the background activity is clicked.
EDIT: This only works with android API level 11 or greater
please import requestoptions from angular cors
import {RequestOptions, Request, Headers } from '@angular/http';
and add request options in your code like given below
let requestOptions = new RequestOptions({ headers:null, withCredentials:
true });
send request option in your api request
code snippet below-
let requestOptions = new RequestOptions({ headers:null,
withCredentials: true });
return this.http.get(this.config.baseUrl +
this.config.getDropDownListForProject, requestOptions)
.map(res =>
{
if(res != null)
{
return res.json();
//return true;
}
})
.catch(this.handleError);
}
and add CORS in your backend PHP code where all api request will land first.
try this and let me know if it is working or not i had a same issue i was adding CORS from angular5 that was not working then i added CORS to backend and it worked for me
This is version that works for me when using a console app without a web page:
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: true);
IConfigurationRoot configuration = builder.Build();
AppSettings appSettings = new AppSettings();
configuration.GetSection("AppSettings").Bind(appSettings);
You can write a function to return array of occurrence positions, Java has String.regionMatches function which is quite handy
public static ArrayList<Integer> occurrencesPos(String str, String substr) {
final boolean ignoreCase = true;
int substrLength = substr.length();
int strLength = str.length();
ArrayList<Integer> occurrenceArr = new ArrayList<Integer>();
for(int i = 0; i < strLength - substrLength + 1; i++) {
if(str.regionMatches(ignoreCase, i, substr, 0, substrLength)) {
occurrenceArr.add(i);
}
}
return occurrenceArr;
}
You need to create an object since printInformation()
is non-static. Try:
int main() {
MyClass o;
o.printInformation();
fgetc( stdin );
return(0);
}
According to the manual, in CPython id()
is the actual memory address of the variable. If you want it in hex format, call hex()
on it.
x = 5
print hex(id(x))
this will print the memory address of x.
If A1 has the week number and year as a 3 or 4 digit integer in the format wwYY then the formula would be:
=INT(A1/100)*7+DATE(MOD([A1,100),1,1)-WEEKDAY(DATE(MOD(A1,100),1,1))-5
the subtraction of the weekday ensures you return a consistent start day of the week. Use the final subtraction to adjust the start day.
I use both Charles Proxy and Fiddler for my HTTP/HTTPS level debugging.
Pros of Charles Proxy:
Cons of Charles Proxy:
.a
files are static libraries typically generated by the archive tool. You usually include the header files associated with that static library and then link to the library when you are compiling.
Below solution worked for me: Navigate to Project->Clean.. Clean all the projects referenced by Tomcat server Refresh the project you're trying to run on Tomcat
Try to run the server afterwards
To anyone who had been wonderstruck about some files being easily uploaded and some not, it could be a size issue. I'm sharing this as I was stuck with my PHP code not uploading large files and I kept assuming it wasn't uploading any Excel files. So, if you are using PHP and you want to increase the file upload limit, go to the php.ini file and make the following modifications:
upload_max_filesize = 2M
to be changed to
upload_max_filesize = 10M
post_max_size = 10M
or the size required. Then restart the Apache server and the upload will start magically working. Hope this will be of help to someone.
Ansible uses the become
, become_user
, and become_method
directives to achieve privilege escalation. You can apply them to an entire play or playbook, set them in an included playbook, or set them for a particular task.
- name: checkout repo
git: repo=https://github.com/some/repo.git version=master dest={{ dst }}
become: yes
become_user: some_user
You can use become_with
to specify how the privilege escalation is achieved, the default being sudo
.
The directive is in effect for the scope of the block in which it is used (examples).
See Hosts and Users for some additional examples and Become (Privilege Escalation) for more detailed documentation.
In addition to the task-scoped become
and become_user
directives, Ansible 1.9 added some new variables and command line options to set these values for the duration of a play in the absence of explicit directives:
become
/become_user
directives.As of Ansible 2.0.2.0, the older sudo
/sudo_user
syntax described below still works, but the deprecation notice states, "This feature will be removed in a future release."
- name: checkout repo
git: repo=https://github.com/some/repo.git version=master dest={{ dst }}
sudo: yes
sudo_user: some_user
void removeDuplicates(std::vector<int>& arr) {
for (int i = 0; i < arr.size(); i++)
{
for (int j = i + 1; j < arr.size(); j++)
{
if (arr[i] > arr[j])
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
std::vector<int> y;
int x = arr[0];
int i = 0;
while (i < arr.size())
{
if (x != arr[i])
{
y.push_back(x);
x = arr[i];
}
i++;
if (i == arr.size())
y.push_back(arr[i - 1]);
}
arr = y;
}
Since PHP 5.5, you can use array_column
:
$ids = array_column($users, 'id');
This is the preferred option on any modern project. However, if you must support PHP<5.5, the following alternatives exist:
Since PHP 5.3, you can use array_map
with an anonymous function, like this:
$ids = array_map(function ($ar) {return $ar['id'];}, $users);
Before (Technically PHP 4.0.6+), you must create an anonymous function with create_function
instead:
$ids = array_map(create_function('$ar', 'return $ar["id"];'), $users);
In html;
<input type="file" accept="image/*">
This will accept all image formats but no other file like pdf or video.
But if you are using django, in django forms.py;
image_field = forms.ImageField(Here_are_the_parameters)
Try this (copied-ish from Erik Garrison: https://stackoverflow.com/a/3071528/575530)
#include <sys/stat.h>
bool FileExists(char* filename)
{
struct stat fileInfo;
return stat(filename, &fileInfo) == 0;
}
stat
returns 0
if the file exists and -1
if not.
simply don't close in
remove in.close()
from your code.
You can use Invoke-RDUserLogoff
An example logging off Active Directory users of a specific Organizational Unit:
$users = Get-ADUser -filter * -SearchBase "ou=YOUR_OU_NAME,dc=contoso,dc=com"
Get-RDUserSession | where { $users.sAMAccountName -contains $_.UserName } | % { $_ | Invoke-RDUserLogoff -Force }
At the end of the pipe, if you try to use only foreach (%), it will log off only one user. But using this combination of foreach and pipe:
| % { $_ | command }
will work as expected.
Ps. Run as Adm.
You need import { NgForm } from @angular/forms in your page.ts;
Code HTML:
<form #values="ngForm" (ngSubmit)="function(values)">
...
<ion-input type="text" name="name" ngModel></ion-input>
<ion-input type="text" name="mail" ngModel></ion-input>
...
</form>
In your Page.ts, implement your funcion to manipulate form data:
function(data) {console.log("Name: "data.value.name + " Mail: " + data.value.mail);}
This is suitable for application from root environment.
<object type="application/x-shockwave-flash" data="/dir/application.swf"
id="applicationID" style="margin:0 10px;width:auto;height:auto;">
<param name="movie" value="/dir/application.swf" />
<param name="wmode" value="transparent" /> <!-- Or opaque, etc. -->
<!-- ? Required paramter or not, depends on application -->
<param name="FlashVars" value="" />
<param name="quality" value="high" />
<param name="menu" value="false" />
</object>
Additional parameters should be/can be added which depends on .swf it self. No embed, just object and parameters within, so, it remains valid, working and usable everywhere, it doesn't matter which !DOCTYPE is all about. :)
This is a handy function for getting filenames, with the specified format (usually .mat
) in a root folder!
function filenames = getFilenames(rootDir, format)
% Get filenames with specified `format` in given `foler`
%
% Parameters
% ----------
% - rootDir: char vector
% Target folder
% - format: char vector = 'mat'
% File foramt
% default values
if ~exist('format', 'var')
format = 'mat';
end
format = ['*.', format];
filenames = dir(fullfile(rootDir, format));
filenames = arrayfun(...
@(x) fullfile(x.folder, x.name), ...
filenames, ...
'UniformOutput', false ...
);
end
In your case, you can use the following snippet :)
filenames = getFilenames('D:/dic/**');
for i = 1:numel(filenames)
filename = filenames{i};
% do your job!
end
You can try with this:
function doParseCSVFile($filesArray)
{
if ((file_exists($filesArray['frmUpload']['name'])) && (is_readable($filesArray['frmUpload']['name']))) {
$strFilePath = $filesArray['frmUpload']['tmp_name'];
$strFileHandle = fopen($strFilePath,"r");
$line_of_text = fgetcsv($strFileHandle,1024,",","'");
$line_of_text = fgetcsv($strFileHandle,1024,",","'");
do {
if ($line_of_text[0]) {
$strInsertSql = "INSERT INTO tbl_employee(employee_name, employee_code, employee_email, employee_designation, employee_number)VALUES('".addslashes($line_of_text[0])."', '".$line_of_text[1]."', '".addslashes($line_of_text[2])."', '".$line_of_text[3]."', '".$line_of_text[4]."')";
ExecuteQry($strInsertSql);
}
} while (($line_of_text = fgetcsv($strFileHandle,1024,",","'"))!== FALSE);
} else {
return FALSE;
}
}
From the Developer Guide:
android:id="@+id/my_button"
The at-symbol (@
) at the beginning of the string indicates that the XML parser should parse and expand the rest of the ID string and identify it as an ID resource. The plus-symbol (+
) means that this is a new resource name that must be created and added to our resources (in the R.java
file). There are a number of other ID resources that are offered by the Android framework. When referencing an Android resource ID, you do not need the plus-symbol, but must add the android
package namespace, like so:
android:id="@android:id/empty"
ggplot2 is another graphics package that handles things like the range issue Gavin mentions in a pretty slick way. It also handles auto generating appropriate legends and just generally has a more polished feel in my opinion out of the box with less manual manipulation.
library(ggplot2)
#Sample data
dat <- data.frame(dens = c(rnorm(100), rnorm(100, 10, 5))
, lines = rep(c("a", "b"), each = 100))
#Plot.
ggplot(dat, aes(x = dens, fill = lines)) + geom_density(alpha = 0.5)
That is really important for example when you are writing a network analyzer. packet headers are defined by the protocol specification, not by the way a particular platform's C compiler works.
Would not that have to be:
.replaceAll("\"","\\\\\"")
FIVE backslashes in the replacement String.
Yes, in your formula
, you can cbind
the numeric variables to be aggregated:
aggregate(cbind(x1, x2) ~ year + month, data = df1, sum, na.rm = TRUE)
year month x1 x2
1 2000 1 7.862002 -7.469298
2 2001 1 276.758209 474.384252
3 2000 2 13.122369 -128.122613
...
23 2000 12 63.436507 449.794454
24 2001 12 999.472226 922.726589
See ?aggregate
, the formula
argument and the examples.
How about
sudo yum install php-mysql
or
sudo apt-get install php5-mysql
For a field named isCurrent
, the correct getter / setter naming is setCurrent()
/ isCurrent()
(at least that's what Eclipse thinks), which is highly confusing and can be traced back to the main problem:
Your field should not be called isCurrent
in the first place. Is is a verb and verbs are inappropriate to represent an Object's state. Use an adjective instead, and suddenly your getter / setter names will make more sense:
private boolean current;
public boolean isCurrent(){
return current;
}
public void setCurrent(final boolean current){
this.current = current;
}
Here you can see what (mobile) browsers support css position fixed + there version.
Using useState with useEffect as described above is absolutely correct way. But if getSearchResults function returns subscription then useEffect should return a function which will be responsible for unsubscribing the subscription . Returned function from useEffect will run before each change to dependency(name in above case) and on component destroy
Well, if you really want to return a mapping from _id
to user
, you could always do:
server.get('/usersList', function(req, res) {
User.find({}, function(err, users) {
var userMap = {};
users.forEach(function(user) {
userMap[user._id] = user;
});
res.send(userMap);
});
});
find()
returns all matching documents in an array, so your last code snipped sends that array to the client.
log.retention.hours
is a property of a broker which is used as a default value when a topic is created. When you change configurations of currently running topic using kafka-topics.sh
, you should specify a topic-level property.
A topic-level property for log retention time is retention.ms
.
From Topic-level configuration in Kafka 0.8.1 documentation:
So the correct command depends on the version. Up to 0.8.2 (although docs still show its use up to 0.10.1) use kafka-topics.sh --alter
and after 0.10.2 (or perhaps from 0.9.0 going forward) use kafka-configs.sh --alter
$ bin/kafka-topics.sh --zookeeper zk.yoursite.com --alter --topic as-access --config retention.ms=86400000
You can check whether the configuration is properly applied with the following command.
$ bin/kafka-topics.sh --describe --zookeeper zk.yoursite.com --topic as-access
Then you will see something like below.
Topic:as-access PartitionCount:3 ReplicationFactor:3 Configs:retention.ms=86400000
Assuming that "a" and "b" are bean properties
rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"
You may look at JSF EL operators
The recommended way is to use filetype based indentation and only use smartindent and cindent if that doesn't suffice.
Add the following to your .vimrc
set expandtab
set shiftwidth=2
set softtabstop=2
filetype plugin indent on
Hope it helps as being a different answer.
At times, if we forget the
return self.cleaned_data
in the clean function of django forms, we will not have any data though the form.is_valid()
will return True
.
Try this:
public static List<ProductActivity> getCatalog(Resources res){
if(catalog == null) {
catalog.add(new Product("Dead or Alive", res
.getDrawable(R.drawable.product_salmon),
"Dead or Alive by Tom Clancy with Grant Blackwood", 29.99));
catalog.add(new Product("Switch", res
.getDrawable(R.drawable.switchbook),
"Switch by Chip Heath and Dan Heath", 24.99));
catalog.add(new Product("Watchmen", res
.getDrawable(R.drawable.watchmen),
"Watchmen by Alan Moore and Dave Gibbons", 14.99));
}
}
It look's like some permissions problem.
Try to set all permisions like you did in mysite1 to the others site.
By default file permissions should be 644 and dirs 755. Also check if the user that runs nginx have permission to read that files and dirs.
As I said in a comment to aqingsao's answer, it doesn't quite work when the textarea
has newline characters, at least on Windows.
I've change his answer slightly thus:
$(function() {
$("textarea[maxlength]").bind('input propertychange', function() {
var maxLength = $(this).attr('maxlength');
//I'm guessing JavaScript is treating a newline as one character rather than two so when I try to insert a "max length" string into the database I get an error.
//Detect how many newlines are in the textarea, then be sure to count them twice as part of the length of the input.
var newlines = ($(this).val().match(/\n/g) || []).length
if ($(this).val().length + newlines > maxLength) {
$(this).val($(this).val().substring(0, maxLength - newlines));
}
})
});
Now when I try to paste a lot of data in with newlines, I get exactly the right number of characters.
Oftentimes hooking refers to Win32 message hooking or the Linux/OSX equivalents, but more generically hooking is simply notifying another object/window/program/etc that you want to be notified when a specified action happens. For instance: Having all windows on the system notify you as they are about to close.
As a general rule, hooking is somewhat hazardous since doing it without understanding how it affects the system can lead to instability or at the very leas unexpected behaviour. It can also be VERY useful in certain circumstances, thought. For instance: FRAPS uses it to determine which windows it should show it's FPS counter on.
Using the client instead of resource:
s3 = boto3.client('s3')
bucket='bucket_name'
result = s3.list_objects(Bucket = bucket, Prefix='/something/')
for o in result.get('Contents'):
data = s3.get_object(Bucket=bucket, Key=o.get('Key'))
contents = data['Body'].read()
print(contents)
you are not creating an arraylist for integers, but you are trying to create an arraylist for arrays of integers.
so if you want your code to work just put.
List<Integer> list = new ArrayList<>();
int x = 5;
list.add(x);
Adding this in case it helps someone.
As I am working with Japanese characters, encoding has also been set appropriately. However, from time to time, I find that htmlentities
and htmlspecialchars
are not sufficient.
Some user inputs contain special characters that are not stripped by the above functions. In those cases I have to do this:
preg_replace('/[\x00-\x1f]/','',htmlspecialchars($string))
This will also remove certain xml-unsafe
control characters like Null character
or EOT
. You can use this table to determine which characters you wish to omit.
I think if I understand correctly this is what you are doing.
ImageView view = (ImageView) findViewById(R.id.someImage);
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
ImageView imageView = (ImageView) view;
assert(R.id.someImage == imageView.getId());
switch(getDrawableId(imageView)) {
case R.drawable.foo:
imageView.setDrawableResource(R.drawable.bar);
break;
case R.drawable.bar:
default:
imageView.setDrawableResource(R.drawable.foo);
break;
}
});
Right? So that function getDrawableId()
doesn't exist. You can't get a the id that a drawable was instantiated from because the id is just a reference to the location of data on the device on how to construct a drawable. Once the drawable is constructed it doesn't have a way to get back the resourceId that was used to create it. But you could make it work something like this using tags
ImageView view = (ImageView) findViewById(R.id.someImage);
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
ImageView imageView = (ImageView) view;
assert(R.id.someImage == imageView.getId());
// See here
Integer integer = (Integer) imageView.getTag();
integer = integer == null ? 0 : integer;
switch(integer) {
case R.drawable.foo:
imageView.setDrawableResource(R.drawable.bar);
imageView.setTag(R.drawable.bar);
break;
case R.drawable.bar:
default:
imageView.setDrawableResource(R.drawable.foo);
imageView.setTag(R.drawable.foo);
break;
}
});
You don't have to use jQuery or Javascript.
Use the name
tag of the select and let the form do it's job.
<select name="agent_id" id="agent_id">
Because this is HTML is not valid does not have any affect on the outcome ... it just means that the HTML does adhere to the standard (merely for organizational purposes). For the sake of being valid it could have been written this way:
<html>
<head>
<style type="text/css">
p.first {color:blue}
p.second {color:green}
</style>
</head>
<body>
<p class="first" style="color:green;">Hello World</p>
<p class="second" style="color:blue;">Hello World</p>
My guess is that the browser applies the last style it comes across.
Don't reinvent the wheel. Use json-framework or something similar.
If you do decide to use json-framework, here's how you would parse a JSON string into an NSDictionary
:
SBJsonParser* parser = [[[SBJsonParser alloc] init] autorelease];
// assuming jsonString is your JSON string...
NSDictionary* myDict = [parser objectWithString:jsonString];
// now you can grab data out of the dictionary using objectForKey or another dictionary method
To link to a UNC path from an HTML document, use file:///// (yes, that's five slashes).
file://///server/path/to/file.txt
Note that this is most useful in IE and Outlook/Word. It won't work in Chrome or Firefox, intentionally - the link will fail silently. Some words from the Mozilla team:
For security purposes, Mozilla applications block links to local files (and directories) from remote files.
And less directly, from Google:
Firefox and Chrome doesn't open "file://" links from pages that originated from outside the local machine. This is a design decision made by those browsers to improve security.
The Mozilla article includes a set of client settings you can use to override this behavior in Firefox, and there are extensions for both browsers to override this restriction.
Well I don't convert bytes to hex often so I have to say I don't know if there is a better way then this, but here is a way to do it.
StringBuilder sb = new StringBuilder();
foreach (byte b in myByteArray)
sb.Append(b.ToString("X2"));
string hexString = sb.ToString();
Like sgibb said it was an if problem, it had nothing to do with | or ||.
Here is another way to solve your problem:
for (i in 1:nrow(trip)) {
if(trip$Ref.y[i]=='G' & trip$Variant.y[i]=='T'|trip$Ref.y[i]=='C' & trip$Variant.y[i]=='A') {
trip[i, 'mutType'] <- "G:C to T:A"
}
else if(trip$Ref.y[i]=='G' & trip$Variant.y[i]=='C'|trip$Ref.y[i]=='C' & trip$Variant.y[i]=='G') {
trip[i, 'mutType'] <- "G:C to C:G"
}
else if(trip$Ref.y[i]=='G' & trip$Variant.y[i]=='A'|trip$Ref.y[i]=='C' & trip$Variant.y[i]=='T') {
trip[i, 'mutType'] <- "G:C to A:T"
}
else if(trip$Ref.y[i]=='A' & trip$Variant.y[i]=='T'|trip$Ref.y[i]=='T' & trip$Variant.y[i]=='A') {
trip[i, 'mutType'] <- "A:T to T:A"
}
else if(trip$Ref.y[i]=='A' & trip$Variant.y[i]=='G'|trip$Ref.y[i]=='T' & trip$Variant.y[i]=='C') {
trip[i, 'mutType'] <- "A:T to G:C"
}
else if(trip$Ref.y[i]=='A' & trip$Variant.y[i]=='C'|trip$Ref.y[i]=='T' & trip$Variant.y[i]=='G') {
trip[i, 'mutType'] <- "A:T to C:G"
}
}
Simple short answer is this:
xcopy /Y /I "$(SolutionDir)<my-src-path>" "$(SolutionDir)<my-dst-path>\"
It is best to use native dictionaries and arrays because they have been optimized for use with swift. That being said you can use NS... classes in swift and I think this situation warrants that. Here is how you would implement it:
var path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist")
var dict = NSDictionary(contentsOfFile: path)
So far (in my opinion) this is the easiest and most efficient way to access a plist, but in the future I expect that apple will add more functionality (such as using plist) into native dictionaries.
@helloswift123 I like your function. Here is a modification to rename multiple keys in a single call:
def rename(d, keymap):
"""
:param d: old dict
:type d: dict
:param keymap: [{:keys from-keys :values to-keys} keymap]
:returns: new dict
:rtype: dict
"""
new_dict = {}
for key, value in zip(d.keys(), d.values()):
new_key = keymap.get(key, key)
new_dict[new_key] = d[key]
return new_dict
echo '<a href="' . $folder_path . '">Link text</a>';
Please note that you must use the path relative to your domain and, if the folder path is outside the public htdocs directory, it will not work.
EDIT: maybe i misreaded the question; you have a file on your pc and want to insert the path on the html page, and then send it to the server?
Try this,
this.searchAll = element(by.xpath('path here'));
this.searchAll.sendKeys('');
The only difference I see is that getJSON performs a GET request instead of a POST.
This occurs when declared (non-pure) virtual functions are missing bodies. In your class definition, something like:
virtual void foo();
Should be defined (inline or in a linked source file):
virtual void foo() {}
Or declared pure virtual:
virtual void foo() = 0;
If you are using jQuery there is a perfect function for you: .scrollTop()
doc here -> http://api.jquery.com/scrollTop/
note: you can use this function to retrieve OR set the position.
see also: http://api.jquery.com/?s=scroll
If you have a rogue loop, pause the code in Google Chrome debugger (the small "||
" button while in Sources tab).
Switch back to Chrome itself, open "Task Manager" (Shift+ESC), select your tab, click the "End Process" button.
You will get the Aww Snap message and then you can reload (F5).
As others have noted, reloading the page at the point of pausing is the same as restarting the rogue loop and can cause nasty lockups if the debugger also then locks (in some cases leading to restarting chrome or even the PC). The debugger needs a "Stop" button. Nb: The accepted answer is out of date in that some aspects of it are now apparently wrong. If you vote me down, pls explain :).
I struggled quite a bit with this, only to find the answer within the Fancybox documentation.
As hinted above, first I thought it would have been as easy as this to disable scrolling:
$('.fancybox').fancybox({'type': 'iframe', 'scrolling': 'no', 'width': 500})
Just setting the 'scrolling' option to 'no' was not enough, though. I had to repeat the same thing in the 'iframe' option, like this:
$('.fancybox').fancybox({
'type': 'iframe',
'scrolling': 'no',
'width': 500,
'iframe': {'scrolling': 'no'}
})
$(document).ready(function() {
$('ul.art-vmenu li').live("click", function() {
alert($(this).text());
});
});
jsfiddle: http://jsfiddle.net/ZpYSC/
jquery documentation on live(): http://api.jquery.com/live/
Description: Attach a handler to the event for all elements which match the current selector, now and in the future.
You can manipulate :disabled
attribute in vue.js.
It will accept a boolean, if it's true, then the input gets disabled, otherwise it will be enabled...
Something like structured like below in your case for example:
<input type="text" id="name" class="form-control" name="name" v-model="form.name" :disabled="validated ? false : true">
Also read this below:
Conditionally Disabling Input Elements via JavaScript Expression
You can conditionally disable input elements inline with a JavaScript expression. This compact approach provides a quick way to apply simple conditional logic. For example, if you only needed to check the length of the password, you may consider doing something like this.
<h3>Change Your Password</h3>
<div class="form-group">
<label for="newPassword">Please choose a new password</label>
<input type="password" class="form-control" id="newPassword" placeholder="Password" v-model="newPassword">
</div>
<div class="form-group">
<label for="confirmPassword">Please confirm your new password</label>
<input type="password" class="form-control" id="confirmPassword" placeholder="Password" v-model="confirmPassword" v-bind:disabled="newPassword.length === 0 ? true : false">
</div>
It appears the default setting for Adobe Reader X is for the toolbars not to be shown by default unless they are explicitly turned on by the user. And even when I turn them back on during a session, they don't show up automatically next time. As such, I suspect you have a preference set contrary to the default.
The state you desire, with the top and left toolbars not shown, is called "Read Mode". If you right-click on the document itself, and then click "Page Display Preferences" in the context menu that is shown, you'll be presented with the Adobe Reader Preferences dialog. (This is the same dialog you can access by opening the Adobe Reader application, and selecting "Preferences" from the "Edit" menu.) In the list shown in the left-hand column of the Preferences dialog, select "Internet". Finally, on the right, ensure that you have the "Display in Read Mode by default" box checked:
You can also turn off the toolbars temporarily by clicking the button at the right of the top toolbar that depicts arrows pointing to opposing corners:
Finally, if you have "Display in Read Mode by default" turned off, but want to instruct the page you're loading not to display the toolbars (i.e., override the user's current preferences), you can append the following to the URL:
#toolbar=0&navpanes=0
So, for example, the following code will disable both the top toolbar (called "toolbar") and the left-hand toolbar (called "navpane"). However, if the user knows the keyboard combination (F8, and perhaps other methods as well), they will still be able to turn them back on.
string url = @"http://www.domain.com/file.pdf#toolbar=0&navpanes=0";
this._WebBrowser.Navigate(url);
You can read more about the parameters that are available for customizing the way PDF files open here on Adobe's developer website.
I've tried most of the top options but it seems that I had something wrong with my environment setup so they didn't help. What solved the issue for me was to re-install jdk1.8.0_201
and jre1.8.0_201
and this solved the error for me. Hope that helps someone.
I have only tested with EditText but you can use the method
public void setBackgroundResource (int resid)
to apply a style defined in an XML file.
Sine this method belongs to View I believe it will work with any UI element.
regards.
Edit: Coming back to this answer after a year of security research, I realize it makes the rather unfortunate implication that you would ever actually compare plaintext passwords. Please don't. Use a secure one-way hash with a salt and a reasonable number of iterations. Consider using a library: this stuff is hard to get right!
Original answer: What about the fact that String.equals() uses short-circuit evaluation, and is therefore vulnerable to a timing attack? It may be unlikely, but you could theoretically time the password comparison in order to determine the correct sequence of characters.
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
// Quits here if Strings are different lengths.
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
// Quits here at first different character.
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
Some more resources on timing attacks:
One advantage not yet mentioned of a TreeSet
is that its has greater "locality", which is shorthand for saying (1) if two entries are nearby in the order, a TreeSet
places them near each other in the data structure, and hence in memory; and (2) this placement takes advantage of the principle of locality, which says that similar data is often accessed by an application with similar frequency.
This is in contrast to a HashSet
, which spreads the entries all over memory, no matter what their keys are.
When the latency cost of reading from a hard drive is thousands of times the cost of reading from cache or RAM, and when the data really is accessed with locality, the TreeSet
can be a much better choice.
The way to do this is by adding tabindex="-1"
. By adding this to a specific element, it becomes unreachable by the keyboard navigation. There is a great article here that will help you further understand tabindex.
If you don't need the unique identifier for further styling of the divs and are using HTML5 you could try and go with custom Data Attributes. Read on here or try a google search for HTML5 Custom Data Attributes
GET CURRENT UTC TIME IN REQUIRED FORMAT
// Current UTC time
OffsetDateTime utc = OffsetDateTime.now(ZoneOffset.UTC);
// GET LocalDateTime
LocalDateTime localDateTime = utc.toLocalDateTime();
System.out.println("*************" + localDateTime);
// formated UTC time
DateTimeFormatter dTF = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
System.out.println(" formats as " + dTF.format(localDateTime));
//GET UTC time for current date
Date now= new Date();
LocalDateTime utcDateTimeForCurrentDateTime = Instant.ofEpochMilli(now.getTime()).atZone(ZoneId.of("UTC")).toLocalDateTime();
DateTimeFormatter dTF2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
System.out.println(" formats as " + dTF2.format(utcDateTimeForCurrentDateTime));
You should do it this way ideally
t = TemperatureData.objects.get(id=1)
t.value = 999
t.save(['value'])
This allow you to specify which column should be saved and rest are left as they currently are in database. (https://code.djangoproject.com/ticket/4102)!
int function(){
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer between 1-100: ");
int range;
while(true){
if(input.hasNextInt()){
range = input.nextInt();
if(0<=range && range <= 100)
break;
else
continue;
}
input.nextLine(); //Comsume the garbage value
System.out.println("Enter an integer between 1-100:");
}
return range;
}
As others have mentioned the dollar sign is intended to be used by mechanically generated code. However, that convention has been broken by some wildly popular JavaScript libraries. JQuery, Prototype and MS AJAX (AKA Atlas) all use this character in their identifiers (or as an entire identifier).
In short you can use the $
whenever you want. (The interpreter won't complain.) The question is when do you want to use it?
I personally do not use it, but I think its use is valid. I think MS AJAX uses it to signify that a function is an alias for some more verbose call.
For example:
var $get = function(id) { return document.getElementById(id); }
That seems like a reasonable convention.
concat
also works nicely with a list comprehension pulled using the "loc" command against an existing dataframe
df = pd.read_csv('./data.csv') # ie; Dataframe pulled from csv file with a "userID" column
review_ids = ['1','2','3'] # ie; ID values to grab from DataFrame
# Gets rows in df where IDs match in the userID column and combines them
dfa = pd.concat([df.loc[df['userID'] == x] for x in review_ids])
I'm not sure what you are doing wrong here, when I build a form using form classes Symfony takes care of selecting the correct option in the list. Here's an example of one of my forms that works.
In the controller for the edit action:
$entity = $em->getRepository('FooBarBundle:CampaignEntity')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find CampaignEntity entity.');
}
$editForm = $this->createForm(new CampaignEntityType(), $entity);
$deleteForm = $this->createDeleteForm($id);
return $this->render('FooBarBundle:CampaignEntity:edit.html.twig', array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
The campaign entity type class (src: Foo\BarBundle\Form\CampaignEntityType.php):
namespace Foo\BarBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Doctrine\ORM\EntityRepository;
class CampaignEntityType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('store', 'entity', array('class'=>'FooBarBundle:Store', 'property'=>'name', 'em'=>'my_non_default_em','required' => true, 'query_builder' => function(EntityRepository $er) {return $er->createQueryBuilder('s')->orderBy('s.name', 'ASC');}))
->add('reward');
}
public function getName()
{
return 'foo_barbundle_campaignentitytype';
}
}
For benefit of those who reach here googling for python ssh sample. The original question and answer are almost a decode old now. It seems that the paramiko has gain a bit of functionalities (Ok. I'll admit - pure guessing here - I'm new to Python) and you can create ssh client directly with paramiko.
import base64
import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('192.168.1.1', username='user', password='password')
stdin, stdout, stderr = client.exec_command('cat /proc/meminfo')
for line in stdout:
print('... ' + line.strip('\n'))
client.close()
This code was adapted from demo of https://github.com/paramiko/paramiko It works for me.
I assume that what you want is a tooltip. The easiest way to do this is to append an svg:title
element to each circle, as the browser will take care of showing the tooltip and you don't need the mousehandler. The code would be something like
vis.selectAll("circle")
.data(datafiltered).enter().append("svg:circle")
...
.append("svg:title")
.text(function(d) { return d.x; });
If you want fancier tooltips, you could use tipsy for example. See here for an example.
Looks like you created a separate question. I was answering your other question How to change flat file source using foreach loop container in an SSIS package? with the same answer. Anyway, here it is again.
Create two string data type variables namely DirPath
and FilePath
. Set the value C:\backup\ to the variable DirPath
. Do not set any value to the variable FilePath
.
Select the variable FilePath
and select F4 to view the properties. Set the EvaluateAsExpression
property to True and set the Expression property as @[User::DirPath] + "Source" + (DT_STR, 4, 1252) DATEPART("yy" , GETDATE()) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2)
Copy the downloaded DLL file in a custom folder on your dev drive, then add the reference to your project using the Browse button in the Add Reference
dialog.
Be sure that the new reference has the Copy Local = True
.
The Add Reference
dialog could be opened right-clicking on the References item in your project in Solution Explorer
UPDATE AFTER SOME YEARS
At the present time the best way to resolve all those problems is through the
Manage NuGet packages menu command of Visual Studio 2017/2019.
You can right click on the References node of your project and select that command. From the Browse tab search for the library you want to use in the NuGet repository, click on the item if found and then Install it. (Of course you need to have a package for that DLL and this is not guaranteed to exist)
Java command line parameters
-Xms: initial heap size
-Xmx: Maximum heap size
if you are using Tomcat. Update CATALINA_OPTS
environment variable
export CATALINA_OPTS=-Xms16m -Xmx256m;
public boolean isAlertPresent()
{
try
{
driver.switchTo().alert();
return true;
} // try
catch (NoAlertPresentException Ex)
{
return false;
} // catch
} // isAlertPresent()
check the link here https://groups.google.com/forum/?fromgroups#!topic/webdriver/1GaSXFK76zY
The question isn't clear - is this for an alert on page load? You shouldn't see any alert dialogues when using Selenium, as it replaces alert()
with its own version which just captures the message given for verification.
Selenium doesn't support alert()
on page load, as it needs to patch the function in the window under test with its own version.
If you can't get rid of onload alerts from the application under test, you should look into using GUI automation to click the popups which are generated, e.g. AutoIT if you're on Windows.
You should be able to use the .RemoveNode method of the node or the .RemoveChild method of the parent node.
Few steps that helped me (some of them are mentioned above):
Open project structure by:
command + ; (mac users)
OR
right click on the project ->
Open Module Settings
->
+ ->
Python ->
<your-project> ->
OK->
Python ->
<select python interpreter>->
Project SDK ->
<select relevant SDK>->
<make sure it's the right one>Click OK
.
Open Run/Debug Configurations by:
Run ->
Edit Configurations
->
<make sure it's the right one> Click OK
.
I used the Visual Studio 2008 Uninstall tool and it worked fine for me.
You can use this tool to uninstall Visual Studio 2008 official release and Visual Studio 2008 Release candidate (Only English version).
Found here, on the MSDN Forum: MSDN forum topic.
I found this answer here
Be sure you run the tool with admin-rights.
I found a better way of doing this
function genrateJSONEngine() {
var XLSX = require('xlsx');
var workbook = XLSX.readFile('test.xlsx');
var sheet_name_list = workbook.SheetNames;
sheet_name_list.forEach(function (y) {
var array = workbook.Sheets[y];
var first = array[0].join()
var headers = first.split(',');
var jsonData = [];
for (var i = 1, length = array.length; i < length; i++) {
var myRow = array[i].join();
var row = myRow.split(',');
var data = {};
for (var x = 0; x < row.length; x++) {
data[headers[x]] = row[x];
}
jsonData.push(data);
}
Well this type of error comes when u are taking input a particular file or data in pandas such as :-
data=pd.read_csv('/kaggle/input/fertilizers-by-product-fao/FertilizersProduct.csv)
Then the error is displaying like this :- UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf4 in position 1: invalid continuation byte
So to avoid this type of error can be removed by adding an argument
data=pd.read_csv('/kaggle/input/fertilizers-by-product-fao/FertilizersProduct.csv', encoding='ISO-8859-1')
This is a great example of why performance matters:
Doing something as simple as a test for a string can be expensive if not done correctly.
For example, if I wanted to write a function to test if something is a string, I could do it in one of two ways:
1) const isString = str => (Object.prototype.toString.call(str) === '[object String]');
2) const isString = str => ((typeof str === 'string') || (str instanceof String));
Both of these are pretty straight forward, so what could possibly impact performance? Generally speaking, function calls can be expensive, especially if you don't know what's happening inside. In the first example, there is a function call to Object's toString method. In the second example, there are no function calls, as typeof and instanceof are operators. Operators are significantly faster than function calls.
When the performance is tested, example 1 is 79% slower than example 2!
See the tests: https://jsperf.com/isstringtype
Here the Implementation of Paul Burkes answer:
public class ShadowImageView extends ImageView {
public ShadowImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public ShadowImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ShadowImageView(Context context) {
super(context);
}
private Paint createShadow() {
Paint mShadow = new Paint();
float radius = 10.0f;
float xOffset = 0.0f;
float yOffset = 2.0f;
// color=black
int color = 0xFF000000;
mShadow.setShadowLayer(radius, xOffset, yOffset, color);
return mShadow;
}
@Override
protected void onDraw(Canvas canvas) {
Paint mShadow = createShadow();
Drawable d = getDrawable();
if (d != null){
setLayerType(LAYER_TYPE_SOFTWARE, mShadow);
Bitmap bitmap = ((BitmapDrawable) getDrawable()).getBitmap();
canvas.drawBitmap(bitmap, 0.0f, 0.0f, mShadow);
} else {
super.onDraw(canvas);
}
};
}
TODO:
execute setLayerType(LAYER_TYPE_SOFTWARE, mShadow);
only if API Level is > 10
Check out curljson
$ pip install curljson
$ curljson -i <the-json-api-url>
actually you shouldn't specify port in the host name. Mysql has special option for port (if port differs from default)
kind of
mysql --host=192.168.1.2 --port=3306
That isn't the Node.js command prompt window. That is a language shell to run JavaScript commands, also known as a REPL.
In Windows, there should be a Node.js command prompt in your Start menu or start screen:
Which will open a command prompt window that looks like this:
From there you can switch directories using the cd
command.
Just to clarify the answer given by JScoobyCed, the scp command cannot copy files to directories that require administrative permission. However, you can use the scp command to copy to directories that belong to the remote user.
So, to copy to a directory that requires root privileges, you must first copy that file to a directory belonging to the remote user using the scp command. Next, you must login to the remote account using ssh. Once logged in, you can then move the file to the directory of your choosing by using the sudo mv command. In short, the commands to use are as follows:
Using scp, copy file to a directory in the remote user's account, for example the Documents directory:
scp /path/to/your/local/file remoteUser@some_address:/home/remoteUser/Documents
Next, login to the remote user's account using ssh and then move the file to a restricted directory using sudo:
ssh remoteUser@some_address
sudo mv /home/remoteUser/Documents/file /var/www
The question is little unclear because the title of the question is asking about string and set conversion but then the question at the end asks how do I serialize ? !
let me refresh the concept of Serialization is the process of encoding an object, including the objects it refers to, as a stream of byte data.
If interested to serialize you can use:
json.dumps -> serialize
json.loads -> deserialize
If your question is more about how to convert set to string and string to set then use below code (it's tested in Python 3)
String to Set
set('abca')
Set to String
''.join(some_var_set)
example:
def test():
some_var_set=set('abca')
print("here is the set:",some_var_set,type(some_var_set))
some_var_string=''.join(some_var_set)
print("here is the string:",some_var_string,type(some_var_string))
test()
This problem is beacouse your proyect is named serial.py and the library imported is name serial too , change the name and thats all.
How about print (x, y)
at once.
from matplotlib import pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54
plt.plot(A,B)
for xy in zip(A, B): # <--
ax.annotate('(%s, %s)' % xy, xy=xy, textcoords='data') # <--
plt.grid()
plt.show()
Newer versions of OpenSSL say BEGIN PRIVATE KEY
because they contain the private key + an OID that identifies the key type (this is known as PKCS8 format). To get the old style key (known as either PKCS1 or traditional OpenSSL format) you can do this:
openssl rsa -in server.key -out server_new.key
Alternately, if you have a PKCS1 key and want PKCS8:
openssl pkcs8 -topk8 -nocrypt -in privkey.pem
when you use \\b(\\w+)+\\b
that means exact match with a word containing only word characters ([a-zA-Z0-9])
in your case for example setting \\b
at the begining of regex will accept -12
(with space) but again it won't accept -12
(without space)
for reference to support my words: https://docs.oracle.com/javase/tutorial/essential/regex/bounds.html
Refer below code for formatting date
long strDate1 = 1346524199000;
Date date=new Date(strDate1);
try {
SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yy");
date = df2.format(format.parse("yourdate");
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Edited:
The vertical-align CSS property specifies the vertical alignment of an inline, inline-block or table-cell element.
Read this article for Understanding vertical-align
If you write it like
myButton.onclick = function() { alert(myMessage); };
It will work, but I don't know if that answers your questions.
The data would probably have been posted originally from a web form looking a bit like this (but probably much more complicated):
<form action="http://example.com" method="post">
User login <input name="user[login]" /><br />
User password <input name="user[password]" /><br />
<input type="submit" />
</form>
If the method were "get" instead of "post", clicking the submit button would take you to a URL looking a bit like this:
http://example.com/?user%5Blogin%5D=username&user%5Bpassword%5D=123456
or:
http://example.com/?user[login]=username&user[password]=123456
The web server on the other end will likely take the user[login]
and user[password]
parameters, and make them into a user
object with login
and password
fields containing those values.
Its worth mentioning that the default for an 'Any CPU' compile now checks the 'Prefer 32bit' check box. Being set to AnyCPU, on a 64bit OS with 16gb of RAM can still hit an out of memory exception at 2gb if this is checked.
There are $watchGroup
and $watchCollection
as well. Specifically, $watchGroup
is really helpful if you want to call a function to update an object which has multiple properties in a view that is not dom object, for e.g. another view in canvas, WebGL or server request.
Here, the documentation link.
public void onClickNext(View v) {
FormEditText[] allFields = { etFirstname, etLastname, etAddress, etZipcode, etCity };
boolean allValid = true;
for (FormEditText field: allFields) {
allValid = field.testValidity() && allValid;
}
if (allValid) {
// YAY
} else {
// EditText are going to appear with an exclamation mark and an explicative message.
}
}
I got this error while connecting to Amazon RDS. I checked the server status 50% of CPU usage while it was a development server and no one is using it.
It was working before, and nothing in the connection configuration has changed. Rebooting the server fixed the issue for me.
You could use dplyr::filter()
and negate a grepl()
match:
library(dplyr)
df %>%
filter(!grepl('REVERSE', Name))
Or with dplyr::filter()
and negating a stringr::str_detect()
match:
library(stringr)
df %>%
filter(!str_detect(Name, 'REVERSE'))
I want to say something about the "G" status,
G: Changes on the repo were automatically merged into the working copy
I think the above definition is not cleary, it can generate a little confusion, because all files are automatically merged in to working copy, the correct one should be:
U = item (U)pdated to repository version
G = item’s local changes mer(G)ed with repository
C = item’s local changes (C)onflicted with repository
D = item (D)eleted from working copy
A = item (A)dded to working copy
EDIT: The Numpy project now provides pre-compiled packages in the wheel format (package format enabling compiled code as binary in packages), so the installation is now as easy as with other packages.
Numpy (as also some other packages like Scipy, Pandas etc.) includes lot's of C-, Cython, and Fortran code that needs to be compiled properly, before you can use it. This is, btw, also the reason why these Python-packages provide such fast Linear Algebra.
To get precompiled packages for Windows, have a look at Gohlke's Unofficial Windows Binaries or use a distribution like Winpython (just works) or Anaconda (more complex) which provide an entire preconfigured environment with lots of packages from the scientific python stack.
If the JSON data in your array is sorted in some way, there are a variety of searches you could implement. However, if you're not dealing with a lot of data then you're probably going to be fine with an O(n) operation here (as you have). Anything else would probably be overkill.