You can specify how to initialize members in the member initializer list:
BigMommaClass {
BigMommaClass(int, int);
private:
ThingOne thingOne;
ThingTwo thingTwo;
};
BigMommaClass::BigMommaClass(int numba1, int numba2)
: thingOne(numba1 + numba2), thingTwo(numba1, numba2) {}
You have a few options:
1) Use the Bundle from the Intent:
Intent mIntent = new Intent(this, Example.class);
Bundle extras = mIntent.getExtras();
extras.putString(key, value);
2) Create a new Bundle
Intent mIntent = new Intent(this, Example.class);
Bundle mBundle = new Bundle();
mBundle.putString(key, value);
mIntent.putExtras(mBundle);
3) Use the putExtra() shortcut method of the Intent
Intent mIntent = new Intent(this, Example.class);
mIntent.putExtra(key, value);
Then, in the launched Activity, you would read them via:
String value = getIntent().getExtras().getString(key)
NOTE: Bundles have "get" and "put" methods for all the primitive types, Parcelables, and Serializables. I just used Strings for demonstrational purposes.
You must not have made jQuery available to your script.
Add this to the top of your file:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
This issue is related to the jQuery/JavaScript file not added to the PHP/JSP/ASP file properly. This goes out and gets the jQuery code from the source. You could download that and reference it locally on the server which would be faster.
Or either one can directly link it to jQuery or GoogleCDN or MicrosoftCDN.
Check this How to view contents of NSDictionary variable in Xcode debugger?
I also use
po variableName
print variableName
in Console.
In your case it is possible to execute
print [myData objectAtIndex:indexPath.row]
or
po [myData objectAtIndex:indexPath.row]
You could wrap your return value in the Boolean function
Boolean([return value])
That'll ensure all falsey values are false and truthy statements are true.
I needed to snapshot a div on the page (for a webapp I wrote) that is protected by JWT's and makes very heavy use of Angular.
I had no luck with any of the above methods.
I ended up taking the outerHTML of the div I needed, cleaning it up a little (*) and then sending it to the server where I run wkhtmltopdf against it.
This is working very well for me.
(*) various input devices in my pages didn't render as checked or have their text values when viewed in the pdf... So I run a little bit of jQuery on the html before I send it up for rendering. ex: for text input items -- I copy their .val()'s into 'value' attributes, which then can be seen by wkhtmlpdf
Depends on which apostrophe you are talking about: there’s '
, ‘
, ’
and probably numerous other ones, depending on the context and the language you’re intending to write. And with a declared character encoding of e.g. UTF-8 you can also write them directly into your HTML: '
, ‘
, ’
.
You need to create WifiConfiguration
instance like this:
String networkSSID = "test";
String networkPass = "pass";
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = "\"" + networkSSID + "\""; // Please note the quotes. String should contain ssid in quotes
Then, for WEP network you need to do this:
conf.wepKeys[0] = "\"" + networkPass + "\"";
conf.wepTxKeyIndex = 0;
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
For WPA network you need to add passphrase like this:
conf.preSharedKey = "\""+ networkPass +"\"";
For Open network you need to do this:
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
Then, you need to add it to Android wifi manager settings:
WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
wifiManager.addNetwork(conf);
And finally, you might need to enable it, so Android connects to it:
List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
for( WifiConfiguration i : list ) {
if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
wifiManager.disconnect();
wifiManager.enableNetwork(i.networkId, true);
wifiManager.reconnect();
break;
}
}
UPD: In case of WEP, if your password is in hex, you do not need to surround it with quotes.
Try to call your proc in this way:
DECLARE @UserIDout int
EXEC YOURPROC @EmailAddress = 'sdfds', @NickName = 'sdfdsfs', ..., @UserId = @UserIDout OUTPUT
SELECT @UserIDout
In your component's template you can use multiple arguments by separating them with colons:
{{ myData | myPipe: 'arg1':'arg2':'arg3'... }}
From your code it will look like this:
new MyPipe().transform(myData, arg1, arg2, arg3)
And in your transform function inside your pipe you can use the arguments like this:
export class MyPipe implements PipeTransform {
// specify every argument individually
transform(value: any, arg1: any, arg2: any, arg3: any): any { }
// or use a rest parameter
transform(value: any, ...args: any[]): any { }
}
Beta 16 and before (2016-04-26)
Pipes take an array that contains all arguments, so you need to call them like this:
new MyPipe().transform(myData, [arg1, arg2, arg3...])
And your transform function will look like this:
export class MyPipe implements PipeTransform {
transform(value:any, args:any[]):any {
var arg1 = args[0];
var arg2 = args[1];
...
}
}
All the changes to the NSMutableURLRequest
must be made before calling NSURLConnection
.
I see this problem as I copy and paste the code above and run TCPMon
and see the request is GET
instead of the expected POST
.
NSURL *aUrl = [NSURL URLWithString:@"http://www.apple.com/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
NSString *postString = @"company=Locassa&quality=AWESOME!";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request
delegate:self];
In Java 8 and later, use the java.time framework (Tutorial).
Duration
The Duration
class represents a span of time as a number of seconds plus a fractional second. It can count days, hours, minutes, and seconds.
ZonedDateTime now = ZonedDateTime.now();
ZonedDateTime oldDate = now.minusDays(1).minusMinutes(10);
Duration duration = Duration.between(oldDate, now);
System.out.println(duration.toDays());
ChronoUnit
If all you need is the number of days, alternatively you can use the ChronoUnit
enum. Notice the calculation methods return a long
rather than int
.
long days = ChronoUnit.DAYS.between( then, now );
This is the way i use it. It's very simple and work very well.. Ionic html:
<ion-content>
<ion-grid class="ion-text-center">
<ion-row class="ion-margin">
<ion-col>
<ion-title>
<ion-text color="default">
Your title remove if don't want use
</ion-text>
</ion-title>
</ion-col>
</ion-row>
<ion-row class="header-row">
<ion-col>
<ion-text>Data</ion-text>
</ion-col>
<ion-col>
<ion-text>Cliente</ion-text>
</ion-col>
<ion-col>
<ion-text>Pagamento</ion-text>
</ion-col>
</ion-row>
<ion-row>
<ion-col>
<ion-text>
19/10/2020
</ion-text>
</ion-col>
<ion-col>
<ion-text>
Nome
</ion-text>
</ion-col>
<ion-col>
<ion-text>
R$ 200
</ion-text>
</ion-col>
</ion-row>
</ion-grid>
</ion-content>
CSS:
.header-row {
background: #7163AA;
color: #fff;
font-size: 18px;
}
ion-col {
border: 1px solid #ECEEEF;
}
If you are using Eclipse then you can do this by specifying the required size for the particular application in its Run Configuration's VM Arguments as EX: -Xms128m -Xmx512m
Or if you want all applications running from your eclipse to have the same specified size then you can specify this in the eclipse.ini
file which is present in your Eclipse home directory.
To get the size of the JVM during Runtime you can use Runtime.totalMemory()
which returns the total amount of memory in the Java virtual machine, measured in bytes.
cut -c1
This is POSIX, and unlike case
actually extracts the first char if you need it for later:
myvar=abc
first_char="$(printf '%s' "$myvar" | cut -c1)"
if [ "$first_char" = a ]; then
echo 'starts with a'
else
echo 'does not start with a'
fi
awk substr
is another POSIX but less efficient alternative:
printf '%s' "$myvar" | awk '{print substr ($0, 0, 1)}'
printf '%s'
is to avoid problems with escape characters: https://stackoverflow.com/a/40423558/895245 e.g.:
myvar='\n'
printf '%s' "$myvar" | cut -c1
outputs \
as expected.
${::}
does not seem to be POSIX.
See also: How to extract the first two characters of a string in shell scripting?
In JavaScript you can use template literals:
let value = 100;
console.log(`The size is ${ value }`);
Coming from someone who has tried a number of "C# IDEs" on the Mac, your best bet is to install a virtual desktop with Windows and Visual Studio. It really is the best development IDE out there for .NET, nothing even comes close.
On a related note: I hate XCode.
Update: Use Xamarin Studio. It's solid.
run it under a different user. assuming this is a windows box, create a user account for scheduled tasks. run it as that user. The command prompt will only show for the user currently logged in.
From other member and my problem:
Camera Rotation issue depend on different Devices and certain Version.
Version 1.6: to fix the Rotation Issue, and it is good for most of devices
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
{
p.set("orientation", "portrait");
p.set("rotation",90);
}
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
{
p.set("orientation", "landscape");
p.set("rotation", 90);
}
Version 2.1: depend on kind of devices, for example, Cannt fix the issue with XPeria X10, but it is good for X8, and Mini
Camera.Parameters parameters = camera.getParameters();
parameters.set("orientation", "portrait");
camera.setParameters(parameters);
Version 2.2: not for all devices
camera.setDisplayOrientation(90);
Here is the complete solution
html code,
create the text anf file upload fields as shown below
<div class="form-group">
<div>
<label for="usr">User Name:</label>
<input type="text" id="usr" ng-model="model.username">
</div>
<div>
<label for="pwd">Password:</label>
<input type="password" id="pwd" ng-model="model.password">
</div><hr>
<div>
<div class="col-lg-6">
<input type="file" file-model="model.somefile"/>
</div>
</div>
<div>
<label for="dob">Dob:</label>
<input type="date" id="dob" ng-model="model.dob">
</div>
<div>
<label for="email">Email:</label>
<input type="email"id="email" ng-model="model.email">
</div>
<button type="submit" ng-click="saveData(model)" >Submit</button>
directive code
create a filemodel directive to parse file
.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};}]);
Service code
append the file and fields to form data and do $http.post as shown below remember to keep 'Content-Type': undefined
.service('fileUploadService', ['$http', function ($http) {
this.uploadFileToUrl = function(file, username, password, dob, email, uploadUrl){
var myFormData = new FormData();
myFormData.append('file', file);
myFormData.append('username', username);
myFormData.append('password', password);
myFormData.append('dob', dob);
myFormData.append('email', email);
$http.post(uploadUrl, myFormData, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
In controller
Now in controller call the service by sending required data to be appended in parameters,
$scope.saveData = function(model){
var file = model.myFile;
var uploadUrl = "/api/createUsers";
fileUpload.uploadFileToUrl(file, model.username, model.password, model.dob, model.email, uploadUrl);
};
I think you can use [UIScreen mainScreen].bounds.size.height
and calculate step for your objects. when you calculate step you can set coordinates for two resolutions.
Or you can get height like above and if(iphone5) then... else if(iphone4) then... else if(ipad)
. Something like this.
If you use storyboards then you have to create new for new iPhone i think.
This works well for me:
jQuery(document).ready(function($) {
var intputElements = document.getElementsByTagName("INPUT");
for (var i = 0; i < intputElements.length; i++) {
intputElements[i].oninvalid = function (e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
if (e.target.name == "email") {
e.target.setCustomValidity("Please enter a valid email address.");
} else {
e.target.setCustomValidity("Please enter a password.");
}
}
}
}
});
and the form I'm using it with (truncated):
<form id="welcome-popup-form" action="authentication" method="POST">
<input type="hidden" name="signup" value="1">
<input type="email" name="email" id="welcome-email" placeholder="Email" required></div>
<input type="password" name="passwd" id="welcome-passwd" placeholder="Password" required>
<input type="submit" id="submitSignup" name="signup" value="SUBMIT" />
</form>
We found same issue building the project on Jenkins. With buildToolsVersion '25.0.2'
, we must accept licenses before building. In our case, we needed to run:
yes | sdkmanager --update
that accepts licenses for the sdkmanager itself, and then
yes | sdkmanager --licenses
that accepts new licenses not previously accepted
Remember: run these commans with the same user that jenkins
does. In our Debian, the Jenkins user is just jenkins
. In other words: doing it as root
will create the accepted licenses as root
, so Jenkins will not read them.
By the way, we found sdkmanager
at /var/lib/jenkins/tools/android-sdk/tools/bin
. If yours is not there, find it with find / -name "sdkmanager"
You can use the createRef to change the state of the child component from the parent component. Here are all the steps.
Create a method to change the state in the child component.
2 - Create a reference for the child component in parent component using React.createRef().
3 - Attach reference with the child component using ref={}.
4 - Call the child component method using this.yor-reference.current.method.
Parent component
class ParentComponent extends Component {
constructor()
{
this.changeChild=React.createRef()
}
render() {
return (
<div>
<button onClick={this.changeChild.current.toggleMenu()}>
Toggle Menu from Parent
</button>
<ChildComponent ref={this.changeChild} />
</div>
);
}
}
Child Component
class ChildComponent extends Component {
constructor(props) {
super(props);
this.state = {
open: false;
}
}
toggleMenu=() => {
this.setState({
open: !this.state.open
});
}
render() {
return (
<Drawer open={this.state.open}/>
);
}
}
MyModelVm.cs
public class MyModelVm
{
public HttpStatusCode StatusCode { get; set; }
}
Index.cshtml
@model MyNamespace.MyModelVm
@functions
{
string GetErrorMessage()
{
var isNotFound = Model.StatusCode == HttpStatusCode.NotFound;
string errorMessage;
if (isNotFound)
{
errorMessage = Resources.NotFoundMessage;
}
else
{
errorMessage = Resources.GeneralErrorMessage
}
return errorMessage;
}
}
<div>
@GetErrorMessage()
</div>
I am late to this thread, but I too had a similar requirement. Since my script was constructing the request for curl dynamically, I wanted a similar structure of the command across GET, POST and PUT.
Here is what works for me
For PUT request:
curl --request PUT --url http://localhost:8080/put --header 'content-type: application/x-www-form-urlencoded' --data 'bar=baz&foo=foo1'
For POST request:
curl --request POST --url http://localhost:8080/post --header 'content-type: application/x-www-form-urlencoded' --data 'bar=baz&foo=foo1'
For GET request:
curl --request GET --url 'http://localhost:8080/get?foo=bar&foz=baz'
I implemented some code to do it manually:
using System.Security.Principal;
public bool IsUserAdministrator()
{
bool isAdmin;
try
{
WindowsIdentity user = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(user);
isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
}
catch (UnauthorizedAccessException ex)
{
isAdmin = false;
}
catch (Exception ex)
{
isAdmin = false;
}
return isAdmin;
}
If you can use Guava library, since version 21, you can use
Streams.stream(iterable)
If you mean lists, try ==
:
l1 = [1,2,3]
l2 = [1,2,3,4]
l1 == l2 # False
If you mean array
:
l1 = array('l', [1, 2, 3])
l2 = array('d', [1.0, 2.0, 3.0])
l1 == l2 # True
l2 = array('d', [1.0, 2.0, 3.0, 4.0])
l1 == l2 # False
If you want to compare strings (per your comment):
date_string = u'Thu Sep 16 13:14:15 CDT 2010'
date_string2 = u'Thu Sep 16 14:14:15 CDT 2010'
date_string == date_string2 # False
If you are stuck with .Net 4.0 and the target site is using TLS 1.2, you need the following line instead.
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
source: TLS 1.2 and .NET Support: How to Avoid Connection Errors
LocalDateTime
is a date-time without a time-zone. You specified the time zone offset format symbol in the format, however, LocalDateTime
doesn't have such information. That's why the error occured.
If you want time-zone information, you should use ZonedDateTime
.
DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z");
ZonedDateTime.now().format(FORMATTER);
=> "20140829 14:12:22.122000 +09"
When I had this error, it went away after I my computer crashed and restarted. Try closing and reopening your IDE, if that doesn't work, try restarting your computer. I had just installed the libraries at that point without restarting pycharm when I got this error.
Never closed PyCharm first to test because my blasted computer keeps crashing randomly... working on that one, but it at least solved this problem.. little victories.. :).
If you have downloaded several Jdks you have to delete all except of the JDK you want to use!
I am late to the party, but for option #1, I would go with IdentityServer3(.NET 4.6 or below) or IdentityServer4 (compatible with Core) .
You can reuse your existing user store in your app and plug that to be IdentityServer's User Store. Then the clients must be pointed to your IdentityServer as the open id provider.
If you want to display text that cannot be edited or selected you can simply use a label
Have you tried Zeroturnaround Zip library? It's really neat! Zip a folder is just a one liner:
ZipUtil.pack(new File("D:\\reports\\january\\"), new File("D:\\reports\\january.zip"));
(thanks to Oleg Šelajev for the example)
As a workaround to force the evaluation of the SELECT clause before the WHERE clause, you could put the former in a sub-query while the latter remains in the main query:
SELECT * FROM (
SELECT (InvoiceTotal - PaymentTotal - CreditTotal) AS BalanceDue
FROM Invoices) AS temp
WHERE BalanceDue > 0
Yes the tab character is one character. You can match it in java with "\t".
If you want to get the full width of the page, including overflow, use document.body.scrollWidth
.
Please try this:
byte[] decodedString = Base64.decode(person_object.getPhoto(),Base64.NO_WRAP);
InputStream inputStream = new ByteArrayInputStream(decodedString);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
user_image.setImageBitmap(bitmap);
The mentioned package/classes are not present in the compiletime classpath. Basically, Java has no idea what you're talking about when you say to import this and that. It can't find them in the classpath.
It's part of Apache Commons FileUpload. Just download the JAR and drop it in /WEB-INF/lib
folder of the webapp project and this error should disappear. Don't forget to do the same for Apache Commons IO, that's where FileUpload depends on, otherwise you will get the same problem during runtime.
Unrelated to the concrete problem, I see that you're using Tomcat 7, which is a Servlet 3.0 compatible container. Do you know that you can just use the new request.getPart()
method to obtain the uploaded file without the need for the whole Commons FileUpload stuff? Just add @MultipartConfig
annotation to the servlet class so that you can use it. See also How to upload files to server using JSP/Servlet?
PEP 3136 proposes labeled break/continue. Guido rejected it because "code so complicated to require this feature is very rare". The PEP does mention some workarounds, though (such as the exception technique), while Guido feels refactoring to use return will be simpler in most cases.
I also came across this issue. It came when I created new DB and I had pending changes for my code-first DB migration then I tried to run "Update-Database" command. Solution : Run "Add-Migration -MigrationName" command to create new migration for new DB. Then run "Update-Database" command.
TL;DR; If you're still having trouble after restarting apache or nginx, also try restarting the php-fpm
service.
The answers here don't always satisfy the requirement to force a reload of the php.ini file. On numerous occasions I've taken these steps to be rewarded with no update, only to find the solution I need after also restarting the php-fpm service. So if restarting apache or nginx doesn't trigger a php.ini update although you know the files are updated, try restarting php-fpm as well.
To restart the service:
Note: prepend sudo if not root
Using SysV Init scripts directly:
/etc/init.d/php-fpm restart # typical
/etc/init.d/php5-fpm restart # debian-style
/etc/init.d/php7.0-fpm restart # debian-style PHP 7
Using service wrapper script
service php-fpm restart # typical
service php5-fpm restart # debian-style
service php7.0-fpm restart. # debian-style PHP 7
Using Upstart (e.g. ubuntu):
restart php7.0-fpm # typical (ubuntu is debian-based) PHP 7
restart php5-fpm # typical (ubuntu is debian-based)
restart php-fpm # uncommon
Using systemd (newer servers):
systemctl restart php-fpm.service # typical
systemctl restart php5-fpm.service # uncommon
systemctl restart php7.0-fpm.service # uncommon PHP 7
Or whatever the equivalent is on your system.
The above commands taken directly from this server fault answer
Just from reading what you have written, you will need to add the file class.phpmailer.php to your directory as well.
We can Increasing the maximum limit using .htaccess
file.
php_value session.gc_maxlifetime 10800
php_value max_input_time 10800
php_value max_execution_time 10800
php_value upload_max_filesize 110M
php_value post_max_size 120M
If sometimes other way are not working, this way is working perfect.
function getWeekdayDatesFrom($format, $start_date_epoch, $end_date_epoch, $range) {
$dates_arr = array();
if( ! $range) {
$range = round(abs($start_date_epoch-$end_date_epoch)/86400) + 1;
} else {
$range = $range + 1; //end date inclusive
}
$current_date_epoch = $start_date_epoch;
for($i = 1; $i <= $range; $i+1) {
$d = date('N', $current_date_epoch);
if($d <= 5) { // not sat or sun
$dates_arr[] = "'".date($format, $current_date_epoch)."'";
}
$next_day_epoch = strtotime('+'.$i.'day', $start_date_epoch);
$i++;
$current_date_epoch = $next_day_epoch;
}
return $dates_arr;
}
Two options: 1, add css inline like style="background:black" Or 2. In the head include the css as a style tag block.
Use both. In fact refer a guide like the OWASP XSS Prevention cheat sheet, on the possible cases for usage of output encoding and input validation.
Input validation helps when you cannot rely on output encoding in certain cases. For instance, you're better off validating inputs appearing in URLs rather than encoding the URLs themselves (Apache will not serve a URL that is url-encoded). Or for that matter, validate inputs that appear in JavaScript expressions.
Ultimately, a simple thumb rule will help - if you do not trust user input enough or if you suspect that certain sources can result in XSS attacks despite output encoding, validate it against a whitelist.
Do take a look at the OWASP ESAPI source code on how the output encoders and input validators are written in a security library.
this can also be tried...
SELECT l.ip, tbl2.ip as ip2, tbl2.hostname
FROM login_log l
LEFT JOIN (SELECT ip_location.ip, ip_location.hostname
FROM ip_location
WHERE ip_location.ip is null)tbl2
There is a very simple way in which you can do this. It involves injecting a javascript code to a label control from code behind. here is sample code:
<head runat="server">
<title>Calling javascript function from code behind example</title>
<script type="text/javascript">
function showDialogue() {
alert("this dialogue has been invoked through codebehind.");
}
</script>
</head>
..........
lblJavaScript.Text = "<script type='text/javascript'>showDialogue();</script>";
Check out the full code here: http://softmate-technologies.com/javascript-from-CodeBehind.htm (dead)
Link from Internet Archive: https://web.archive.org/web/20120608053720/http://softmate-technologies.com/javascript-from-CodeBehind.htm
OSFMount , MagicDisc , Gizmo Director/Gizmo Drive , The Takeaway .
All these work well on .img files
There isn't really a way to do this without the css getting a little convoluted, but here's the cleanest solution I could put together (the breakpoints in this are just for example purposes, change them to whatever breakpoints you're actually using.) The key is :nth-of-type
(or :nth-child
-- either would work in this case.)
Smallest viewport:
@media (max-width:$smallest-breakpoint) {
.row div {
background: #eee;
}
.row div:nth-of-type(2n) {
background: #fff;
}
}
Medium viewport:
@media (min-width:$smallest-breakpoint) and (max-width:$mid-breakpoint) {
.row div {
background: #eee;
}
.row div:nth-of-type(4n+1), .row div:nth-of-type(4n+2) {
background: #fff;
}
}
Largest viewport:
@media (min-width:$mid-breakpoint) and (max-width:9999px) {
.row div {
background: #eee;
}
.row div:nth-of-type(6n+4),
.row div:nth-of-type(6n+5),
.row div:nth-of-type(6n+6) {
background: #fff;
}
}
Working fiddle here
if ID
is available - You can use getElementById()
var element = document.getElementById('elementId');
if (typeof(element) != 'undefined' && element != null)
{
// exists.
}
OR Try with Jquery -
if ($(document).find(yourElement).length == 0)
{
// -- Not Exist
}
serialize() is not a good idea if you want to send a form with post method. For example if you want to pass a file via ajax its not gonna work.
Suppose that we have a form with this id : "myform".
the better solution is to make a FormData and send it:
var myform = document.getElementById("myform");
var fd = new FormData(myform );
$.ajax({
url: "example.php",
data: fd,
cache: false,
processData: false,
contentType: false,
type: 'POST',
success: function (dataofconfirm) {
// do something with the result
}
});
To change multiple files (and saving a backup of each as *.bak):
perl -p -i -e "s/\|/x/g" *
will take all files in directory and replace |
with x
this is called a “Perl pie” (easy as a pie)
I know this is old, but it is actually very possible.
Go to your WinSCP profile (Session > Sites > Site Manager)
Click on Edit > Advanced... > Environment > SFTP
Insert sudo su -c /usr/lib/sftp-server
in "SFTP Server" (note this path might be different in your system)
Save and connect
#outerDiv{_x000D_
width: 500px;_x000D_
height: 500px;_x000D_
position:relative;_x000D_
background:grey;_x000D_
display:flex;_x000D_
justify-content:center;_x000D_
align-items:center;_x000D_
}_x000D_
_x000D_
#innerDiv{_x000D_
background:cyan;_x000D_
width: 284px;_x000D_
height: 290px;_x000D_
_x000D_
_x000D_
}
_x000D_
<div id="outerDiv">_x000D_
<div id="innerDiv">Inner Div_x000D_
</div>_x000D_
</div>
_x000D_
you can do it by simply adding css style mentioned above. All the best. For any query please comment
To reverse rails generate
, use rails destroy
:
rails destroy Model
See "rails destroy
" for more information.
You most likely have your virtual machine’s networking set to NAT. If you set your networking to Bridged you should be able to access your host machine by its hostname. For example, if your hostname is “jsmith-Precision-7510” and you want to open http://localhost:3000/, you will be able to view that page at http://jsmith-Precision-7510:3000/.
To find your hostname, open a terminal/console and then run the command hostname
. Your hostname will be outputted on the next line.
See the VirtualBox documentation for instructions on how to set your networking setttings to Bridged.
There is an app in google play known as MyAppSharer. Open the app, search for the app that you have installed, check apk and select share. The app would take some time and build the apk. You can then close the app. The apk of the file is located in /sdcard/MyAppSharer
This does not require rooting your phone and works only for apps that are currently installed on your phone
I would argue against "abstract" tests. I think a test is a concrete idea and doesn't have an abstraction. If you have common elements, put them in helper methods or classes for everyone to use.
As for testing an abstract test class, make sure you ask yourself what it is you're testing. There are several approaches, and you should find out what works in your scenario. Are you trying to test out a new method in your subclass? Then have your tests only interact with that method. Are you testing the methods in your base class? Then probably have a separate fixture only for that class, and test each method individually with as many tests as necessary.
You can't edit the image via CSS. The only solution I can think of is to edit the image and change its opacity, or make different images with all the opacities needed.
If you want this in config, you can set npm config like so:
npm config set prefix "$(pwd)/vendor/node_modules"
or
npm config set prefix "$HOME/vendor/node_modules"
Check your config with
npm config ls -l
Or as @pje says and use the --prefix
flag
Short answer is: Don't. ;-) Pointers are to be used where you can't use anything else. It is either because the lack of appropriate functionality, missing data types or for pure perfomance. More below...
Short answer here is: Where you cannot use anything else. In C you don't have any support for complex datatypes such as a string. There are also no way of passing a variable "by reference" to a function. That's where you have to use pointers. Also you can have them to point at virtually anything, linked lists, members of structs and so on. But let's not go into that here.
With little effort and much confusion. ;-) If we talk about simple data types such as int and char there is little difference between an array and a pointer.
These declarations are very similar (but not the same - e.g., sizeof
will return different values):
char* a = "Hello";
char a[] = "Hello";
You can reach any element in the array like this
printf("Second char is: %c", a[1]);
Index 1 since the array starts with element 0. :-)
Or you could equally do this
printf("Second char is: %c", *(a+1));
The pointer operator (the *) is needed since we are telling printf that we want to print a character. Without the *, the character representation of the memory address itself would be printed. Now we are using the character itself instead. If we had used %s instead of %c, we would have asked printf to print the content of the memory address pointed to by 'a' plus one (in this example above), and we wouldn't have had to put the * in front:
printf("Second char is: %s", (a+1)); /* WRONG */
But this would not have just printed the second character, but instead all characters in the next memory addresses, until a null character (\0) were found. And this is where things start to get dangerous. What if you accidentally try and print a variable of the type integer instead of a char pointer with the %s formatter?
char* a = "Hello";
int b = 120;
printf("Second char is: %s", b);
This would print whatever is found on memory address 120 and go on printing until a null character was found. It is wrong and illegal to perform this printf statement, but it would probably work anyway, since a pointer actually is of the type int in many environments. Imagine the problems you might cause if you were to use sprintf() instead and assign this way too long "char array" to another variable, that only got a certain limited space allocated. You would most likely end up writing over something else in the memory and cause your program to crash (if you are lucky).
Oh, and if you don't assign a string value to the char array / pointer when you declare it, you MUST allocate sufficient amount of memory to it before giving it a value. Using malloc, calloc or similar. This since you only declared one element in your array / one single memory address to point at. So here's a few examples:
char* x;
/* Allocate 6 bytes of memory for me and point x to the first of them. */
x = (char*) malloc(6);
x[0] = 'H';
x[1] = 'e';
x[2] = 'l';
x[3] = 'l';
x[4] = 'o';
x[5] = '\0';
printf("String \"%s\" at address: %d\n", x, x);
/* Delete the allocation (reservation) of the memory. */
/* The char pointer x is still pointing to this address in memory though! */
free(x);
/* Same as malloc but here the allocated space is filled with null characters!*/
x = (char *) calloc(6, sizeof(x));
x[0] = 'H';
x[1] = 'e';
x[2] = 'l';
x[3] = 'l';
x[4] = 'o';
x[5] = '\0';
printf("String \"%s\" at address: %d\n", x, x);
/* And delete the allocation again... */
free(x);
/* We can set the size at declaration time as well */
char xx[6];
xx[0] = 'H';
xx[1] = 'e';
xx[2] = 'l';
xx[3] = 'l';
xx[4] = 'o';
xx[5] = '\0';
printf("String \"%s\" at address: %d\n", xx, xx);
Do note that you can still use the variable x after you have performed a free() of the allocated memory, but you do not know what is in there. Also do notice that the two printf() might give you different addresses, since there is no guarantee that the second allocation of memory is performed in the same space as the first one.
try
{
Bitmap bmp = null;
URL url = new URL("Your_URL");
URLConnection conn = url.openConnection();
bmp = BitmapFactory.decodeStream(conn.getInputStream());
File f = new File(Environment.getExternalStorageDirectory(),System.currentTimeMillis() + ".jpg");
if(f.exists())
f.delete();
f.createNewFile();
Bitmap bitmap = bmp;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
Log.e(TAG, "imagepath: "+f );
}
catch (Exception e)
{
e.printStackTrace();
}
From JavaScript, since the Github API is CORS enabled:
fetch('https://api.github.com/repos/webdev23/source_control_sentry')
.then(v => v.json()).then((function(v){
console.log(v['size'] + "KB")
})
)
_x000D_
For the final, compiled code of your application, the short answer is “no”. Different tools are able to extract different information from the code (e.g. the forms setups) and there are P code decompilers (see Edgar's excellent link for such tools). However, up to this day, there is no decompiler for native code. I'm not aware of anything similar for other high-level languages either.
generateNumbers()
expects a parameter and you aren't passing one in!
generateNumbers() also returns after it has set the first random number - seems to be some confusion about what it is trying to do.
What is meta_key
? Strip out all of the meta_value
conditionals, reduce, and you end up with this:
SELECT
*
FROM
meta_data
WHERE
(
(meta_key = 'lat')
)
AND
(
(meta_key = 'long')
)
GROUP BY
item_id
Since meta_key
can never simultaneously equal two different values, no results will be returned.
Based on comments throughout this question and answers so far, it sounds like you're looking for something more along the lines of this:
SELECT
*
FROM
meta_data
WHERE
(
(meta_key = 'lat')
AND
(
(meta_value >= '60.23457047672217')
OR
(meta_value <= '60.23457047672217')
)
)
OR
(
(meta_key = 'long')
AND
(
(meta_value >= '24.879140853881836')
OR
(meta_value <= '24.879140853881836')
)
)
GROUP BY
item_id
Note the OR
between the top-level conditionals. This is because you want records which are lat
or long
, since no single record will ever be lat
and long
.
I'm still not sure what you're trying to accomplish by the inner conditionals. Any non-null value will match those numbers. So maybe you can elaborate on what you're trying to do there. I'm also not sure about the purpose of the GROUP BY
clause, but that might be outside the context of this question entirely.
The easiest way to do it directly in the list is
HashSet<Object> seen=new HashSet<>();
employee.removeIf(e->!seen.add(e.getID()));
removeIf
will remove an element if it meets the specified criteriaSet.add
will return false
if it did not modify the Set
, i.e. already contains the valueOf course, it only works if the list supports removal of elements.
Updated list as of 6/11/2013
204.15.20.0/22
69.63.176.0/20
66.220.144.0/20
66.220.144.0/21
69.63.184.0/21
69.63.176.0/21
74.119.76.0/22
69.171.255.0/24
173.252.64.0/18
69.171.224.0/19
69.171.224.0/20
103.4.96.0/22
69.63.176.0/24
173.252.64.0/19
173.252.70.0/24
31.13.64.0/18
31.13.24.0/21
66.220.152.0/21
66.220.159.0/24
69.171.239.0/24
69.171.240.0/20
31.13.64.0/19
31.13.64.0/24
31.13.65.0/24
31.13.67.0/24
31.13.68.0/24
31.13.69.0/24
31.13.70.0/24
31.13.71.0/24
31.13.72.0/24
31.13.73.0/24
31.13.74.0/24
31.13.75.0/24
31.13.76.0/24
31.13.77.0/24
31.13.96.0/19
31.13.66.0/24
173.252.96.0/19
69.63.178.0/24
31.13.78.0/24
31.13.79.0/24
31.13.80.0/24
31.13.82.0/24
31.13.83.0/24
31.13.84.0/24
31.13.85.0/24
31.13.87.0/24
31.13.88.0/24
31.13.89.0/24
31.13.90.0/24
31.13.91.0/24
31.13.92.0/24
31.13.93.0/24
31.13.94.0/24
31.13.95.0/24
69.171.253.0/24
69.63.186.0/24
204.15.20.0/22
69.63.176.0/20
69.63.176.0/21
69.63.184.0/21
66.220.144.0/20
69.63.176.0/20
I am a VIMer. I can do some rare Hex edits with:
:%!xxd
to switch into hex mode
:%!xxd -r
to exit from hex mode
But I strongly recommend ht
apt-cache show ht
Package: ht
Version: 2.0.18-1
Installed-Size: 1780
Maintainer: Alexander Reichle-Schmehl <[email protected]>
Homepage: http://hte.sourceforge.net/
Note: The package is called ht
, whereas the executable is named hte
after the package was installed.
Dot grammar maybe more swift!
@(intValueDemo).stringValue
for example
int intValueDemo = 1;
//or
NSInteger intValueDemo = 1;
//So you can use dot grammar
NSLog(@"%@",@(intValueDemo).stringValue);
Thanks Box. I'm using MyStile Theme and I needed to display the product category name in my search result page. I added this function to my child theme functions.php
Hope it helps others.
/* Post Meta */
if (!function_exists( 'woo_post_meta')) {
function woo_post_meta( ) {
global $woo_options;
global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
$product_cat = $term->name;
break;
}
?>
<aside class="post-meta">
<ul>
<li class="post-category">
<?php the_category( ', ', $post->ID) ?>
<?php echo $product_cat; ?>
</li>
<?php the_tags( '<li class="tags">', ', ', '</li>' ); ?>
<?php if ( isset( $woo_options['woo_post_content'] ) && $woo_options['woo_post_content'] == 'excerpt' ) { ?>
<li class="comments"><?php comments_popup_link( __( 'Leave a comment', 'woothemes' ), __( '1 Comment', 'woothemes' ), __( '% Comments', 'woothemes' ) ); ?></li>
<?php } ?>
<?php edit_post_link( __( 'Edit', 'woothemes' ), '<li class="edit">', '</li>' ); ?>
</ul>
</aside>
<?php
}
}
?>
Try this:
SELECT to_char(sysdate - (2 / 24), 'MM-DD-YYYY HH24') FROM DUAL
To test it using a new date instance:
SELECT to_char(TO_DATE('11/06/2015 00:00','dd/mm/yyyy HH24:MI') - (2 / 24), 'MM-DD-YYYY HH24:MI') FROM DUAL
Output is: 06-10-2015 22:00, which is the previous day.
The solution depends on the answer to the question - are all the parameters going to be the same type and if so will each be treated the same?
If the parameters are not the same type or more importantly are not going to be treated the same then you should use method overloading:
public class MyClass
{
public void doSomething(int i)
{
...
}
public void doSomething(int i, String s)
{
...
}
public void doSomething(int i, String s, boolean b)
{
...
}
}
If however each parameter is the same type and will be treated in the same way then you can use the variable args feature in Java:
public MyClass
{
public void doSomething(int... integers)
{
for (int i : integers)
{
...
}
}
}
Obviously when using variable args you can access each arg by its index but I would advise against this as in most cases it hints at a problem in your design. Likewise, if you find yourself doing type checks as you iterate over the arguments then your design needs a review.
Don't use HTTP use SSH instead
change
https://github.com/WEMP/project-slideshow.git
to
[email protected]:WEMP/project-slideshow.git
you can do it in .git/config
file
You need to account for DateTime Kind too.
public static DateTime GetTime(this DateTime d)
{
return new DateTime(d.TimeOfDay.Ticks, d.Kind);
}
You can create a subprocess using Windows cmd.exe
that restarts yourself:
Process process = new Process();
process.StartInfo.FileName = "cmd";
process.StartInfo.Arguments = "/c net stop \"servicename\" & net start \"servicename\"";
process.Start();
How to export your Visual Studio Code extensions from the terminal. Here is git for that. Maybe this helps somebody.
Note: Unix-like systems only.
code --list-extensions | sed -e 's/^/code --install-extension /' > my_vscode_extensions.sh
less my_vscode_extesions.sh
Run your my_vscode_extensions.sh
using a Bash command:
bash my_vscode_extensions.sh
My team was hitting a situation with multiple databases on one server, depending on which database you connected to, the ROLE in question was not returned by SELECT * FROM pg_catalog.pg_user
, as proposed by @erwin-brandstetter and @a_horse_with_no_name. The conditional block executed, and we hit role "my_user" already exists
.
Unfortunately we aren't sure of exact conditions, but this solution works around the problem:
DO
$body$
BEGIN
CREATE ROLE my_user LOGIN PASSWORD 'my_password';
EXCEPTION WHEN others THEN
RAISE NOTICE 'my_user role exists, not re-creating';
END
$body$
It could probably be made more specific to rule out other exceptions.
For example, lets say we want to display only the first 10 items of an array, we could do this using the SlicePipe like so:
<ul>
<li *ngFor="let item of items | slice:0:10">
{{ item }}
</li>
</ul>
To make POST request instead of GET request using urllib2
, you need to specify empty data, for example:
import urllib2
req = urllib2.Request("http://am.domain.com:8080/openam/json/realms/root/authenticate?authIndexType=Module&authIndexValue=LDAP")
req.add_header('X-OpenAM-Username', 'demo')
req.add_data('')
r = urllib2.urlopen(req)
getElementById
returns null
if there is no such element.
In a parent component you can use @ViewChild() to access child component's method/variable.
@Component({
selector: 'app-number-parent',
templateUrl: './number-parent.component.html'
})
export class NumberParentComponent {
@ViewChild(NumberComponent)
private numberComponent: NumberComponent;
increase() {
this.numberComponent.increaseByOne();
}
decrease() {
this.numberComponent.decreaseByOne();
}
}
Update:
Angular 8 onwards -
@ViewChild(NumberComponent, { static: false })
you may try like this using jquery
var arr = [1,2,2,3,4,5,5,5,6,7,7,8,9,10,10];
var uniqueVals = [];
$.each(arr, function(i, el){
if($.inArray(el, uniqueVals) === -1) uniqueVals.push(el);
});
Some applications like skype uses wamp's default port:80 so you have to find out which application is accessing this port you can easily find it by using TCP View. End the service accessing this port and restart wamp server. Now it will work.
If you love the command line, you can also do this using drush with the watchdog show command:
drush ws
More information about this command available here:
You almost had it with the your first query you just need to specify the columns, that way you can exclude your primary key in the insert which will enact the auto-increment you likely have on the table to automatically create a new primary key for the entry.
For example change this:
insert into table select * from table where primarykey=1
To this:
INSERT INTO table (col1, col2, col3)
SELECT col1, col2, col3
FROM table
WHERE primarykey = 1
Just don't include the primarykey column in either the column list for the INSERT or for the SELECT portions of the query.
string verificationCode ="dmdsnjds5344gfgk65585";
string code = "";
Regex r1 = new Regex("\\d+");
Match m1 = r1.Match(verificationCode);
while (m1.Success)
{
code += m1.Value;
m1 = m1.NextMatch();
}
The first <img />
is invalid - src
is a required attribute. data-src
is an attribute than can be leveraged by, say, JavaScript, but has no presentational meaning.
Using execComand:
<input type="button" name="save" value="Save" onclick="javascript:document.execCommand('SaveAs','true','your_file.txt')">
In the next link: execCommand
Use std::cout
, since cout
is defined within the std
namespace. Alternatively, add a using std::cout;
directive.
We must to stopPropagation()
In order to avoid Clicks triggers event too many times.
$(this).find('#cameraImageView').on('click', function(evt) {
evt.stopPropagation();
console.log("Camera click event.");
});
It Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. This method does not accept any arguments.
We can use event.isPropagationStopped()
to determine if this method was ever called (on that event object).
This method works for custom events triggered with trigger(), as well.Note that this will not prevent other handlers on the same element from running.
The answer with screenshots (put the checkbox as in the second pic, then press OK):
CSS cannot disable the textbox, you can however turn off display or visibility.
display: none;
visibility: hidden;
Or you can also set the HTMLattribute:
disabled="disabled"
From http://readableweb.com/mo-bulletproofer-font-face-css-syntax/
Now that web fonts are supported in Firefox 3.5 and 3.6, Internet Explorer, Safari, Opera 10.5, and Chrome, web authors face new questions: How do these implementations differ? What CSS techniques will accommodate all? Firefox developer John Daggett recently posted a little roundup about these issues and the workarounds that are being explored. In response to that post, and in response to, particularly, Paul Irish’s work, I came up with the following @font-face CSS syntax. It’s been tested in all of the above named browsers including IE 8, 7, and 6. So far, so good. The following is a test page that declares the free Droid font as a complete font-family with Regular, Italic, Bold, and Bold Italic. View source for details. Alert: Be aware that Readable Web has released it’s first @font-face related software utility for creating natively compressed EOT files quickly and easily. It has it’s own web site and, in addition to the utility itself, the download package contains helpful documentation, a test font, and an EOT test page. It’s called EOTFAST If you’re working with @font-face, it’s a must-have.
Here’s The Mo’ Bulletproofer Code:
@font-face{ /* for IE */
font-family:FishyFont;
src:url(fishy.eot);
}
@font-face { /* for non-IE */
font-family:FishyFont;
src:url(http://:/) format("No-IE-404"),url(fishy.ttf) format("truetype");
}
If you are using the latest version of Bootstrap and Ruby on Rails, you can just type it in the html.erb file as so:
<nav class="navbar navbar-transparent">
And that is all you need.
Note that GCC has an extension to the designated initializer notation which is very useful for the context. It is also allowed by clang
without comment (in part because it tries to be compatible with GCC).
The extension notation allows you to use ...
to designate a range of elements to be initialized with the following value. For example:
#include <stdio.h>
enum { ROW = 5, COLUMN = 10 };
int array[ROW][COLUMN] = { [0 ... ROW-1] = { [0 ... COLUMN-1] = 1 } };
int main(void)
{
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COLUMN; j++)
printf("%2d", array[i][j]);
putchar('\n');
}
return 0;
}
The output is, unsurprisingly:
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
Note that Fortran 66 (Fortran IV) had repeat counts for initializers for arrays; it's always struck me as odd that C didn't get them when designated initializers were added to the language. And Pascal uses the 0..9
notation to designate the range from 0 to 9 inclusive, but C doesn't use ..
as a token, so it is not surprising that was not used.
Note that the spaces around the ...
notation are essentially mandatory; if they're attached to numbers, then the number is interpreted as a floating point number. For example, 0...9
would be tokenized as 0.
, .
, .9
, and floating point numbers aren't allowed as array subscripts.
With the named constants, ...ROW-1
would not cause trouble, but it is better to get into the safe habits.
Addenda:
I note in passing that GCC 7.3.0 rejects:
int array[ROW][COLUMN] = { [0 ... ROW-1] = { [0 ... COLUMN-1] = { 1 } } };
where there's an extra set of braces around the scalar initializer 1
(error: braces around scalar initializer [-Werror]
). I'm not sure that's correct given that you can normally specify braces around a scalar in int a = { 1 };
, which is explicitly allowed by the standard. I'm not certain it's incorrect, either.
I also wonder if a better notation would be [0]...[9]
— that is unambiguous, cannot be confused with any other valid syntax, and avoids confusion with floating point numbers.
int array[ROW][COLUMN] = { [0]...[4] = { [0]...[9] = 1 } };
Maybe the standards committee would consider that?
you can try this for html side
<label for="appointment-time">Choose Time</label>
<input class="form-control" type="time" ng-model="time" ng-change="ChangeTime()" />
<label class="form-control" >{{displayTime}}</label>
JavaScript Side
function addMinutes(time/*"hh:mm"*/, minsToAdd/*"N"*/)
{
function z(n)
{
return (n<10? '0':'') + n;
}
var bits = time.split(':');
var mins = bits[0]*60 + (+bits[1]) + (+minsToAdd);
return z(mins%(24*60)/60 | 0) + ':' + z(mins%60);
}
$scope.ChangeTime=function()
{
var d = new Date($scope.time);
var hours=d.getHours();
var minutes=Math.round(d.getMinutes());
var ampm = hours >= 12 ? 'PM' : 'AM';
var Time=hours+':'+minutes;
var DisplayTime=addMinutes(Time, duration);
$scope.displayTime=Time+' - '+DisplayTime +' '+ampm;
}
I know, this is an old post, but it's the first hit on everyone's favorite search engine if you are looking for error 1025.
However, there is an easy "hack" for fixing this issue:
Before you execute your command(s) you first have to disable the foreign key constraints check using this command:
SET FOREIGN_KEY_CHECKS = 0;
Then you are able to execute your command(s).
After you are done, don't forget to enable the foreign key constraints check again, using this command:
SET FOREIGN_KEY_CHECKS = 1;
Good luck with your endeavor.
Try this code
public static String pathRoot = "/sdcard/system/temp/";
public static String readFromFile(Context contect, String nameFile) {
String aBuffer = "";
try {
File myFile = new File(pathRoot + nameFile);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
String aDataRow = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow;
}
myReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return aBuffer;
}
Drop the hash - that's for identifying the id attribute.
Sum of arithmetical progression
(A1+AN)/2*N = (1 + (N-1))/2*(N-1) = N*(N-1)/2
If the remote branch name begins with special characteres you need to use single quotes around it in the checkout command, or else git won't know which branch you are talking about.
For example, I tried to checkout a remote branch named as #9773
but the command didn't work properly, as shown in the picture below:
For some reason I wondered if the sharp symbol (#) could have something to do with it, and then I tried surrounding the branch name with single quotes, like '#9773'
rathen than just #9773
, and fortunately it worked fine.
$ git checkout -b '#9773' origin/'#9773'
this works for me on my Android 7.11 phone:
<!-- TOOLBAR -->
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:contentInsetStartWithNavigation="0dp">
<TextView
style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"
android:id="@+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/create_account_title"
android:textColor="@color/color_dark_grey"/>
</android.support.v7.widget.Toolbar>
note: I had absolutely no success with padding=0, or contentInsetLeft=0, or contentInsetStart=0
Your file structure says that folder name is Container
with a capital C. But you are trying to import it by container
with a lowercase c. You will need to change the import or the folder name because the paths are case sensitive.
When you do a cmp a,b
, the flags are set as if you had calculated a - b
.
Then the jmp
-type instructions check those flags to see if the jump should be made.
In other words, the first block of code you have (with my comments added):
cmp al,dl ; set flags based on the comparison
jg label1 ; then jump based on the flags
would jump to label1
if and only if al
was greater than dl
.
You're probably better off thinking of it as al > dl
but the two choices you have there are mathematically equivalent:
al > dl
al - dl > dl - dl (subtract dl from both sides)
al - dl > 0 (cancel the terms on the right hand side)
You need to be careful when using jg
inasmuch as it assumes your values were signed. So, if you compare the bytes 101 (101 in two's complement) with 200 (-56 in two's complement), the former will actually be greater. If that's not what was desired, you should use the equivalent unsigned comparison.
See here for more detail on jump selection, reproduced below for completeness. First the ones where signed-ness is not appropriate:
+--------+------------------------------+-------------+--------------------+
|Instr | Description | signed-ness | Flags |
+--------+------------------------------+-------------+--------------------+
| JO | Jump if overflow | | OF = 1 |
+--------+------------------------------+-------------+--------------------+
| JNO | Jump if not overflow | | OF = 0 |
+--------+------------------------------+-------------+--------------------+
| JS | Jump if sign | | SF = 1 |
+--------+------------------------------+-------------+--------------------+
| JNS | Jump if not sign | | SF = 0 |
+--------+------------------------------+-------------+--------------------+
| JE/ | Jump if equal | | ZF = 1 |
| JZ | Jump if zero | | |
+--------+------------------------------+-------------+--------------------+
| JNE/ | Jump if not equal | | ZF = 0 |
| JNZ | Jump if not zero | | |
+--------+------------------------------+-------------+--------------------+
| JP/ | Jump if parity | | PF = 1 |
| JPE | Jump if parity even | | |
+--------+------------------------------+-------------+--------------------+
| JNP/ | Jump if no parity | | PF = 0 |
| JPO | Jump if parity odd | | |
+--------+------------------------------+-------------+--------------------+
| JCXZ/ | Jump if CX is zero | | CX = 0 |
| JECXZ | Jump if ECX is zero | | ECX = 0 |
+--------+------------------------------+-------------+--------------------+
Then the unsigned ones:
+--------+------------------------------+-------------+--------------------+
|Instr | Description | signed-ness | Flags |
+--------+------------------------------+-------------+--------------------+
| JB/ | Jump if below | unsigned | CF = 1 |
| JNAE/ | Jump if not above or equal | | |
| JC | Jump if carry | | |
+--------+------------------------------+-------------+--------------------+
| JNB/ | Jump if not below | unsigned | CF = 0 |
| JAE/ | Jump if above or equal | | |
| JNC | Jump if not carry | | |
+--------+------------------------------+-------------+--------------------+
| JBE/ | Jump if below or equal | unsigned | CF = 1 or ZF = 1 |
| JNA | Jump if not above | | |
+--------+------------------------------+-------------+--------------------+
| JA/ | Jump if above | unsigned | CF = 0 and ZF = 0 |
| JNBE | Jump if not below or equal | | |
+--------+------------------------------+-------------+--------------------+
And, finally, the signed ones:
+--------+------------------------------+-------------+--------------------+
|Instr | Description | signed-ness | Flags |
+--------+------------------------------+-------------+--------------------+
| JL/ | Jump if less | signed | SF <> OF |
| JNGE | Jump if not greater or equal | | |
+--------+------------------------------+-------------+--------------------+
| JGE/ | Jump if greater or equal | signed | SF = OF |
| JNL | Jump if not less | | |
+--------+------------------------------+-------------+--------------------+
| JLE/ | Jump if less or equal | signed | ZF = 1 or SF <> OF |
| JNG | Jump if not greater | | |
+--------+------------------------------+-------------+--------------------+
| JG/ | Jump if greater | signed | ZF = 0 and SF = OF |
| JNLE | Jump if not less or equal | | |
+--------+------------------------------+-------------+--------------------+
Not necessary to execute as script
Calling object.paintComponent(g)
is an error.
Instead this method is called automatically when the panel is created. The paintComponent()
method can also be called explicitly by the repaint()
method defined in Component
class.
The effect of calling repaint()
is that Swing automatically clears the graphic on the panel and executes the paintComponent
method to redraw the graphics on this panel.
Html Code :
<a id="f">Show First content!</a>
<br/>
<a id="s">Show Second content!!</a>
<div class="a">Default Content</div>
<div class="ab hideDiv">First content</div>
<div class="abc hideDiv">Second content</div>
Script code:
$(document).ready(function() {
$("#f").mouseover(function(){
$('.a,.abc').addClass('hideDiv');
$('.ab').removeClass('hideDiv');
}).mouseout(function() {
$('.a').removeClass('hideDiv');
$('.ab,.abc').addClass('hideDiv');
});
$("#s").mouseover(function(){
$('.a,.ab').addClass('hideDiv');
$('.abc').removeClass('hideDiv');
}).mouseout(function() {
$('.a').removeClass('hideDiv');
$('.ab,.abc').addClass('hideDiv');
});
});
css code:
.hideDiv
{
display:none;
}
This is too simple
final CharSequence[] items = {"Take Photo", "Choose from Library", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(MyProfile.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
getCapturesProfilePicFromCamera();
} else if (items[item].equals("Choose from Library")) {
getProfilePicFromGallery();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
TRUNCATE will blank your table and reset primary key DELETE will also make your table blank but it will not reset primary key.
we can use for truncate
TRUNCATE TABLE tablename
we can use for delete
DELETE FROM tablename
we can also give conditions as below
DELETE FROM tablename WHERE id='xyz'
Same think can be done using lambda function. Here I am reading the data from a xlsx file.
import pandas as pd
df = pd.read_excel("data.xlsx", sheet_name = 4)
print df
Output:
cluster Unnamed: 1 date budget actual
0 a 2014-01-01 00:00:00 11000 10000
1 a 2014-02-01 00:00:00 1200 1000
2 a 2014-03-01 00:00:00 200 100
3 b 2014-04-01 00:00:00 200 300
4 b 2014-05-01 00:00:00 400 450
5 c 2014-06-01 00:00:00 700 1000
6 c 2014-07-01 00:00:00 1200 1000
7 c 2014-08-01 00:00:00 200 100
8 c 2014-09-01 00:00:00 200 300
Sum two columns into 3rd new one.
df['variance'] = df.apply(lambda x: x['budget'] + x['actual'], axis=1)
print df
Output:
cluster Unnamed: 1 date budget actual variance
0 a 2014-01-01 00:00:00 11000 10000 21000
1 a 2014-02-01 00:00:00 1200 1000 2200
2 a 2014-03-01 00:00:00 200 100 300
3 b 2014-04-01 00:00:00 200 300 500
4 b 2014-05-01 00:00:00 400 450 850
5 c 2014-06-01 00:00:00 700 1000 1700
6 c 2014-07-01 00:00:00 1200 1000 2200
7 c 2014-08-01 00:00:00 200 100 300
8 c 2014-09-01 00:00:00 200 300 500
By using designated array initializers your string array is independent of the order of elements in the enum:
enum Values {
Val1,
Val2
};
constexpr string_view v_name[] = {
[Val1] = "Value 1",
[Val2] = "Value 2"
}
_tmain is a macro that gets redefined depending on whether or not you compile with Unicode or ASCII. It is a Microsoft extension and isn't guaranteed to work on any other compilers.
The correct declaration is
int _tmain(int argc, _TCHAR *argv[])
If the macro UNICODE is defined, that expands to
int wmain(int argc, wchar_t *argv[])
Otherwise it expands to
int main(int argc, char *argv[])
Your definition goes for a bit of each, and (if you have UNICODE defined) will expand to
int wmain(int argc, char *argv[])
which is just plain wrong.
std::cout works with ASCII characters. You need std::wcout if you are using wide characters.
try something like this
#include <iostream>
#include <tchar.h>
#if defined(UNICODE)
#define _tcout std::wcout
#else
#define _tcout std::cout
#endif
int _tmain(int argc, _TCHAR *argv[])
{
_tcout << _T("There are ") << argc << _T(" arguments:") << std::endl;
// Loop through each argument and print its number and value
for (int i=0; i<argc; i++)
_tcout << i << _T(" ") << argv[i] << std::endl;
return 0;
}
Or you could just decide in advance whether to use wide or narrow characters. :-)
Updated 12 Nov 2013:
Changed the traditional "TCHAR" to "_TCHAR" which seems to be the latest fashion. Both work fine.
End Update
The tag is not closed:
$form.append("<input type=button value=button");
Should be:
$form.append('<input type="button" value="button">');
See the Maven - Users forum 'version' contains an expression but should be a constant. Better way to add a new version?:
here is why this is a bad plan.
the pom that gets deployed will not have the property value resolved, so anyone depending on that pom will pick up the dependency as being the string uninterpolated with the ${ } and much hilarity will ensue in your build process.
in maven 2.1.0 and/or 2.2.0 an attempt was made to deploy poms with resolved properties... this broke more than expected, which is why those two versions are not recommended, 2.2.1 being the recommended 2.x version.
I've used Sothink SWF decompiler a couple of times, the only problem is that as project gets more complex, the output of decompiler gets harder to compile back again. But it ensures that you can get your .as files most of the time, compilable fla is a question.
In the fiddle your blob isn't a blob, it's a string representation of hexadecimal data. Try this on a blob and your done
var image = document.createElement('img');
let reader=new FileReader()
reader.addEventListener('loadend',()=>{
let contents=reader.result
image.src = contents
document.body.appendChild(image);
})
if(blob instanceof Blob) reader.readAsDataURL(blob)
readAsDataURL give you a base64 encoded image ready for you image element () source (src)
class Loader extends StatefulWidget {
@override
State createState() => LoaderState();
}
class LoaderState extends State<Loader> with SingleTickerProviderStateMixin {
AnimationController controller;
Animation<double> animation;
@override
void initState() {
super.initState();
controller = AnimationController(
duration: Duration(milliseconds: 1200), vsync: this);
animation = CurvedAnimation(parent: controller, curve: Curves.elasticOut);
animation.addListener(() {
this.setState(() {});
});
animation.addStatusListener((AnimationStatus status) {});
controller.repeat();
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
color: Colors.blue,
height: 3.0,
width: animation.value * 100.0,
),
Padding(
padding: EdgeInsets.only(bottom: 5.0),
),
Container(
color: Colors.blue[300],
height: 3.0,
width: animation.value * 75.0,
),
Padding(
padding: EdgeInsets.only(bottom: 5.0),
),
Container(
color: Colors.blue,
height: 3.0,
width: animation.value * 50.0,
)
],
);
}
}
Expanded(
child: Padding(
padding:
EdgeInsets.only(left: 20.0, right: 5.0, top:20.0),
child: GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => FirstScreen()));
},
child: Container(
alignment: Alignment.center,
height: 45.0,
decoration: BoxDecoration(
color: Color(0xFF1976D2),
borderRadius: BorderRadius.circular(9.0)),
child: Text('Login',
style: TextStyle(
fontSize: 20.0, color: Colors.white))),
),
),
),
If it's an object method, you need to pass the object to CallObjectMethod
:
jobject result = env->CallObjectMethod(obj, messageMe, jstr);
What you were doing was the equivalent of jstr.messageMe()
.
Since your is a void method, you should call:
env->CallVoidMethod(obj, messageMe, jstr);
If you want to return a result, you need to change your JNI signature (the ()V
means a method of void
return type) and also the return type in your Java code.
Have a look at jQuery's .parseXML()
[docs]:
var $xml = $(jQuery.parseXML(xml));
var $test = $xml.find('Page[Name="test"] > controls > test');
Use the exact layout numbers described here and a nice blogpost here.
so:
layout := "2006-01-02T15:04:05.000Z"
str := "2014-11-12T11:45:26.371Z"
t, err := time.Parse(layout, str)
if err != nil {
fmt.Println(err)
}
fmt.Println(t)
gives:
>> 2014-11-12 11:45:26.371 +0000 UTC
I know. Mind boggling. Also caught me first time.
Go just doesn't use an abstract syntax for datetime components (YYYY-MM-DD
), but these exact numbers (I think the time of the first commit of go Nope, according to this. Does anyone know?).
On Ubuntu, placed your id_rsa
and id_rsa.pub
files in /var/lib/jenkins/.ssh
Make Jenkins own them
sudo chown -R jenkins /var/lib/jenkins/.ssh/
Make sure that Jenkins key is added as deploy key with RW access in GitHub (or similar) - use the id_rsa.pub
key for this.
Now everything should jive with the SCM Sync Plugin.
Here i have a simple solution, - (Multiple permission checking)
String[] permissions = new String[]{
Manifest.permission.WRITE_CALL_LOG,
Manifest.permission.READ_CALL_LOG,
Manifest.permission.READ_CONTACTS,
Manifest.permission.WRITE_CONTACTS}; // Here i used multiple permission check
Then call it in Oncreate
if (checkPermissions()) { // permissions granted.
getCallDetails();
}
Finally, copy the below code
private boolean checkPermissions() {
int result;
List<String> listPermissionsNeeded = new ArrayList<>();
for (String p : permissions) {
result = ContextCompat.checkSelfPermission(getApplicationContext(), p);
if (result != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(p);
}
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), MULTIPLE_PERMISSIONS);
return false;
}
return true;
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MULTIPLE_PERMISSIONS: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permissions granted.
getCallDetails(); // Now you call here what ever you want :)
} else {
String perStr = "";
for (String per : permissions) {
perStr += "\n" + per;
} // permissions list of don't granted permission
}
return;
}
}
}
You'll need to order by the same field you're ordering by now, but descending.
As an example, if you have a time stamp when the upload was done called upload_time
, you'd do something like this;
For Pre-Laravel 4
return DB::table('files')->order_by('upload_time', 'desc')->first();
For Laravel 4 and onwards
return DB::table('files')->orderBy('upload_time', 'desc')->first();
For Laravel 5.7 and onwards
return DB::table('files')->latest('upload_time')->first();
This will order the rows in the files table by upload time, descending order, and take the first one. This will be the latest uploaded file.
Any time you need to separate allocation from initialization, you'll need placement new and explicit calling of the destructor manually. Today, it's rarely necessary, since we have the standard containers, but if you have to implement some new sort of container, you'll need it.
Through discourse it's clear that the problem lies in using VS2010 to write the query, as it uses the canonical CONCAT()
function which is limited to 2 parameters. There's probably a way to change that, but I'm not aware of it.
An alternative:
SELECT '1'+'2'+'3'
This approach requires non-string values to be cast/converted to strings, as well as NULL
handling via ISNULL()
or COALESCE()
:
SELECT ISNULL(CAST(Col1 AS VARCHAR(50)),'')
+ COALESCE(CONVERT(VARCHAR(50),Col2),'')
I needed rollback for the 1.9.x version, in 2.x.x not work
composer self-update --rollback
This method should handle filenames which have any number/combination of spaces in them...
svn status /home/websites/website1 | grep -Z "^?" | sed s/^?// | sed s/[[:space:]]*// | xargs -i svn add \"{}\"
Here is an explanation of what that command does:
Use the -i argument to xargs to handle being able to import files names with spaces into 'svn add' - basically, -i sets {} to be used as a placeholder so we can put the " characters around the filename used by 'svn add'.
An advantage of this method is that this should handle filenames with spaces in them.
If you press C-x C-e
command that will open your default editor which defined .bashrc
, after that you can use all powerful features of your editor. When you save and exit, the lines will wait your enter.
If you want to define your editor, just write for Ex. EDITOR=emacs -nw
or EDITOR=vi
inside of ~/.bashrc
read = com.ExecuteReader()
SqlDataReader
has a function Read()
that reads the next row from your query's results and returns a bool
whether it found a next row to read or not. So you need to check that before you actually get the columns from your reader (which always just gets the current row that Read()
got). Or preferably make a loop while(read.Read())
if your query returns multiple rows.
From CSS-Tricks... there is a one step way to do this without z-indexing and adding pseudo elements-- requires linear gradient which I think means you need CSS3 support
.tinted-image {
background-image:
/* top, transparent red */
linear-gradient(
rgba(255, 0, 0, 0.45),
rgba(255, 0, 0, 0.45)
),
/* your image */
url(image.jpg);
}
If you are working with redis and Java 8, you can take a look at JetCache:
@Cached(expire = 10, timeUnit = TimeUnit.MINUTES)
User getUserById(long userId);
Here is one solution
# GET EQUATION AND R-SQUARED AS STRING
# SOURCE: https://groups.google.com/forum/#!topic/ggplot2/1TgH-kG5XMA
lm_eqn <- function(df){
m <- lm(y ~ x, df);
eq <- substitute(italic(y) == a + b %.% italic(x)*","~~italic(r)^2~"="~r2,
list(a = format(unname(coef(m)[1]), digits = 2),
b = format(unname(coef(m)[2]), digits = 2),
r2 = format(summary(m)$r.squared, digits = 3)))
as.character(as.expression(eq));
}
p1 <- p + geom_text(x = 25, y = 300, label = lm_eqn(df), parse = TRUE)
EDIT. I figured out the source from where I picked this code. Here is the link to the original post in the ggplot2 google groups
Code:
TelephonyManager tMgr = (TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();
Required Permission:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
According to the highly upvoted comments, there are a few caveats to be aware of. This can return null
or ""
or even "???????"
, and it can return a stale phone number that is no longer valid. If you want something that uniquely identifies the device, you should use getDeviceId()
instead.
Use the zzz
format specifier to get the timezone offset as hours and minutes. You also want to use the HH
format specifier to get the hours in 24 hour format.
DateTime.Now.ToString("yyyy-MM-ddTHH:mm:sszzz")
Result:
2011-08-09T23:49:58+02:00
Some culture settings uses periods instead of colons for time, so you might want to use literal colons instead of time separators:
DateTime.Now.ToString("yyyy-MM-ddTHH':'mm':'sszzz")
its better to use the Dependency than to attache it to the class.
public function add_question(Request $request)
{
return Request::all();
}
or if you prefer using input variable use
public function add_question(Request $input)
{
return $input::all();
}
you can now use the global request method provided by laravel
request()
for example to get the first_name of a form input.
request()->first_name
// or
request('first_name')
All right, after Jeffrey L Whitledge said that there was no performance difference (as of 1997), I went and tested it. I ran this small benchmark:
public class Main {
private static final int NUM_TESTS = 100;
private static int ITERATIONS = 1000000;
// time counters
private static long inTime = 0L;
private static long aroundTime = 0L;
public static void main(String[] args) {
for (int i = 0; i < NUM_TESTS; i++) {
test();
ITERATIONS += 1; // so the tests don't always return the same number
}
System.out.println("Inside loop: " + (inTime/1000000.0) + " ms.");
System.out.println("Around loop: " + (aroundTime/1000000.0) + " ms.");
}
public static void test() {
aroundTime += testAround();
inTime += testIn();
}
public static long testIn() {
long start = System.nanoTime();
Integer i = tryInLoop();
long ret = System.nanoTime() - start;
System.out.println(i); // don't optimize it away
return ret;
}
public static long testAround() {
long start = System.nanoTime();
Integer i = tryAroundLoop();
long ret = System.nanoTime() - start;
System.out.println(i); // don't optimize it away
return ret;
}
public static Integer tryInLoop() {
int count = 0;
for (int i = 0; i < ITERATIONS; i++) {
try {
count = Integer.parseInt(Integer.toString(count)) + 1;
} catch (NumberFormatException ex) {
return null;
}
}
return count;
}
public static Integer tryAroundLoop() {
int count = 0;
try {
for (int i = 0; i < ITERATIONS; i++) {
count = Integer.parseInt(Integer.toString(count)) + 1;
}
return count;
} catch (NumberFormatException ex) {
return null;
}
}
}
I checked the resulting bytecode using javap to make sure that nothing got inlined.
The results showed that, assuming insignificant JIT optimizations, Jeffrey is correct; there is absolutely no performance difference on Java 6, Sun client VM (I did not have access to other versions). The total time difference is on the order of a few milliseconds over the entire test.
Therefore, the only consideration is what looks cleanest. I find that the second way is ugly, so I will stick to either the first way or Ray Hayes's way.
Recently encountered this and kept getting warnings/errors about the method being void.
We're in the business of placating the compiler and this clears it up:
public async Task MyVoidAsyncMethod()
{
await Task.CompletedTask;
}
This brings together the best of all the advice here so far. No return statement is necessary unless you're actually doing something in the method.
For me, Error has been fixed when activated Billing in google console. (I got 1-year developer trial)
You can try a list comp
>>> exampleSet = [{'type':'type1'},{'type':'type2'},{'type':'type2'}, {'type':'type3'}]
>>> keyValList = ['type2','type3']
>>> expectedResult = [d for d in exampleSet if d['type'] in keyValList]
>>> expectedResult
[{'type': 'type2'}, {'type': 'type2'}, {'type': 'type3'}]
Another way is by using filter
>>> list(filter(lambda d: d['type'] in keyValList, exampleSet))
[{'type': 'type2'}, {'type': 'type2'}, {'type': 'type3'}]
Cell spacing and margin is the space between cells.
Cell padding is space inside cells, between the cell border (even if invisible) and the cell content, such as text.
Try http://www.sql-server-helper.com/tips/date-formats.aspx. Lists all formats needed. In this case select Convert(varchar(10),CONVERT(date,YourDateColumn,106),103) change 103 to 104 id you need dd.mm.yyyy
You can do
:noh
or :nohlsearch
to temporarily disable search highlighting until the next search.
Unless the variable k
is defined, that's probably what's causing your trouble. Something like this will do what you want:
var new_tweets = { };
new_tweets.k = { };
new_tweets.k.tweet_id = 98745521;
new_tweets.k.user_id = 54875;
new_tweets.k.data = { };
new_tweets.k.data.in_reply_to_screen_name = 'other_user';
new_tweets.k.data.text = 'tweet text';
// Will create the JSON string you're looking for.
var json = JSON.stringify(new_tweets);
You can also do it all at once:
var new_tweets = {
k: {
tweet_id: 98745521,
user_id: 54875,
data: {
in_reply_to_screen_name: 'other_user',
text: 'tweet_text'
}
}
}
What you have here is a non-local variable (https://en.wikipedia.org/wiki/Non-local_variable), i.e. you access a local variable in a method an anonymous class.
Local variables of the method are kept on the stack and lost as soon as the method ends, however even after the method ends, the local inner class object is still alive on the heap and will need to access this variable (here, when an action is performed).
I would suggest two workarounds :
Either you make your own class that implements actionlistenner
and takes as constructor argument, your variable and keeps it as an class attribute. Therefore you would only access this variable within the same object.
Or (and this is probably the best solution) just qualify a copy of the variable final
to access it in the inner scope as the error suggests to make it a constant:
This would suit your case since you are not modifying the value of the variable.
My issue was that there was no __init__.py
file in the same folder as the migrations. On adding the __init__.py
to the folder which contained them, manage.py migrate
found and ran them.
// drunk, fix later
Wish I were kidding. And knowing the developer who wrote the code, I think he meant it literally.
Thanks for the tip, i used this to get my date "20071122" parsed, I needed to add datetimestyles, I used none and it worked:
DateTime dt = DateTime.MinValue;
DateTime.TryParseExact("20071122", "yyyyMMdd", null,System.Globalization.DateTimeStyles.None, out dt);
Some compilers also implement an extension, that allows multi-character constants. The C99 standard says:
6.4.4.4p10: "The value of an integer character constant containing more than one character (e.g., 'ab'), or containing a character or escape sequence that does not map to a single-byte execution character, is implementation-defined."
This could look like this, for instance:
const uint32_t png_ihdr = 'IHDR';
The resulting constant (in GCC, which implements this) has the value you get by taking each character and shifting it up, so that 'I' ends up in the most significant bits of the 32-bit value. Obviously, you shouldn't rely on this if you are writing platform independent code.
In my case, I wanted to check out
a new branch
that has cut recently
but it's it big in size and I want to save time and internet bandwidth, as I'm in a slow metered network
so I copped the previous branch
that I already checked in
I went to the working directory, and from svn info, I can see it's on the previous branch I did the following command (you can find this command from svn switch --help
)
svn switch ^/branches/newBranchName
go check svn info
again you can see it is becoming the newBranchName go ahead and svn up
and this how I got the new branch easily, quickly with minimum data transmitting over the internet
hope sharing my case helps and speeds up your work
Update (December 1, 2009):
I'd like to amend this answer and concede that the original answer was flawed.
The original analysis does apply to objects that require finalization – and the point that practices shouldn’t be accepted on the surface without an accurate, in-depth understanding still stands.
However, it turns out that DataSets, DataViews, DataTables suppress finalization in their constructors – this is why calling Dispose() on them explicitly does nothing.
Presumably, this happens because they don’t have unmanaged resources; so despite the fact that MarshalByValueComponent makes allowances for unmanaged resources, these particular implementations don’t have the need and can therefore forgo finalization.
(That .NET authors would take care to suppress finalization on the very types that normally occupy the most memory speaks to the importance of this practice in general for finalizable types.)
Notwithstanding, that these details are still under-documented since the inception of the .NET Framework (almost 8 years ago) is pretty surprising (that you’re essentially left to your own devices to sift though conflicting, ambiguous material to put the pieces together is frustrating at times but does provide a more complete understanding of the framework we rely on everyday).
After lots of reading, here’s my understanding:
If an object requires finalization, it could occupy memory longer than it needs to – here’s why: a) Any type that defines a destructor (or inherits from a type that defines a destructor) is considered finalizable; b) On allocation (before the constructor runs), a pointer is placed on the Finalization queue; c) A finalizable object normally requires 2 collections to be reclaimed (instead of the standard 1); d) Suppressing finalization doesn’t remove an object from the finalization queue (as reported by !FinalizeQueue in SOS)
This command is misleading; Knowing what objects are on the finalization queue (in and of itself) isn’t helpful; Knowing what objects are on the finalization queue and still require finalization would be helpful (is there a command for this?)
Suppressing finalization turns a bit off in the object's header indicating to the runtime that it doesn’t need to have its Finalizer invoked (doesn’t need to move the FReachable queue); It remains on the Finalization queue (and continues to be reported by !FinalizeQueue in SOS)
The DataTable, DataSet, DataView classes are all rooted at MarshalByValueComponent, a finalizable object that can (potentially) handle unmanaged resources
4 (new references):
Original Answer:
There are a lot of misleading and generally very poor answers on this - anyone who's landed here should ignore the noise and read the references below carefully.
Without a doubt, Dispose should be called on any Finalizable objects.
DataTables are Finalizable.
Calling Dispose significantly speeds up the reclaiming of memory.
MarshalByValueComponent calls GC.SuppressFinalize(this) in its Dispose() - skipping this means having to wait for dozens if not hundreds of Gen0 collections before memory is reclaimed:
With this basic understanding of finalization we can already deduce some very important things:
First, objects that need finalization live longer than objects that do not. In fact, they can live a lot longer. For instance, suppose an object that is in gen2 needs to be finalized. Finalization will be scheduled but the object is still in gen2, so it will not be re-collected until the next gen2 collection happens. That could be a very long time indeed, and, in fact, if things are going well it will be a long time, because gen2 collections are costly and thus we want them to happen very infrequently. Older objects needing finalization might have to wait for dozens if not hundreds of gen0 collections before their space is reclaimed.
Second, objects that need finalization cause collateral damage. Since the internal object pointers must remain valid, not only will the objects directly needing finalization linger in memory but everything the object refers to, directly and indirectly, will also remain in memory. If a huge tree of objects was anchored by a single object that required finalization, then the entire tree would linger, potentially for a long time as we just discussed. It is therefore important to use finalizers sparingly and place them on objects that have as few internal object pointers as possible. In the tree example I just gave, you can easily avoid the problem by moving the resources in need of finalization to a separate object and keeping a reference to that object in the root of the tree. With that modest change only the one object (hopefully a nice small object) would linger and the finalization cost is minimized.
Finally, objects needing finalization create work for the finalizer thread. If your finalization process is a complex one, the one and only finalizer thread will be spending a lot of time performing those steps, which can cause a backlog of work and therefore cause more objects to linger waiting for finalization. Therefore, it is vitally important that finalizers do as little work as possible. Remember also that although all object pointers remain valid during finalization, it might be the case that those pointers lead to objects that have already been finalized and might therefore be less than useful. It is generally safest to avoid following object pointers in finalization code even though the pointers are valid. A safe, short finalization code path is the best.
Take it from someone who's seen 100s of MBs of non-referenced DataTables in Gen2: this is hugely important and completely missed by the answers on this thread.
References:
1 - http://msdn.microsoft.com/en-us/library/ms973837.aspx
2 - http://vineetgupta.spaces.live.com/blog/cns!8DE4BDC896BEE1AD!1104.entry http://www.dotnetfunda.com/articles/article524-net-best-practice-no-2-improve-garbage-collector-performance-using-finalizedispose-pattern.aspx
3 - http://codeidol.com/csharp/net-framework/Inside-the-CLR/Automatic-Memory-Management/
According to the answers here and on other 'flows, I've made a version that looks like the one of Google Chrome, with css3 transition. JS Fiddle
Lets start eazy, since we have the js above on this page, we can worry about the css and layout. The layout that we will be using is an <a>
element with a <img>
element or a font awesome icon (<i class="fa fa-flag"></i>
) and a <span>
to show the keyboard shortcuts. So this is the structure:
<a href="#" onclick="doSomething()">
<img src="path/to/image.gif" />
This is a menu option
<span>Ctrl + K</span>
</a>
We will put these in a div and show that div on the right-click. Let's style them like in Google Chrome, shall we?
#menu a {
display: block;
color: #555;
text-decoration: no[...]
Now we will add the code from the accepted answer, and get the X and Y value of the cursor. To do this, we will use e.clientX
and e.clientY
. We are using client, so the menu div has to be fixed.
var i = document.getElementById("menu").style;
if (document.addEventListener) {
document.addEventListener('contextmenu', function(e) {
var posX = e.clientX;
var posY = e.client[...]
And that is it! Just add the css transisions to fade in and out, and done!
var i = document.getElementById("menu").style;_x000D_
if (document.addEventListener) {_x000D_
document.addEventListener('contextmenu', function(e) {_x000D_
var posX = e.clientX;_x000D_
var posY = e.clientY;_x000D_
menu(posX, posY);_x000D_
e.preventDefault();_x000D_
}, false);_x000D_
document.addEventListener('click', function(e) {_x000D_
i.opacity = "0";_x000D_
setTimeout(function() {_x000D_
i.visibility = "hidden";_x000D_
}, 501);_x000D_
}, false);_x000D_
} else {_x000D_
document.attachEvent('oncontextmenu', function(e) {_x000D_
var posX = e.clientX;_x000D_
var posY = e.clientY;_x000D_
menu(posX, posY);_x000D_
e.preventDefault();_x000D_
});_x000D_
document.attachEvent('onclick', function(e) {_x000D_
i.opacity = "0";_x000D_
setTimeout(function() {_x000D_
i.visibility = "hidden";_x000D_
}, 501);_x000D_
});_x000D_
}_x000D_
_x000D_
function menu(x, y) {_x000D_
i.top = y + "px";_x000D_
i.left = x + "px";_x000D_
i.visibility = "visible";_x000D_
i.opacity = "1";_x000D_
}
_x000D_
body {_x000D_
background: white;_x000D_
font-family: sans-serif;_x000D_
color: #5e5e5e;_x000D_
}_x000D_
_x000D_
#menu {_x000D_
visibility: hidden;_x000D_
opacity: 0;_x000D_
position: fixed;_x000D_
background: #fff;_x000D_
color: #555;_x000D_
font-family: sans-serif;_x000D_
font-size: 11px;_x000D_
-webkit-transition: opacity .5s ease-in-out;_x000D_
-moz-transition: opacity .5s ease-in-out;_x000D_
-ms-transition: opacity .5s ease-in-out;_x000D_
-o-transition: opacity .5s ease-in-out;_x000D_
transition: opacity .5s ease-in-out;_x000D_
-webkit-box-shadow: 2px 2px 2px 0px rgba(143, 144, 145, 1);_x000D_
-moz-box-shadow: 2px 2px 2px 0px rgba(143, 144, 145, 1);_x000D_
box-shadow: 2px 2px 2px 0px rgba(143, 144, 145, 1);_x000D_
padding: 0px;_x000D_
border: 1px solid #C6C6C6;_x000D_
}_x000D_
_x000D_
#menu a {_x000D_
display: block;_x000D_
color: #555;_x000D_
text-decoration: none;_x000D_
padding: 6px 8px 6px 30px;_x000D_
width: 250px;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
#menu a img,_x000D_
#menu a i.fa {_x000D_
height: 20px;_x000D_
font-size: 17px;_x000D_
width: 20px;_x000D_
position: absolute;_x000D_
left: 5px;_x000D_
top: 2px;_x000D_
}_x000D_
_x000D_
#menu a span {_x000D_
color: #BCB1B3;_x000D_
float: right;_x000D_
}_x000D_
_x000D_
#menu a:hover {_x000D_
color: #fff;_x000D_
background: #3879D9;_x000D_
}_x000D_
_x000D_
#menu hr {_x000D_
border: 1px solid #EBEBEB;_x000D_
border-bottom: 0;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<h2>CSS3 and JAVASCRIPT custom menu.</h2>_x000D_
<em>Stephan Stanisic | Lisence free</em>_x000D_
<p>Right-click anywhere on this page to open the custom menu. Styled like the Google Chrome contextmenu. And yes, you can use <i class="fa fa-flag"></i>font-awesome</p>_x000D_
<p style="font-size: small">_x000D_
<b>Lisence</b>_x000D_
<br /> "THE PIZZA-WARE LICENSE" (Revision 42):_x000D_
<br /> You can do whatever you want with this stuff. If we meet some day, and you think this stuff is worth it, you can buy me a Pizza in return._x000D_
<br />_x000D_
<a style="font-size:xx-small" href="https://github.com/KLVN/UrbanDictionary_API#license">https://github.com/KLVN/UrbanDictionary_API#license</a>_x000D_
</p>_x000D_
<br />_x000D_
<br />_x000D_
<small>(The white body background is just because I hate the light blue editor background on the result on jsfiddle)</small>_x000D_
<div id="menu">_x000D_
<a href="#">_x000D_
<img src="http://puu.sh/nr60s/42df867bf3.png" /> AdBlock Plus <span>Ctrl + ?!</span>_x000D_
</a>_x000D_
<a href="#">_x000D_
<img src="http://puu.sh/nr5Z6/4360098fc1.png" /> SNTX <span>Ctrl + ?!</span>_x000D_
</a>_x000D_
<hr />_x000D_
<a href="#">_x000D_
<i class="fa fa-fort-awesome"></i> Fort Awesome <span>Ctrl + ?!</span>_x000D_
</a>_x000D_
<a href="#">_x000D_
<i class="fa fa-flag"></i> Font Awesome <span>Ctrl + ?!</span>_x000D_
</a>_x000D_
</div>
_x000D_
First, the error you're getting is due to where you're using the COUNT
function -- you can't use an aggregate (or group) function in the WHERE
clause.
Second, instead of using a subquery, simply join the table to itself:
SELECT a.pid
FROM Catalog as a LEFT JOIN Catalog as b USING( pid )
WHERE a.sid != b.sid
GROUP BY a.pid
Which I believe should return only rows where at least two rows exist with the same pid
but there is are at least 2 sid
s. To make sure you get back only one row per pid
I've applied a grouping clause.
Another example:
Suppose I created an immutable Rectangle class like this:
class Rectangle {
public:
Rectangle(int width, int height) : width_(width), height_(height) {}
int width() const { return width_; }
int height() const { return height_; }
private:
int width_;
int height_;
}
Now it's obvious that I've encapsulated width and height (access is somehow restricted), but I've not abstracted anything (okay, maybe I've ignored where the rectangle is located in the coordinates space, but this is a flaw of the example).
Good abstraction usually implies good encapsulation.
An example of good abstraction is a generic database connection class. Its public interface is database-agnostic, and is very simple, yet allows me to do what I want with the connection. And you see? There's also encapsulation there, because the class must have all the low-level handles and calls inside.
A naming service associates names with objects and finds objects based on their given names.(RMI registry is a good example of a naming service.) JNDI provides a common interface to many existing naming services, such as LDAP, DNS.
Without JNDI, the location or access information of remote resources would have to be hard-coded in applications or made available in a configuration. Maintaining this information is quite tedious and error prone.
try this C# code to drop your database
public static void DropDatabases(string dataBase) {
string sql = "ALTER DATABASE " + dataBase + "SET SINGLE_USER WITH ROLLBACK IMMEDIATE" ;
using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["DBRestore"].ConnectionString))
{
connection.Open();
using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(sql, connection))
{
command.CommandType = CommandType.Text;
command.CommandTimeout = 7200;
command.ExecuteNonQuery();
}
sql = "DROP DATABASE " + dataBase;
using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(sql, connection))
{
command.CommandType = CommandType.Text;
command.CommandTimeout = 7200;
command.ExecuteNonQuery();
}
}
}
For me works using &autoplay=1&mute=1
As others have pointed out, string is always nullable in C#. I suspect you are asking the question because you are not able to leave the middle name as null or blank? I suspect the problem is with your validation attributes, most likely the RegEx. I'm not able to fully parse RegEx in my head but I think your RegEx insists on the first character being present. I could be wrong - RegEx is hard. In any case, try commenting out your validation attributes and see if it works, then add them back in one at a time.
If you install a JDK and choose to install sources too, the src.zip contains the source of ALL the public Java classes. Most of these have pretty good javadoc.
You can create the state in the ParentComponent using useState
and pass down the setIsParentData
function as prop into the ChildComponent.
In the ChildComponent, update the data using the received function through prop to send the data back to ParentComponent.
I use this technique especially when my code in the ParentComponent is getting too long, therefore I will create child components from the ParentComponent. Typically, it will be only 1 level down and using useContext or redux seems overkill in order to share states between components.
ParentComponent.js
import React, { useState } from 'react';
import ChildComponent from './ChildComponent';
export function ParentComponent(){
const [isParentData, setIsParentData] = useState(True);
return (
<p>is this a parent data?: {isParentData}</p>
<ChildComponent toChild={isParentData} sendToParent={setIsParentData} />
);
}
ChildComponent.js
import React from 'react';
export function ChildComponent(props){
return (
<button onClick={() => {props.sendToParent(False)}}>Update</button>
<p>The state of isParentData is {props.toChild}</p>
);
};
You can use:
$redirectURL = curl_getinfo($ch,CURLINFO_REDIRECT_URL);
Like this http://jsfiddle.net/8ha9e/1/
Add colspan="2"
to the 3rd <th>
and then have 4 <td>
's in your second row.
<table border="1">
<tr>
<th scope="col">Header</th>
<th scope="col">Header</th>
<th scope="col" colspan="2">Header</th>
</tr>
<tr>
<th scope="row"> </th>
<td> </td>
<!-- The following two cells will appear under the same header -->
<td>Col 1</td>
<td>Col 2</td>
</tr>
</table>
always use with statement like ;WITH
then you'll never get this error. The WITH command required a ;
between it and any previous command, by always using ;WITH
you'll never have to remember to do this.
see WITH common_table_expression (Transact-SQL), from the section Guidelines for Creating and Using Common Table Expressions:
When a CTE is used in a statement that is part of a batch, the statement before it must be followed by a semicolon.
It is not supported in java as in other language for ex. Kotlin.
For compatibility with all browsers stick with .ico
.
.png is getting more and more support though as it is easier to create using multiple programs.
for .ico
<link rel="shortcut icon" href="http://example.com/myicon.ico" />
for .png, you need to specify the type
<link rel="icon" type="image/png" href="http://example.com/image.png" />
The total of 7 numbers in an array can be created as:
import java.util.*;
class Sum
{
public static void main(String arg[])
{
int a[]=new int[7];
int total=0;
Scanner n=new Scanner(System.in);
System.out.println("Enter the no. for total");
for(int i=0;i<=6;i++)
{
a[i]=n.nextInt();
total=total+a[i];
}
System.out.println("The total is :"+total);
}
}
For anyone still experiencing this, I found that images served on Amazon S3 do not work for WhatsApp mobile app (both Android and iOS, but Mac desktop app was fine). It's very possible that our AWS settings cause this, but I noticed the pattern in other sites as well (e.g. this one with an og:image
hitting a domain like https://s3.amazonaws.com
).
There were no problems on any other platform I tried, just WhatsApp mobile apps. As soon as I pointed my <meta property="og:image" content="https://some-non-aws-location" />
to another public URL like a Google Drive file (shared publicly of course), it worked fine.
I also tried committing the image in our repo, which is hosted and deployed on AWS with a custom domain, and that didn't work either. So AWS still seems to be the culprit. Hope this helps someone!
private int getRandomNumber(int min,int max) {
return (new Random()).nextInt((max - min) + 1) + min;
}
I think you should append .value in IF statement:
If Cells(i, "A").Value <> "Miami" And Cells(i, "D").Value <> "Florida" Then
Cells(i, "C").Value = "BA"
End IF
You failed to find an app that does this because it is not possible.
The documentation clearly states (here):
Note: You can play back the audio data only to the standard output device. Currently, that is the mobile device speaker or a Bluetooth headset. You cannot play sound files in the conversation audio during a call.
The reason behind this decision has probably something to do with security: there are several scenarios where this capability could be used for cons.
(the OP is highly similar to this, hence I'm basically giving the same answer)
Lets say you saved your software onto your desktop.
if you want to remove an entire folder like an uninstaller program you could use this.
cd C:\Users\User\Detsktop\
rd /s /q SOFTWARE
this will delete the entire folder called software and all of its files and subfolders
Make Sure You Delete The Correct Folder Cause This Does Not Have A Yes / No Option
So.. I had noticed in event viewer that this crash corresponded to a "System.IO.FileNotFoundException" error.
So I fired ProcMon and noticed that one of the program dlls was failing to load vcruntime140. So I simply installed vs15 redist and it worked.
brew reinstall php56-mcrypt --build-from-source
Do this—pass the --build-from-source
flag—for each module which needs to be compiled with the same version.
It may also require PHP options depending on your plugins. If so, brew reinstall php56 --with-thread-safety
To see all of the options for php[version] run brew options php56
(replacing 56 with your version)
it depends what sort of t-test you want to do (one sided or two sided dependent or independent) but it should be as simple as:
from scipy.stats import ttest_ind
cat1 = my_data[my_data['Category']=='cat1']
cat2 = my_data[my_data['Category']=='cat2']
ttest_ind(cat1['values'], cat2['values'])
>>> (1.4927289925706944, 0.16970867501294376)
it returns a tuple with the t-statistic & the p-value
see here for other t-tests http://docs.scipy.org/doc/scipy/reference/stats.html
Just change the indexes. i and j....in the loop, plus if you're dealing with Strings you have to use concat and initialize the variable to an empty Strong otherwise you'll get an exception.
String string="";
for (int i = 0; i<array.length; i++){
for (int j = 0; j<array[i].length; j++){
string = string.concat(array[j][i]);
}
}
System.out.println(string)
Console.Write(new string('=', 30) + "\n");
==============================
Please find below example to load image using JavaFX.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class LoadImage extends Application {
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Load Image");
StackPane sp = new StackPane();
Image img = new Image("javafx.jpg");
ImageView imgView = new ImageView(img);
sp.getChildren().add(imgView);
//Adding HBox to the scene
Scene scene = new Scene(sp);
primaryStage.setScene(scene);
primaryStage.show();
}
}
Create one source folder with name Image in your project and add your image to that folder otherwise you can directly load image from external URL like following.
Image img = new Image("http://mikecann.co.uk/wp-content/uploads/2009/12/javafx_logo_color_1.jpg");
If you're willing to "take this to the console", I'd recommend enca
. Unlike the rather simplistic mb_detect_encoding
, it uses "a mixture of parsing, statistical analysis, guessing and black magic to determine their encodings" (lol - see man page). However, you usually have to pass the language of the input file if you want to detect such country-specific encodings. (However, mb_detect_encoding
essentially has the same requirement, as the encoding would have to appear "in the right place" in the list of passed encodings for it to be detectable at all.)
enca
also came up here: How to find encoding of a file in Unix via script(s)
Ad hoc queries are those that are not already defined that are not needed on a regular basis, so they're not included in the typical set of reports or queries
Try the Apache Commons HttpClient library instead of trying to roll your own: http://hc.apache.org/httpclient-3.x/index.html
From their sample code:
HttpClient httpclient = new HttpClient();
httpclient.getHostConfiguration().setProxy("myproxyhost", 8080);
/* Optional if authentication is required.
httpclient.getState().setProxyCredentials("my-proxy-realm", " myproxyhost",
new UsernamePasswordCredentials("my-proxy-username", "my-proxy-password"));
*/
PostMethod post = new PostMethod("https://someurl");
NameValuePair[] data = {
new NameValuePair("user", "joe"),
new NameValuePair("password", "bloggs")
};
post.setRequestBody(data);
// execute method and handle any error responses.
// ...
InputStream in = post.getResponseBodyAsStream();
// handle response.
/* Example for a GET reqeust
GetMethod httpget = new GetMethod("https://someurl");
try {
httpclient.executeMethod(httpget);
System.out.println(httpget.getStatusLine());
} finally {
httpget.releaseConnection();
}
*/
Problems only surface when I am I trying to give the first loaded content an active state
Does this mean that you want to add a class to the first button?
$('.o-links').click(function(e) { // ... }).first().addClass('O_Nav_Current');
instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:
CSS:
.image-area { width: 100%; height: auto; display: none; } .image-area:first-of-type { display: block; }
JavaScript:
var $slides = $('.image-area'), $btns = $('a.o-links'); $btns.on('click', function (e) { var i = $btns.removeClass('O_Nav_Current').index(this); $(this).addClass('O_Nav_Current'); $slides.filter(':visible').fadeOut(1000, function () { $slides.eq(i).fadeIn(1000); }); e.preventDefault(); }).first().addClass('O_Nav_Current');
[+-]?(([1-9][0-9]*)|(0))([.,][0-9]+)?
[+-]?
- optional leading sign
(([1-9][0-9]*)|(0))
- integer without leading zero, including single zero
([.,][0-9]+)?
- optional fractional part
Another difference between declaring const and static readonly is in memory allocation.
A static field belongs to the type of an object rather than to an instance of that type. As a result, once the class is referenced for the first time, the static field would "live" in the memory for the rest of time, and the same instance of the static field would be referenced by all instances of the type.
On the other hand, a const field "belongs to an instance of the type.
If memory of deallocation is more important for you, prefer to use const. If speed, then use static readonly.
Well, you are using both frame.setSize()
and frame.pack()
.
You should use one of them at one time.
Using setSize()
you can give the size of frame you want but if you use pack()
, it will automatically change the size of the frames according to the size of components in it. It will not consider the size you have mentioned earlier.
Try removing frame.pack()
from your code or putting it before setting size and then run it.
The standard MIME type for ZIP files is application/zip
. The types for the files inside the ZIP does not matter for the MIME type.
As always, it ultimately depends on your server setup.
Had a similar question and had difficulty finding an answer. The following function allows you to paste an image with a transparency parameter over another image at a specific offset.
import Image
def trans_paste(fg_img,bg_img,alpha=1.0,box=(0,0)):
fg_img_trans = Image.new("RGBA",fg_img.size)
fg_img_trans = Image.blend(fg_img_trans,fg_img,alpha)
bg_img.paste(fg_img_trans,box,fg_img_trans)
return bg_img
bg_img = Image.open("bg.png")
fg_img = Image.open("fg.png")
p = trans_paste(fg_img,bg_img,.7,(250,100))
p.show()
Install it by running
python setup.py install
Better yet, you can download from github. Install git via apt-get install git
and then follow this steps:
git clone https://github.com/mwaskom/seaborn.git
cd seaborn
python setup.py install
Adding to @pranay-rana's list:
Third way is:
function passFromValue(){
var x = 15;
return x;
}
function passToValue() {
var y = passFromValue();
console.log(y);//15
}
passToValue();
Use the $_SERVER['HTTP_REFERER']
header, but bear in mind anybody can spoof it at anytime regardless of whether they clicked on a link.
You can check whether object
contains attribute by using hasattr
builtin method.
For an instance if your object is a
and you want to check for attribute stuff
>>> class a:
... stuff = "something"
...
>>> hasattr(a,'stuff')
True
>>> hasattr(a,'other_stuff')
False
The method signature itself is hasattr(object, name) -> bool
which mean if object
has attribute which is passed to second argument in hasattr
than it gives boolean True
or False
according to the presence of name
attribute in object.
If you have
<div>
<input type="checkbox" class="check-with-label" id="idinput" />
<label class="label-for-check" for="idinput">My Label</label>
</div>
you can do
.check-with-label:checked + .label-for-check {
font-weight: bold;
}
See this working. Note that this won't work in non-modern browsers.
Main issue is that you first need to set the location of your x and y ticks. Also, it helps to use the more object-oriented interface to matplotlib. Namely, interact with the axes
object directly.
import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABCD')
row_labels = list('WXYZ')
data = np.random.rand(4,4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data)
# put the major ticks at the middle of each cell, notice "reverse" use of dimension
ax.set_yticks(np.arange(data.shape[0])+0.5, minor=False)
ax.set_xticks(np.arange(data.shape[1])+0.5, minor=False)
ax.set_xticklabels(row_labels, minor=False)
ax.set_yticklabels(column_labels, minor=False)
plt.show()
Hope that helps.
display: inline-block
is your friend you just need all three parts of the construct - before, the "block", after - to be one, then you can vertically align them all to the middle:
(it looks like your picture anyway ;))
CSS:
p, div {
display: inline-block;
vertical-align: middle;
}
p, div {
display: inline !ie7; /* hack for IE7 and below */
}
table {
background: #000;
color: #fff;
font-size: 16px;
font-weight: bold; margin: 0 10px;
}
td {
padding: 5px;
text-align: center;
}
HTML:
<p>some text</p>
<div>
<table summary="">
<tr><td>A</td></tr>
<tr><td>B</td></tr>
<tr><td>C</td></tr>
<tr><td>D</td></tr>
</table>
</div>
<p>continues afterwards</p>
To all:
Note that the accepted answer has a bug in it relating to nullable types and the DataTable. The fix is available at the linked site (http://www.chinhdo.com/20090402/convert-list-to-datatable/) or in my modified code below:
///###############################################################
/// <summary>
/// Convert a List to a DataTable.
/// </summary>
/// <remarks>
/// Based on MIT-licensed code presented at http://www.chinhdo.com/20090402/convert-list-to-datatable/ as "ToDataTable"
/// <para/>Code modifications made by Nick Campbell.
/// <para/>Source code provided on this web site (chinhdo.com) is under the MIT license.
/// <para/>Copyright © 2010 Chinh Do
/// <para/>Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
/// <para/>The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
/// <para/>THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
/// <para/>(As per http://www.chinhdo.com/20080825/transactional-file-manager/)
/// </remarks>
/// <typeparam name="T">Type representing the type to convert.</typeparam>
/// <param name="l_oItems">List of requested type representing the values to convert.</param>
/// <returns></returns>
///###############################################################
/// <LastUpdated>February 15, 2010</LastUpdated>
public static DataTable ToDataTable<T>(List<T> l_oItems) {
DataTable oReturn = new DataTable(typeof(T).Name);
object[] a_oValues;
int i;
//#### Collect the a_oProperties for the passed T
PropertyInfo[] a_oProperties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
//#### Traverse each oProperty, .Add'ing each .Name/.BaseType into our oReturn value
//#### NOTE: The call to .BaseType is required as DataTables/DataSets do not support nullable types, so it's non-nullable counterpart Type is required in the .Column definition
foreach(PropertyInfo oProperty in a_oProperties) {
oReturn.Columns.Add(oProperty.Name, BaseType(oProperty.PropertyType));
}
//#### Traverse the l_oItems
foreach (T oItem in l_oItems) {
//#### Collect the a_oValues for this loop
a_oValues = new object[a_oProperties.Length];
//#### Traverse the a_oProperties, populating each a_oValues as we go
for (i = 0; i < a_oProperties.Length; i++) {
a_oValues[i] = a_oProperties[i].GetValue(oItem, null);
}
//#### .Add the .Row that represents the current a_oValues into our oReturn value
oReturn.Rows.Add(a_oValues);
}
//#### Return the above determined oReturn value to the caller
return oReturn;
}
///###############################################################
/// <summary>
/// Returns the underlying/base type of nullable types.
/// </summary>
/// <remarks>
/// Based on MIT-licensed code presented at http://www.chinhdo.com/20090402/convert-list-to-datatable/ as "GetCoreType"
/// <para/>Code modifications made by Nick Campbell.
/// <para/>Source code provided on this web site (chinhdo.com) is under the MIT license.
/// <para/>Copyright © 2010 Chinh Do
/// <para/>Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
/// <para/>The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
/// <para/>THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
/// <para/>(As per http://www.chinhdo.com/20080825/transactional-file-manager/)
/// </remarks>
/// <param name="oType">Type representing the type to query.</param>
/// <returns>Type representing the underlying/base type.</returns>
///###############################################################
/// <LastUpdated>February 15, 2010</LastUpdated>
public static Type BaseType(Type oType) {
//#### If the passed oType is valid, .IsValueType and is logicially nullable, .Get(its)UnderlyingType
if (oType != null && oType.IsValueType &&
oType.IsGenericType && oType.GetGenericTypeDefinition() == typeof(Nullable<>)
) {
return Nullable.GetUnderlyingType(oType);
}
//#### Else the passed oType was null or was not logicially nullable, so simply return the passed oType
else {
return oType;
}
}
Note that both of these example are NOT extension methods like the example above.
Lastly... apologies for my extensive/excessive comments (I had a anal/mean prof that beat it into me! ;)
I just made a class to handle this with Generics, so it can be used with all the object types that are serializable:
public class SerializableManager {
/**
* Saves a serializable object.
*
* @param context The application context.
* @param objectToSave The object to save.
* @param fileName The name of the file.
* @param <T> The type of the object.
*/
public static <T extends Serializable> void saveSerializable(Context context, T objectToSave, String fileName) {
try {
FileOutputStream fileOutputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(objectToSave);
objectOutputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Loads a serializable object.
*
* @param context The application context.
* @param fileName The filename.
* @param <T> The object type.
*
* @return the serializable object.
*/
public static<T extends Serializable> T readSerializable(Context context, String fileName) {
T objectToReturn = null;
try {
FileInputStream fileInputStream = context.openFileInput(fileName);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
objectToReturn = (T) objectInputStream.readObject();
objectInputStream.close();
fileInputStream.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return objectToReturn;
}
/**
* Removes a specified file.
*
* @param context The application context.
* @param filename The name of the file.
*/
public static void removeSerializable(Context context, String filename) {
context.deleteFile(filename);
}
}