I figured out myself.
cmp
calls ComputeBetasAndNuHat
which returns a list which has objective
as minusloglik
So I can change the function cmp
to get this value.
Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.
You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.
But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.
You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.
You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start()
. The headers will be sent automatically when any HTML is output.
Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.
Move the session_start()
to the top of your document :
<?php session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php'; // more PHP code here.
The addEdge is trusting more than the correction of the addNode method. It's also trusting that the addNode method has been invoked by other method. I'd recommend to include check if m is not null.
Font Squirrel has a wonderful web font generator.
I think you should find what you need here to generate OTF fonts and the needed CSS to use them. It will even support older IE versions.
Your model is @Messages
, change it to @message
.
To change it like you should use migration:
def change rename_table :old_table_name, :new_table_name end
Of course do not create that file by hand but use rails generator:
rails g migration ChangeMessagesToMessage
That will generate new file with proper timestamp in name in 'db
dir. Then run:
rake db:migrate
And your app should be fine since then.
self.tableView.tableHeaderView = segmentedControl;
If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.
Your variable declarations and their scope are correct. The problem you are facing is that the first AJAX request may take a little bit time to finish. Therefore, the second URL will be filled with the value of sID
before the its content has been set. You have to remember that AJAX request are normally asynchronous, i.e. the code execution goes on while the data is being fetched in the background.
You have to nest the requests:
$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE" , function(name){ obj = name; // sID is only now available! sID = obj.id; console.log(sID); });
name.id
is sufficient unless you really need the other variables outside the function.$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE" , function(name){ // We don't need sID or obj here - name.id is sufficient console.log(name.id); doSecondRequest(name.id); }); /// TODO Choose a better name function doSecondRequest(sID) { $.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.2/stats/by-summoner/" + sID + "/summary?api_key=API_KEY_HERE", function(stats){ console.log(stats); }); }
Hapy New Year :)
You had thead
in your selector, but there is no thead
in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr
class to the th
, not vice-versa (although your comment seems to contradict what you wrote up above).
$('tr th').each(function(index){ if($('tr td').eq(index).attr('class') != ''){ // get the class of the td var tdClass = $('tr td').eq(index).attr('class'); // add it to this th $(this).addClass(tdClass ); } });
First add an Enrty
and Category
class:
public class Entry { public string Id { get; set; } public string Title { get; set; } public string Updated { get; set; } public string Summary { get; set; } public string GPoint { get; set; } public string GElev { get; set; } public List<string> Categories { get; set; } } public class Category { public string Label { get; set; } public string Term { get; set; } }
Then use LINQ to XML
XDocument xDoc = XDocument.Load("path"); List<Entry> entries = (from x in xDoc.Descendants("entry") select new Entry() { Id = (string) x.Element("id"), Title = (string)x.Element("title"), Updated = (string)x.Element("updated"), Summary = (string)x.Element("summary"), GPoint = (string)x.Element("georss:point"), GElev = (string)x.Element("georss:elev"), Categories = (from c in x.Elements("category") select new Category { Label = (string)c.Attribute("label"), Term = (string)c.Attribute("term") }).ToList(); }).ToList();
Yes, it is possible:
git clone https://github.com/pitosalas/st3_packages Packages
You can specify the local root directory when using git clone.
<directory>
The name of a new directory to clone into.
The "humanish" part of the source repository is used if no directory is explicitly given (repo
for/path/to/repo.git
andfoo
forhost.xz:foo/.git
).
Cloning into an existing directory is only allowed if the directory is empty.
As Chris comments, you can then rename that top directory.
Git only cares about the .git
within said top folder, which you can get with various commands:
git rev-parse --show-toplevel git rev-parse --git-dir
In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.
EDIT
It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.
var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>"
I submitted a pull request to update this.
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');
You can use Jquery's on method and listen for the scroll
event.
maybe this will help you out:
or this page:
www.scala-lang.org/node/6372
In your test, you are comparing the two TestParent
beans, not the single TestedChild
bean.
Also, Spring proxies your @Configuration
class so that when you call one of the @Bean
annotated methods, it caches the result and always returns the same object on future calls.
See here:
Quite a few applications seem to implement Steganography on JPEG, so it's feasible:
http://www.jjtc.com/Steganography/toolmatrix.htm
Here's an article regarding a relevant algorithm (PM1) to get you started:
http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1
Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.
So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.
Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.
Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.
Do you have this:
use Cartalyst\Sentry\Sentry;
In your code?
Ok, but if this line is working for you:
$user = $this->sentry->register(array( 'username' => e($data['username']), 'email' => e($data['email']), 'password' => e($data['password']) ));
So you already have it instantiated and you can surely do:
$adminGroup = $this->sentry->findGroupById(5);
You are looking to see if a single value is in an array. Use in_array
.
However note that case is important, as are any leading or trailing spaces. Use var_dump
to find out the length of the strings too, and see if they fit.
Configuration
The styles and scripts options in your angular.json configuration now allow to reference a package directly:
before: "styles": ["../node_modules/bootstrap/dist/css/bootstrap.css"]
after: "styles": ["bootstrap/dist/css/bootstrap.css"]
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/ng6",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.app.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css","bootstrap/dist/css/bootstrap.min.css"
],
"scripts": [
"jquery/dist/jquery.min.js",
"bootstrap/dist/js/bootstrap.min.js"
]
},
Angular v6 Onwards
CLI projects in angular 6 onwards will be using angular.json
instead of .angular-cli.json
for build and project configuration.
Each CLI workspace has projects, each project has targets, and each target can have configurations.Docs
. {
"projects": {
"my-project-name": {
"projectType": "application",
"architect": {
"build": {
"configurations": {
"production": {},
"demo": {},
"staging": {},
}
},
"serve": {},
"extract-i18n": {},
"test": {},
}
},
"my-project-name-e2e": {}
},
}
OPTION-1
execute npm install bootstrap@4 jquery --save
The JavaScript parts of Bootstrap
are dependent on jQuery
. So you need the jQuery
JavaScript
library file too.
In your angular.json add the file paths to the styles and scripts array in under build
target
NOTE:
Before v6 the Angular CLI project configuration was stored in <PATH_TO_PROJECT>/.angular-cli.json.
As of v6 the location of the file changed to angular.json.
Since there is no longer a leading dot, the file is no longer hidden by default and is on the same level.
which also means that file paths in angular.json should not contain leading dots and slash
i.e you can provide an absolute path instead of a relative path
In .angular-cli.json
file Path was "../node_modules/"
In angular.json
it is "node_modules/"
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/ng6",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.app.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css","node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": ["node_modules/jquery/dist/jquery.min.js",
"node_modules/bootstrap/dist/js/bootstrap.min.js"]
},
OPTION 2
Add files from CDN (Content Delivery Network) to your project CDN LINK
Open file src/index.html and insert
the <link>
element at the end of the head section to include the Bootstrap CSS file
a <script>
element to include jQuery at the bottom of the body section
a <script>
element to include Popper.js at the bottom of the body section
a <script>
element to include the Bootstrap JavaScript file at the bottom of the body section
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Angular</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<app-root>Loading...</app-root>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>
OPTION 3
Execute npm install bootstrap
In src/styles.css
add the following line:
@import "~bootstrap/dist/css/bootstrap.css";
OPTION-4
ng-bootstrap It contains a set of native Angular directives based on Bootstrap’s markup and CSS. As a result, it's not dependent on jQuery or Bootstrap’s JavaScript
npm install --save @ng-bootstrap/ng-bootstrap
After Installation import it in your root module and register it in @NgModule
imports` array
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
@NgModule({
declarations: [AppComponent, ...],
imports: [NgbModule.forRoot(), ...],
bootstrap: [AppComponent]
})
NOTE
ng-bootstrap
requires Bootstrap's 4 css to be added in your project. you need to Install it explicitly via:
npm install bootstrap@4 --save
In your angular.json add the file paths to the styles array in under build
target
"styles": [
"src/styles.css",
"node_modules/bootstrap/dist/css/bootstrap.min.css"
],
If your are invoking fetch on a localhost server, use non-SSL unless you have a valid certificate for localhost. fetch will fail on an invalid or self signed certificate especially on localhost.
As of June 2020, adding role='button'
to any HTML tag would add cursor: "pointer"
to the element styling.
<span role="button">Non-button element button</span>
Official discussion on this feature - https://github.com/twbs/bootstrap/issues/23709
Documentation link - https://getbootstrap.com/docs/4.5/content/reboot/#pointers-on-buttons
I had same problems with Sublime Text.
I came up with following solution: I just edited
tsconfig.json
in the root of Angular workspace to include my freshly created application.
{
"files": [],
"references": [
{
"path": "./projects/client/tsconfig.app.json"
},
{
"path": "./projects/client/tsconfig.spec.json"
},
{
"path": "./projects/vehicle-market/tsconfig.app.json"
},
{
"path": "./projects/vehicle-market/tsconfig.spec.json"
},
{
"path": "./projects/mobile-de-lib/tsconfig.lib.json"
},
{
"path": "./projects/mobile-de-lib/tsconfig.spec.json"
}
]
}
Here's another way to plot the data, involves turning the date_time into an index, this might help you for future slicing
#convert column to datetime
trip_data['lpep_pickup_datetime'] = pd.to_datetime(trip_data['lpep_pickup_datetime'])
#turn the datetime to an index
trip_data.index = trip_data['lpep_pickup_datetime']
#Plot
trip_data['Trip_distance'].plot(kind='hist')
plt.show()
I do the following for my .NET Standard 2.0 projects.
Create a Directory.Build.props
file (e.g. in the root of your repo)
and move the properties to be shared from the .csproj
file to this file.
MSBuild will pick it up automatically and apply them to the autogenerated AssemblyInfo.cs
.
They also get applied to the nuget package when building one with dotnet pack
or via the UI in Visual Studio 2017.
See https://docs.microsoft.com/en-us/visualstudio/msbuild/customize-your-build
Example:
<Project>
<PropertyGroup>
<Company>Some company</Company>
<Copyright>Copyright © 2020</Copyright>
<AssemblyVersion>1.0.0.1</AssemblyVersion>
<FileVersion>1.0.0.1</FileVersion>
<Version>1.0.0.1</Version>
<!-- ... -->
</PropertyGroup>
</Project>
From Dockerfile reference:
The
ARG
instruction defines a variable that users can pass at build-time to the builder with the docker build command using the--build-arg <varname>=<value>
flag.The
ENV
instruction sets the environment variable<key>
to the value<value>
.
The environment variables set usingENV
will persist when a container is run from the resulting image.
So if you need build-time customization, ARG
is your best choice.
If you need run-time customization (to run the same image with different settings), ENV
is well-suited.
If I want to add let's say 20 (a random number) of extensions or any other feature that can be enable|disable
Given the number of combinations involved, using ENV
to set those features at runtime is best here.
But you can combine both by:
ARG
ARG
as an ENV
That is, with a Dockerfile including:
ARG var
ENV var=${var}
You can then either build an image with a specific var
value at build-time (docker build --build-arg var=xxx
), or run a container with a specific runtime value (docker run -e var=yyy
)
I was getting this same error while running RUN dotnet restore
in my Dockerfile
using docker-compose up
command in Windows 10
.
I have tried all the possible solution provided on the internet and was also keep an eye on this open issue. Finally, after spending more than 8 hours, by following the preceding steps, I was able to fix my issue.
Docker
from your systemInstall Docker
from this link. Below is the version of my Docker
Restart your system
Start Docker for Windows, search Docker
in the search bar in Windows. Make sure it is running.
You should also go to Services.msc
and make sure the services Docker Engine
and Docker for Windows Service
are running.
At last, you must check your Nuget.config file from C:\Users\{Username}\AppData\Roaming\NuGet
. For me, the content of that file was as below.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
</packageSources>
<packageRestore>
<add key="enabled" value="True" />
<add key="automatic" value="True" />
</packageRestore>
<bindingRedirects>
<add key="skip" value="False" />
</bindingRedirects>
<packageManagement>
<add key="format" value="0" />
<add key="disabled" value="False" />
</packageManagement>
</configuration>
Hope this helps.
If you are working a lot with graphs and ggplot, you might be tired to add the theme() each time. If you don't want to change the default theme as suggested earlier, you may find easier to create your own personal theme.
personal_theme = theme(plot.title =
element_text(hjust = 0.5))
Say you have multiple graphs, p1, p2 and p3, just add personal_theme to them.
p1 + personal_theme
p2 + personal_theme
p3 + personal_theme
dat <- data.frame(
time = factor(c("Lunch","Dinner"),
levels=c("Lunch","Dinner")),
total_bill = c(14.89, 17.23)
)
p1 = ggplot(data=dat, aes(x=time, y=total_bill,
fill=time)) +
geom_bar(colour="black", fill="#DD8888",
width=.8, stat="identity") +
guides(fill=FALSE) +
xlab("Time of day") + ylab("Total bill") +
ggtitle("Average bill for 2 people")
p1 + personal_theme
Get latest iOS-device-support-files (GitHub) (updated regularly). Download and copy iOS-device-support-files to:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport
The easiest possible fix for this issue if it is a AWS linux instance
sudo yum install java-1.8.0 -y
sudo yum remove java-1.7.0-openjdk
<ng-container>
to the rescueThe Angular
<ng-container>
is a grouping element that doesn't interfere with styles or layout because Angular doesn't put it in the DOM.(...)
The
<ng-container>
is a syntax element recognized by the Angular parser. It's not a directive, component, class, or interface. It's more like the curly braces in a JavaScript if-block:if (someCondition) { statement1; statement2; statement3; }
Without those braces, JavaScript would only execute the first statement when you intend to conditionally execute all of them as a single block. The
<ng-container>
satisfies a similar need in Angular templates.
According to this pull request :
<ng-container>
is a logical container that can be used to group nodes but is not rendered in the DOM tree as a node.
<ng-container>
is rendered as an HTML comment.
so this angular template :
<div>
<ng-container>foo</ng-container>
<div>
will produce this kind of output :
<div>
<!--template bindings={}-->foo
<div>
So ng-container
is useful when you want to conditionaly append a group of elements (ie using *ngIf="foo"
) in your application but don't want to wrap them with another element.
<div>
<ng-container *ngIf="true">
<h2>Title</h2>
<div>Content</div>
</ng-container>
</div>
will then produce :
<div>
<h2>Title</h2>
<div>Content</div>
</div>
You have to install
Python and add it to PATH on Windows
. After that you can try:
python `C:/pathToFolder/prog.py`
or go to the files directory and execute:
python prog.py
Here is the correct implementation using numpy (np.log()
is the natural logarithm)
import numpy as np
p = 100
r = 0.06 / 12
FV = 4000
n = np.log(1 + FV * r/ p) / np.log(1 + r)
print ("Number of periods = " + str(n))
Output:
Number of periods = 36.55539635919235
Most of the time problem is a spelling mistake in
<a [routerLink]="['/home']" routerLinkActive="active">Home</a>
Just check again for spelling.
In my case an iframe
with a bound src
was trying to get host/null ( when the value of the bound variable was null ).
Adding an *ngIf
to it helped.
I changed:
<iframe [src]="iframeSource"></iframe>
to
<iframe [src]="iframeSource" *ngIf="iframeSource"></iframe>
I know, question is a bit old, but since am here looks like people are still looking for solutions.
I'll suggest you to use react-moment
link,
react-moment
comes with handy JSX
tags which reduce a lot of work. Like in your case :-
import React from 'react';
import Moment from 'react-moment';
exports default class MyComponent extends React.Component {
render() {
<Moment format="YYYY/MM/DD">{this.props.dateToFormat}</Moment>
}
}
It seems to be (as of 2018.03) in code-insider. A directive has been introduced called python.venvFolders:
"python.venvFolders": [
"envs",
".pyenv",
".direnv"
],
All you need is to add your virtualenv folder name.
In the case of my Cordova-project, uninstalling and installing cordova -g fixed the problem for me.
npm uninstall -g cordova
npm install -g cordova
Go to Phone Settings --> Developer Options --> Simulate Secondary Displays
and turn it to None
.
If you don't see Developer Options
in the settings menu
(it should be at the bottom, go Settings ==> About phone
and tap on the Build number
a lot of times)
In my case none of the answers helped. Finally it turned out, that changing to a 64 bit version of PHP (M$ Windows) fixed the problem immediately. I did not change any settings - it just worked.
What you are trying to do is simply not possible from an app (at least not on a non-rooted/non-modified device). The message "NFC tag type not supported" is displayed by the Android system (or more specifically the NFC system service) before and instead of dispatching the tag to your app. This means that the NFC system service filters MIFARE Classic tags and never notifies any app about them. Consequently, your app can't detect MIFARE Classic tags or circumvent that popup message.
On a rooted device, you may be able to bypass the message using either
the CSC (Consumer Software Customization) feature configuration files on the system partition (see /system/csc/. The NFC system service disables the popup and dispatches MIFARE Classic tags to apps if the CSC feature <CscFeature_NFC_EnableSecurityPromptPopup>
is set to any value but "mifareclassic" or "all". For instance, you could use:
<CscFeature_NFC_EnableSecurityPromptPopup>NONE</CscFeature_NFC_EnableSecurityPromptPopup>
You could add this entry to, for instance, the file "/system/csc/others.xml" (within the section <FeatureSet> ... </FeatureSet>
that already exists in that file).
Since, you asked for the Galaxy S6 (the question that you linked) as well: I have tested this method on the S4 when it came out. I have not verified if this still works in the latest firmware or on other devices (e.g. the S6).
This is pure guessing, but according to this (link no longer available), it seems that some apps (e.g. NXP TagInfo) are capable of detecting MIFARE Classic tags on affected Samsung devices since Android 4.4. This might mean that foreground apps are capable of bypassing that popup using the reader-mode API (see NfcAdapter.enableReaderMode
) possibly in combination with NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK
.
As noted the Ajax and effects modules have been excluded from jQuery slim the size difference as of 3.3.1 for the minified version unzipped is 85k vs 69k (16k saving for slim) or 30vs24 for zipped, it is important to note that bootstrap 4 uses the slim jQuery so if someone wants the full version they need to call that instead
If you're running Angular 2 through ASP.NET Core 1 in Visual Studio 2015, you might find this solution from Jürgen Gutsch helpful. He describes it in a blog post. It was the best solution for me. Place the C# code provided below in your Startup.cs public void Configure() just before app.UseStaticFiles();
app.Use( async ( context, next ) => {
await next();
if( context.Response.StatusCode == 404 && !Path.HasExtension( context.Request.Path.Value ) ) {
context.Request.Path = "/index.html";
await next();
}
});
Abstract:
The reason why you are getting this error
message is because you are trying to call a method on an int
type of a variable. This would work if would have called len()
function on a list
type of a variable. Let's examin the two cases:
Fail:
num = 10
print(len(num))
The above will produce an error similar to yours due to calling len()
function on an int
type of a variable;
Success:
data = [0, 4, 8, 9, 12]
print(len(data))
The above will work since you are calling a function on a list
type of a variable;
I also go through same problem and do this simple work just go to res->values->style.xml and change
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
to
<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">
Another late answer, but I was playing with this and came up with a general purpose Sass solution that I found useful and many others might as well. To give an overview, this introduces new classes that can modify the column count of a .card-columns
element in very similar ways to columns with .col-4
or .col-lg-3
:
@import "bootstrap";
$card-column-counts: 1, 2, 3, 4, 5;
.card-columns {
@each $column-count in $card-column-counts {
&.card-columns-#{$column-count} {
column-count: $column-count;
}
}
@each $breakpoint in map-keys($grid-breakpoints) {
@include media-breakpoint-up($breakpoint) {
$infix: breakpoint-infix($breakpoint, $grid-breakpoints);
@each $column-count in $card-column-counts {
&.card-columns#{$infix}-#{$column-count} {
column-count: $column-count;
}
}
}
}
}
The end result of this is if you have the following:
<div class="card-columns card-columns-2 card-columns-md-3 card-columns-xl-4">
...
</div>
Then you would have 2 columns by default, 3 for medium devices and up and 4 for xl devices and up. Additionally if you change your grid breakpoints this will automatically support those, and the $card-column-counts
can be overridden to change the allowed numbers of columns.
You can also use Microsoft Visual Studio compiler instead of Cygwin or MinGW in Windows environment as the compiler for CLion.
Just go to find Actions in Help and type "Registry" without " and enable CLion.enable.msvc Now configure toolchain with Microsoft Visual Studio Compiler. (You need to download it if not already downloaded)
follow this link for more details: https://www.jetbrains.com/help/clion/quick-tutorial-on-configuring-clion-on-windows.html
git clone
to clone your repository into a folder (say work). You should see a new subfolder, work/.git
.PS: Blow away the temporary folder.
I saw it's solved, but I still want to share a solution which worked for me.
.env file:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=[your database name]
DB_USERNAME=[your MySQL username]
DB_PASSWORD=[your MySQL password]
MySQL admin:
SELECT user, host FROM mysql.user
Console:
php artisan cache:clear
php artisan config:cache
Now it works for me.
if you have a data frame and want to remove all duplicates -- with reference to duplicates in a specific column (called 'colName'):
count before dedupe:
df.count()
do the de-dupe (convert the column you are de-duping to string type):
from pyspark.sql.functions import col
df = df.withColumn('colName',col('colName').cast('string'))
df.drop_duplicates(subset=['colName']).count()
can use a sorted groupby to check to see that duplicates have been removed:
df.groupBy('colName').count().toPandas().set_index("count").sort_index(ascending=False)
Try with below logic
driver.get("http://www.labmultis.info/jpecka.portal-exdrazby/index.php?c1=2&a=s&aa=&ta=1");
List<WebElement> allElements=driver.findElements(By.cssSelector(".list.list-categories li"));
for(WebElement ele :allElements) {
System.out.println("Name + Number===>"+ele.getText());
String s=ele.getText();
s=s.substring(s.indexOf("(")+1, s.indexOf(")"));
System.out.println("Number==>"+s);
}
====Output======
Name + Number===>Vše (950)
Number==>950
Name + Number===>Byty (181)
Number==>181
Name + Number===>Domy (512)
Number==>512
Name + Number===>Pozemky (172)
Number==>172
Name + Number===>Chaty (28)
Number==>28
Name + Number===>Zemedelské objekty (5)
Number==>5
Name + Number===>Komercní objekty (30)
Number==>30
Name + Number===>Ostatní (22)
Number==>22
for AndroidX use like
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/ic_add" />
90% of the laravel ajax internal server error is due to missing CSRF token. other reasons can inlucde:
You can read further about this in details here: https://abbasharoon.me/how-to-fix-laravel-ajax-500-internal-server-error/
unfortunately, there is not option to put number in whatsapp protocol. only is possible with parameter ABID (address Book ID), but you must have this contact with specific name to do this. check WhatsApp Documentation
import requests
image_file_descriptor = open('test.jpg', 'rb')
# Requests makes it simple to upload Multipart-encoded files
files = {'media': image_file_descriptor}
url = '...'
requests.post(url, files=files)
image_file_descriptor.close()
Don't forget to close the descriptor, it prevents bugs: Is explicitly closing files important?
Check this has everything you need
http://www.html5rocks.com/en/mobile/fullscreen/
The Chrome team has recently implemented a feature that tells the browser to launch the page fullscreen when the user has added it to the home screen. It is similar to the iOS Safari model.
<meta name="mobile-web-app-capable" content="yes">
When I tried to make ObjectMapper primary in spring boot 2.0.6 I got errors So I modified the one that spring boot created for me
Also see https://stackoverflow.com/a/48519868/255139
@Lazy
@Autowired
ObjectMapper mapper;
@PostConstruct
public ObjectMapper configureMapper() {
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, true);
mapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
SimpleModule module = new SimpleModule();
module.addDeserializer(LocalDate.class, new LocalDateDeserializer());
module.addSerializer(LocalDate.class, new LocalDateSerializer());
mapper.registerModule(module);
return mapper;
}
You need to create a header with a proper formatted User agent String, it server to communicate client-server.
You can check your own user agent Here.
Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0
Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:42.0) Gecko/20100101 Firefox/42.0
I found this module very simple to use, in one line of code it randomly generates a User agent string.
from user_agent import generate_user_agent, generate_navigator
from pprint import pprint
print(generate_user_agent())
# 'Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.3; Win64; x64)'
print(generate_user_agent(os=('mac', 'linux')))
# 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:36.0) Gecko/20100101 Firefox/36.0'
pprint(generate_navigator())
# {'app_code_name': 'Mozilla',
# 'app_name': 'Netscape',
# 'appversion': '5.0',
# 'name': 'firefox',
# 'os': 'linux',
# 'oscpu': 'Linux i686 on x86_64',
# 'platform': 'Linux i686 on x86_64',
# 'user_agent': 'Mozilla/5.0 (X11; Ubuntu; Linux i686 on x86_64; rv:41.0) Gecko/20100101 Firefox/41.0',
# 'version': '41.0'}
pprint(generate_navigator_js())
# {'appCodeName': 'Mozilla',
# 'appName': 'Netscape',
# 'appVersion': '38.0',
# 'platform': 'MacIntel',
# 'userAgent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:38.0) Gecko/20100101 Firefox/38.0'}
As I felt similarly confused with .transform
operation vs. .apply
I found a few answers shedding some light on the issue. This answer for example was very helpful.
My takeout so far is that .transform
will work (or deal) with Series
(columns) in isolation from each other. What this means is that in your last two calls:
df.groupby('A').transform(lambda x: (x['C'] - x['D']))
df.groupby('A').transform(lambda x: (x['C'] - x['D']).mean())
You asked .transform
to take values from two columns and 'it' actually does not 'see' both of them at the same time (so to speak). transform
will look at the dataframe columns one by one and return back a series (or group of series) 'made' of scalars which are repeated len(input_column)
times.
So this scalar, that should be used by .transform
to make the Series
is a result of some reduction function applied on an input Series
(and only on ONE series/column at a time).
Consider this example (on your dataframe):
zscore = lambda x: (x - x.mean()) / x.std() # Note that it does not reference anything outside of 'x' and for transform 'x' is one column.
df.groupby('A').transform(zscore)
will yield:
C D
0 0.989 0.128
1 -0.478 0.489
2 0.889 -0.589
3 -0.671 -1.150
4 0.034 -0.285
5 1.149 0.662
6 -1.404 -0.907
7 -0.509 1.653
Which is exactly the same as if you would use it on only on one column at a time:
df.groupby('A')['C'].transform(zscore)
yielding:
0 0.989
1 -0.478
2 0.889
3 -0.671
4 0.034
5 1.149
6 -1.404
7 -0.509
Note that .apply
in the last example (df.groupby('A')['C'].apply(zscore)
) would work in exactly the same way, but it would fail if you tried using it on a dataframe:
df.groupby('A').apply(zscore)
gives error:
ValueError: operands could not be broadcast together with shapes (6,) (2,)
So where else is .transform
useful? The simplest case is trying to assign results of reduction function back to original dataframe.
df['sum_C'] = df.groupby('A')['C'].transform(sum)
df.sort('A') # to clearly see the scalar ('sum') applies to the whole column of the group
yielding:
A B C D sum_C
1 bar one 1.998 0.593 3.973
3 bar three 1.287 -0.639 3.973
5 bar two 0.687 -1.027 3.973
4 foo two 0.205 1.274 4.373
2 foo two 0.128 0.924 4.373
6 foo one 2.113 -0.516 4.373
7 foo three 0.657 -1.179 4.373
0 foo one 1.270 0.201 4.373
Trying the same with .apply
would give NaNs
in sum_C
.
Because .apply
would return a reduced Series
, which it does not know how to broadcast back:
df.groupby('A')['C'].apply(sum)
giving:
A
bar 3.973
foo 4.373
There are also cases when .transform
is used to filter the data:
df[df.groupby(['B'])['D'].transform(sum) < -1]
A B C D
3 bar three 1.287 -0.639
7 foo three 0.657 -1.179
I hope this adds a bit more clarity.
It seems that the version "20140702" of the example link in the question was the final version, because I downloaded this file on the 12th November 2014, i.e. the version from the 2nd of July 2014 was still the latest version on 12th of November. When I try manually all the possible versions/dates between today in this date, then I always get a page with error code "404" (file not found), which indicates that no new version was released since the 12th of November.
Solving this problem is easy:
net stop W3SVC
and Enter.You can now click in WAMPP and restart all services. Open your browser and navigate to "localhost".
If you need to start W3SVC again,
net start W3SVC
and Enter.Hi curious you can validate your google recaptcha at client side also 100% work for me to verify your google recaptcha just see below code
This code at the html body:
<div class="g-recaptcha" id="rcaptcha" style="margin-left: 90px;" data-sitekey="my_key"></div>
<span id="captcha" style="margin-left:100px;color:red" />
This code put at head section on call get_action(this)
method form button:
function get_action(form) {
var v = grecaptcha.getResponse();
if(v.length == 0)
{
document.getElementById('captcha').innerHTML="You can't leave Captcha Code empty";
return false;
}
if(v.length != 0)
{
document.getElementById('captcha').innerHTML="Captcha completed";
return true;
}
}
If you are using node (React / Redux / Universal JS) you can install npm i -S jwt-autorefresh
.
This library schedules refresh of JWT tokens at a user calculated number of seconds prior to the access token expiring (based on the exp claim encoded in the token). It has an extensive test suite and checks for quite a few conditions to ensure any strange activity is accompanied by a descriptive message regarding misconfigurations from your environment.
Full example implementation
import autorefresh from 'jwt-autorefresh'
/** Events in your app that are triggered when your user becomes authorized or deauthorized. */
import { onAuthorize, onDeauthorize } from './events'
/** Your refresh token mechanism, returning a promise that resolves to the new access tokenFunction (library does not care about your method of persisting tokens) */
const refresh = () => {
const init = { method: 'POST'
, headers: { 'Content-Type': `application/x-www-form-urlencoded` }
, body: `refresh_token=${localStorage.refresh_token}&grant_type=refresh_token`
}
return fetch('/oauth/token', init)
.then(res => res.json())
.then(({ token_type, access_token, expires_in, refresh_token }) => {
localStorage.access_token = access_token
localStorage.refresh_token = refresh_token
return access_token
})
}
/** You supply a leadSeconds number or function that generates a number of seconds that the refresh should occur prior to the access token expiring */
const leadSeconds = () => {
/** Generate random additional seconds (up to 30 in this case) to append to the lead time to ensure multiple clients dont schedule simultaneous refresh */
const jitter = Math.floor(Math.random() * 30)
/** Schedule autorefresh to occur 60 to 90 seconds prior to token expiration */
return 60 + jitter
}
let start = autorefresh({ refresh, leadSeconds })
let cancel = () => {}
onAuthorize(access_token => {
cancel()
cancel = start(access_token)
})
onDeauthorize(() => cancel())
disclaimer: I am the maintainer
You say you want to delete any column with the title "Percent Margin of Error" so let's try to make this dynamic instead of naming columns directly.
Sub deleteCol()
On Error Resume Next
Dim wbCurrent As Workbook
Dim wsCurrent As Worksheet
Dim nLastCol, i As Integer
Set wbCurrent = ActiveWorkbook
Set wsCurrent = wbCurrent.ActiveSheet
'This next variable will get the column number of the very last column that has data in it, so we can use it in a loop later
nLastCol = wsCurrent.Cells.Find("*", LookIn:=xlValues, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
'This loop will go through each column header and delete the column if the header contains "Percent Margin of Error"
For i = nLastCol To 1 Step -1
If InStr(1, wsCurrent.Cells(1, i).Value, "Percent Margin of Error", vbTextCompare) > 0 Then
wsCurrent.Columns(i).Delete Shift:=xlShiftToLeft
End If
Next i
End Sub
With this you won't need to worry about where you data is pasted/imported to, as long as the column headers are in the first row.
EDIT: And if your headers aren't in the first row, it would be a really simple change. In this part of the code: If InStr(1, wsCurrent.Cells(1, i).Value, "Percent Margin of Error", vbTextCompare)
change the "1" in Cells(1, i)
to whatever row your headers are in.
EDIT 2: Changed the For
section of the code to account for completely empty columns.
You can just place your header and your RecyclerView in a NestedScrollView:
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<include
layout="@layout/your_header"/>
<android.support.v7.widget.RecyclerView
android:id="@+id/list_recylclerview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
In order for scrolling to work correctly, you need to disable nested scrolling on your RecyclerView:
myRecyclerView.setNestedScrollingEnabled(false);
You can have many java versions in your system.
I think you should add the java 8 in yours JREs installed or edit.
Take a look my screen:
If you click in edit (check your java 8 path):
As for your regexp I guess it should be
^\+{0,2}([\-\. ])?(\(?\d{0,3}\))?([\-\. ])?\(?\d{0,3}\)?([\-\. ])?\d{3}([\-\. ])?\d{4}
But in general the presumption is not correct because one might enter something like ++44 20 1234 56789 or +44 (0) 1234 567890 it is better to do something like this
var phone = document.forms["myForm"]["phone"].value;
var phoneNum = phone.replace(/[^\d]/g, '');
if(phoneNum.length > 6 && phoneNum.length < 11) { return true; }
this will assure that entered value has 7 to 10 figures nevertheless what the formatting is. But you have to think about max length for number might be more than 10 as in the sample above.
Instead of changing the COM port in Device manager, if you're using the Arduino software, I had to set the port in Tools > Port menu.
As of January 2018 the url is https://www.twitch.tv/username/dashboard/settings/streamkey
Clear your whatsapp data and cache (or use another whatsapp) !
Android Phone : Go to SETTINGS > APPS > Application List > WhatsApp > Storage and Clear Data.
Be careful ! Backup your messages before this action.
Then the result : before and after clearing data and cache WhatsApp
Cause you need to add jQuery library to your file:
jQuery UI is just an addon to jQuery which means that
first you need to include the jQuery library → and then the UI.
<script src="path/to/your/jquery.min.js"></script>
<script src="path/to/your/jquery.ui.min.js"></script>
If you are having trouble with --coverage not working it may also be due to having coverageReporters enabled without 'text' or 'text-summary' being added. From the docs: "Note: Setting this option overwrites the default values. Add "text" or "text-summary" to see a coverage summary in the console output." Source
A simple question should be followed by a short, simple and clear answer.
When we are getting a value of the property it fires its get{}
part.
When we are setting a value to the property it fires its set{}
part.
PS. When setting a value to the property, SWIFT automatically creates a constant named "newValue" = a value we are setting. After a constant "newValue" becomes accessible in the property's set{}
part.
Example:
var A:Int = 0
var B:Int = 0
var C:Int {
get {return 1}
set {print("Recived new value", newValue, " and stored into 'B' ")
B = newValue
}
}
//When we are getting a value of C it fires get{} part of C property
A = C
A //Now A = 1
//When we are setting a value to C it fires set{} part of C property
C = 2
B //Now B = 2
I found @naota's solution useful, and extended it to use dates as well
//taken from StackOverflow:
//https://stackoverflow.com/questions/3880615/how-can-i-determine-whether-a-given-string-represents-a-date
function isDate(val) {
var d = new Date(val);
return !isNaN(d.valueOf());
}
var getVal = function(elm, n){
var v = $(elm).children('td').eq(n).text().toUpperCase();
if($.isNumeric(v)){
v = parseFloat(v,10);
return v;
}
if (isDate(v)) {
v = new Date(v);
return v;
}
return v;
}
In my case, the file containing JSON string had BOM. Once I removed BOM the problem was solved.
Case matters
I manually added a submodule :k3b-geohelper
to the
settings.gradle
file
include ':app', ':k3b-geohelper'
and everthing works fine on my mswindows build system
When i pushed the update to github the fdroid build system failed with
Cannot evaluate module k3b-geohelper : Configuration with name 'default' not found
The final solution was that the submodule folder was named k3b-geoHelper
not k3b-geohelper
.
Under MSWindows case doesn-t matter but on linux system it does
You can download IE Driver (both 32 and 64-bit) from Selenium official site: http://docs.seleniumhq.org/download/
IE Driver is also available in the following site:
You alread removed the active class from all the tabs but then you add the active class, again, to all the tabs. You should only add the active class to the currently selected tab like so http://jsfiddle.net/QFnRa/
$(".tab").removeClass("active");
$(this).addClass("active");
Everybody getting a headache from this error: Make absolutely sure all your projetcs have a reference to the same Entity Framework assembly.
Short story long:
My model and my application were in different assemblies. These assemblies were referencing a different version of Entity framework. I guess that the two versions generated a different id for the same modell. So when my application ran the id of the model didn't match the one of the latest migration in __MigrationHistory. After updating all references to the latest EF release the error never showed up again.
Only SVG with path information. you can't do that to the image.. as the path you can change stroke and fill information and you are done. like Illustrator
so: via CSS you can overwrite path fill
value
path { fill: orange; }
but if you want more flexible way as you want to change it with a text when having some hovering effect going on.. use
path { fill: currentcolor; }
body {_x000D_
background: #ddd;_x000D_
text-align: center;_x000D_
padding-top: 2em;_x000D_
}_x000D_
_x000D_
.parent {_x000D_
width: 320px;_x000D_
height: 50px;_x000D_
display: block;_x000D_
transition: all 0.3s;_x000D_
cursor: pointer;_x000D_
padding: 12px;_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
/*** desired colors for children ***/_x000D_
.parent{_x000D_
color: #000;_x000D_
background: #def;_x000D_
}_x000D_
.parent:hover{_x000D_
color: #fff;_x000D_
background: #85c1fc;_x000D_
}_x000D_
_x000D_
.parent span{_x000D_
font-size: 18px;_x000D_
margin-right: 8px;_x000D_
font-weight: bold;_x000D_
font-family: 'Helvetica';_x000D_
line-height: 26px;_x000D_
vertical-align: top;_x000D_
}_x000D_
.parent svg{_x000D_
max-height: 26px;_x000D_
width: auto;_x000D_
display: inline;_x000D_
}_x000D_
_x000D_
/**** magic trick *****/_x000D_
.parent svg path{_x000D_
fill: currentcolor;_x000D_
}
_x000D_
<div class='parent'>_x000D_
<span>TEXT WITH SVG</span>_x000D_
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="128" height="128" viewBox="0 0 32 32">_x000D_
<path d="M30.148 5.588c-2.934-3.42-7.288-5.588-12.148-5.588-8.837 0-16 7.163-16 16s7.163 16 16 16c4.86 0 9.213-2.167 12.148-5.588l-10.148-10.412 10.148-10.412zM22 3.769c1.232 0 2.231 0.999 2.231 2.231s-0.999 2.231-2.231 2.231-2.231-0.999-2.231-2.231c0-1.232 0.999-2.231 2.231-2.231z"></path>_x000D_
</svg>_x000D_
</div>
_x000D_
Postman is a good solution and so is php fiddle. However to avoid putting in the GCM URL and the header information every time, you can also use this nifty GCM Notification Test Tool
.navbar-nav {
float: left;
margin: 0;
margin-left: 40%;
}
.navbar-nav.navbar-right:last-child {
margin-right: -15px;
margin-left: 0;
}
Since You Have used the float
property we don't have many options except to adjust it manually.
Here's a fixed version of it: http://play.golang.org/p/w2ZcOzGHKR
The biggest fix that was needed is when Unmarshalling an array, that property needs to be an array/slice in the struct as well.
For example:
{ "things": ["a", "b", "c"] }
Would Unmarshal into a:
type Item struct {
Things []string
}
And not into:
type Item struct {
Things string
}
The other thing to watch out for when Unmarshaling is that the types line up exactly. It will fail when Unmarshalling a JSON string representation of a number into an int
or float
field -- "1"
needs to Unmarshal into a string
, not into an int
like we saw with ShippingAdditionalCost int
$pwd /usr/lib/jvm/jre1.8.0_25/bin
./jcontrol
as follow,
java Control Panel --> Security --> Edit Site list ,
then apply, and ok.
A (partial) practical work-around is to put things into a throw-away function.
Pasting
x = 1
x += 1
print(x)
results in
>>> x = 1
x += 1
print(x)
File "<stdin>", line 1
x += 1
print(x)
^
SyntaxError: multiple statements found while compiling a single statement
>>>
However, pasting
def abc():
x = 1
x += 1
print(x)
works:
>>> def abc():
x = 1
x += 1
print(x)
>>> abc()
2
>>>
Of course, this is OK for a quick one-off, won't work for everything you might want to do, etc. But then, going to ipython
/ jupyter qtconsole
is probably the next simplest option.
HTML5 does not support .mkv / Matroska files but you can use this code...
<video>
<source src="video.mkv" type="video/mp4">
</video>
But it depends on the browser as to whether it will play or not. This method is known to work with Chrome.
There's a workaround for those who want to use Chrome. This extension allows you to request any site with AJAX from any source, since it adds 'Access-Control-Allow-Origin: *'
header to the response.
As an alternative, you can add this argument to your Chrome launcher: --disable-web-security
. Note that I'd only use this for development purposes, not for normal "web surfing". For reference see Run Chromium with Flags.
As a final note, by installing the extension mentioned on the first paragraph, you can easily enable/disable CORS.
All of these answers appear to be incomplete and/or kludges. Looking at the RestTemplate interface, it sure looks like it is intended to have a ClientHttpRequestFactory
injected into it, and then that requestFactory will be used to create the request, including any customizations of headers, body, and request params.
You either need a universal ClientHttpRequestFactory
to inject into a single shared RestTemplate
or else you need to get a new template instance via new RestTemplate(myHttpRequestFactory)
.
Unfortunately, it looks somewhat non-trivial to create such a factory, even when you just want to set a single Authorization header, which is pretty frustrating considering what a common requirement that likely is, but at least it allows easy use if, for example, your Authorization header can be created from data contained in a Spring-Security Authorization
object, then you can create a factory that sets the outgoing AuthorizationHeader on every request by doing SecurityContextHolder.getContext().getAuthorization()
and then populating the header, with null checks as appropriate. Now all outbound rest calls made with that RestTemplate will have the correct Authorization header.
Without more emphasis placed on the HttpClientFactory mechanism, providing simple-to-overload base classes for common cases like adding a single header to requests, most of the nice convenience methods of RestTemplate
end up being a waste of time, since they can only rarely be used.
I'd like to see something simple like this made available
@Configuration
public class MyConfig {
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate(new AbstractHeaderRewritingHttpClientFactory() {
@Override
public HttpHeaders modifyHeaders(HttpHeaders headers) {
headers.addHeader("Authorization", computeAuthString());
return headers;
}
public String computeAuthString() {
// do something better than this, but you get the idea
return SecurityContextHolder.getContext().getAuthorization().getCredential();
}
});
}
}
At the moment, the interface of the available ClientHttpRequestFactory's are harder to interact with than that. Even better would be an abstract wrapper for existing factory implementations which makes them look like a simpler object like AbstractHeaderRewritingRequestFactory for the purposes of replacing just that one piece of functionality. Right now, they are very general purpose such that even writing those wrappers is a complex piece of research.
I think saving dicts in a list is not an ideal solution here proposed by @falsetru.
Better way is, iterating through dicts and saving them to .json by adding a new line.
our 2 dictionaries are
d1 = {'a':1}
d2 = {'b':2}
you can write them to .json
import json
with open('sample.json','a') as sample:
for dict in [d1,d2]:
sample.write('{}\n'.format(json.dumps(dict)))
and you can read json file without any issues
with open('sample.json','r') as sample:
for line in sample:
line = json.loads(line.strip())
simple and efficient
I had the same problem. You should type your Angular js code outside of any function like this:
$( document ).ready(function() {});
With JRE 8 on XP there is another way - to use MSI to deploy package.
or (silent way, usable in batch file etc..)
for %%I in ("*.msi") do if exist "%%I" msiexec.exe /i %%I /qn EULA=0 SKIPLICENSE=1 PROG=0 ENDDIALOG=0
I used the Visual Studio 2008 Uninstall tool and it worked fine for me.
You can use this tool to uninstall Visual Studio 2008 official release and Visual Studio 2008 Release candidate (Only English version).
Found here, on the MSDN Forum: MSDN forum topic.
I found this answer here
Be sure you run the tool with admin-rights.
your log files shows it is stopping on error "0x8004C000"
From MS Website (http://social.technet.microsoft.com/wiki/contents/articles/15716.visual-studio-2012-and-the-error-code-2147205120.aspx):
Setup Status
Block
Restart not required
0x80044000 [-2147205120]
Restart required
0x8004C000 [-2147172352]
Description
If the only block to be reported is “Reboot Pending,” the returned value is the Incomplete-Reboot Required value (0x80048bc7).
.row {
letter-spacing: -.31em;
word-spacing: -.43em;
}
.col-md-4 {
float: none;
display: inline-block;
vertical-align: middle;
}
Note: .col-md-4 could be any grid column, its just an example here.
U can just add, timezone difference to unix timestamp. Example for Moscow (UTC+3)
echo date('d.m.Y H:i:s', time() + 3 * 60 * 60);
The WebRTC API can be used to retrieve the client's local IP.
However the browser may not support it, or the client may have disabled it for security reasons. In any case, one should not rely on this "hack" on the long term as it is likely to be patched in the future (see Cullen Fluffy Jennings's answer).
The ECMAScript 6 code below demonstrates how to do that.
/* ES6 */
const findLocalIp = (logInfo = true) => new Promise( (resolve, reject) => {
window.RTCPeerConnection = window.RTCPeerConnection
|| window.mozRTCPeerConnection
|| window.webkitRTCPeerConnection;
if ( typeof window.RTCPeerConnection == 'undefined' )
return reject('WebRTC not supported by browser');
let pc = new RTCPeerConnection();
let ips = [];
pc.createDataChannel("");
pc.createOffer()
.then(offer => pc.setLocalDescription(offer))
.catch(err => reject(err));
pc.onicecandidate = event => {
if ( !event || !event.candidate ) {
// All ICE candidates have been sent.
if ( ips.length == 0 )
return reject('WebRTC disabled or restricted by browser');
return resolve(ips);
}
let parts = event.candidate.candidate.split(' ');
let [base,componentId,protocol,priority,ip,port,,type,...attr] = parts;
let component = ['rtp', 'rtpc'];
if ( ! ips.some(e => e == ip) )
ips.push(ip);
if ( ! logInfo )
return;
console.log(" candidate: " + base.split(':')[1]);
console.log(" component: " + component[componentId - 1]);
console.log(" protocol: " + protocol);
console.log(" priority: " + priority);
console.log(" ip: " + ip);
console.log(" port: " + port);
console.log(" type: " + type);
if ( attr.length ) {
console.log("attributes: ");
for(let i = 0; i < attr.length; i += 2)
console.log("> " + attr[i] + ": " + attr[i+1]);
}
console.log();
};
} );
Notice I write return resolve(..)
or return reject(..)
as a shortcut. Both of those functions do not return anything.
Then you may have something this :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Local IP</title>
</head>
<body>
<h1>My local IP is</h1>
<p id="ip">Loading..</p>
<script src="ip.js"></script>
<script>
let p = document.getElementById('ip');
findLocalIp().then(
ips => {
let s = '';
ips.forEach( ip => s += ip + '<br>' );
p.innerHTML = s;
},
err => p.innerHTML = err
);
</script>
</body>
</html>
You should install Google Drivers from: http://developer.android.com/sdk/win-usb.html#top That works for me every time
In my case, I created a new project and when I ran it the first time, it gave me the following error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
So my solution was to go to the Package Manager Console inside the Visual Studio and run:Update-Package
Problem solved!!
I know this is a bit old, but I had the same problem and my search brought me here. I wanted two select elements and a button all inline, which worked in 2 but not 3. I ended up wrapping the three elements in <form class="form-inline">...</form>
. This actually worked perfectly for me.
Simple comparison of FP numbers has it's own specific and it's key is the understanding of FP format (see https://en.wikipedia.org/wiki/IEEE_floating_point)
When FP numbers calculated in a different ways, one through sin(), other though exp(), strict equality won't be working, even though mathematically numbers could be equal. The same way won't be working equality with the constant. Actually, in many situations FP numbers must not be compared using strict equality (==)
In such cases should be used DBL_EPSIPON constant, which is minimal value do not change representation of 1.0 being added to the number more than 1.0. For floating point numbers that more than 2.0 DBL_EPSIPON does not exists at all. Meanwhile, DBL_EPSILON has exponent -16, which means that all numbers, let's say, with exponent -34, would be absolutely equal in compare to DBL_EPSILON.
Also, see example, why 10.0 == 10.0000000000000001
Comparing dwo floating point numbers depend on these number nature, we should calculate DBL_EPSILON for them that would be meaningful for the comparison. Simply, we should multiply DBL_EPSILON to one of these numbers. Which of them? Maximum of course
bool close_enough(double a, double b){
if (fabs(a - b) <= DBL_EPSILON * std::fmax(fabs(a), fabs(b)))
{
return true;
}
return false;
}
All other ways would give you bugs with inequality which could be very hard to catch
The most straight forward answer to this question is: You can't.
Youtube doesn't output their video's in the right format, thus they can't be embedded in a
<video/>
element.
There are a few solutions posted using javascript, but don't trust on those, they all need a fallback, and won't work cross-browser.
This convention is followed for security reasons. For example if unauthorized person is allowed to access root JSP file directly from URL then they can navigate through whole application without any authentication and they can access all the secured data.
You can use this jsFiddle
And HTML:
<div id="previewBox">
<button id="closeButton">Close</button>
<a class="fragment" href="google.com">
<div>
<img src ="http://placehold.it/116x116" alt="some description"/>
<h3>the title will go here</h3>
<h4> www.myurlwill.com </h4>
<p class="text">
this is a short description yada yada peanuts etc this is a short description yada yada peanuts etc this is a short description yada yada peanuts etc this is a short description yada yada peanuts etcthis is a short description yada yada peanuts etc
</p>
</div>
</a>
</div>
With JS (jquery required):
$(document).ready(function() {
$('#closeButton').on('click', function(e) {
$('#previewBox').remove();
});
});
After years I have discovered one, if not the, answer to the Microsoft bug of the 'User-defined type not defined' error in Excel. I'm running Excel 2010 for Windows.
If you have a UDF named for example 'xyz()
', then if you invoke a non-existent entity beginning with that name followed by a period followed by other chars -- e.g., if you try to invoke non-existent range name 'xyz.abc
', the stupid app throws that wrong msg., after which it returns you to your sheet.
In my case it was especially unnerving, because I have UDFs named with just one letter, e.g. x()
, y()
, etc., and I also have range names that include periods--'x.a
', 'c.d
', etc. Every time I, say, misspelled a range name--for example, 'x.h', the 'User-defined …' error was thrown simply because a UDF named 'x()
' existed somewhere in my project.
It took several hrs. to diagnose. Suggestions above to incrementally remove code from your project, or conversely strip all code and incrementally add it back in, were on the right track but they didn't follow thru. It has nothing to do with code per se; it has only to do with the name of the first line of code in each proc, namely the Sub MyProc
or Function MyProc
line naming the proc. It was when I commented out one of my 1-letter-named UDFs in a completely unrelated part of the project that the bugged error msg. went away, and from there, after another hr. or so, I was able to generalize the rule as stated.
Perhaps the bug also occurs with punctuation characters other than period ('.
') But there aren't very many non-alpha chars permitted in a range name; underline ('_
') is allowed, but using it in the manner described doesn't seem to throw the bug.
Jim Luedke
Forget float, margin and html 3/5. The mail is very obsolete. You need do all with table. One line = one table. You need margin or padding ? Do another column.
Example : i need one line with 1 One Picture of 40*40 2 One margin of 10 px 3 One text of 400px
I start my line :
<table style=" background-repeat:no-repeat; width:450px;margin:0;" cellpadding="0" cellspacing="0" border="0">
<tr style="height:40px; width:450px; margin:0;">
<td style="height:40px; width:40px; margin:0;">
<img src="" style="width=40px;height40;margin:0;display:block"
</td>
<td style="height:40px; width:10px; margin:0;">
</td>
<td style="height:40px; width:400px; margin:0;">
<p style=" margin:0;"> my text </p>
</td>
</tr>
</table>
Mike Flynn's version did not work for me. Renaming C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\Microsoft.TeamFoundation.Git.Provider.dll
worked for me.
<input type="name" placeholder="First Name" title="First Name" />
title="First Name"
solves my proble. it worked with bootstrap.
update this code in baseactivity. and dont forget to include drawer_list_header in your activity xml.
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
setContentView(R.layout.drawer_list_header);
and dont use request() in your activity. but still the drawer is not visible on clicking image..and by dragging it will visible without list items. i tried a lot but no success. need some workouts for this...
EDIT: I've added one more option for bootstrap sidebars.
There are actually three manners in which you can make a bootstrap 3 sidebar. I tried to keep the code as simple as possible.
Here you can see a demo of a simple fixed sidebar I've developed with the same height as the page
I've also developed a rather simple column sidebar that works in a two or three column page inside a container. It takes the length of the longest column. Here you can see a demo
If you google bootstrap dashboard, you can find multiple suitable dashboard, such as this one. However, most of them require a lot of coding. I've developed a dashboard that works without additional javascript (next to the bootstrap javascript). Here is a demo
For all three examples you off course have to include the jquery, bootstrap css, js and theme.css files.
If you want the sidebar to hide on pressing a button this is also possible with only a little javascript.Here is a demo
Installing git and running npm install from git-bash worked for me. Make sure you are in the correct directory.
There are a few things to keep in mind while declaring primitive type values.
They are:
So in your code:
public class Main {
int instanceVariable;
static int staticVariable;
public static void main(String[] args) {
Main mainInstance = new Main()
int localVariable;
int localVariableTwo = 2;
System.out.println(mainInstance.instanceVariable);
System.out.println(staticVariable);
// System.out.println(localVariable); // Will throw a compilation error
System.out.println(localVariableTwo);
}
}
Try like this.
On change event,
$('input[type=checkbox]').on('change', function (e) {
if ($('input[type=checkbox]:checked').length > 3) {
$(this).prop('checked', false);
alert("allowed only 3");
}
});
Check this in JSFiddle
I'm a little late to the game here, but the simple answer is to move the H4 AFTER the button div. This is a common issue when floating, always have your floats defined BEFORE the rest of the contents or you'll have that extra line-break problem.
<div class="panel-heading">
<div class="btn-group pull-right">
<a href="#" class="btn btn-default btn-sm">## Lock</a>
<a href="#" class="btn btn-default btn-sm">## Delete</a>
<a href="#" class="btn btn-default btn-sm">## Move</a>
</div>
<h4>Panel header</h4>
</div>
The issue here is that when your floats are defined after other items, the float's top will start at the last line-position of the element immediately before it. So, if the previous item wraps to line 3, your float will start at line 3 too.
Moving the float to the TOP of the list eliminates the issue because there are no previous elements to push it down and anything after the float will be rendered at the top line (assuming there is room on the line for all items)
Example of correct and incorrect ordering and the effects: http://www.bootply.com/HkDlNIKv9g
Another way is to let chocolatey manage your ruby package (and any other package), that way you won't have to put ruby in your path manually:
Install chocolatey first by opening your favourite command prompt and executing:
@powershell -NoProfile -ExecutionPolicy unrestricted -Command "iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))" && SET PATH=%PATH%;%systemdrive%\chocolatey\bin
then all you need to do is type
cinst ruby
In your command prompt and the package installs.
Using a package manager provides overall more control, I'd recommend this for every package that can be installed via chocolatey.
iBeacon Profile contains 31 Bytes which includes the followings
For anyone else who runs into this...
Version 1.2.0 of this plugin (current as of this post) doesn't quite work in all cases as documented with Bootstrap 3.0, but it does with a minor workaround.
Specifically, if using an input with icon, the HTML markup is of course slightly different as class names have changed:
<div class="input-group" data-datepicker="true">
<input name="date" type="text" class="form-control" />
<span class="input-group-addon"><i class="icon-calendar"></i></span>
</div>
It seems because of this, you need to use a selector that points directly to the input element itself NOT the parent container (which is what the auto generated HTML on the demo page suggests).
$('*[data-datepicker="true"] input[type="text"]').datepicker({
todayBtn: true,
orientation: "top left",
autoclose: true,
todayHighlight: true
});
Having done this you will probably also want to add a listener for clicking/tapping on the icon so it sets focus on the text input when clicked (which is the behaviour when using this plugin with TB 2.x by default).
$(document).on('touch click', '*[data-datepicker="true"] .input-group-addon', function(e){
$('input[type="text"]', $(this).parent()).focus();
});
NB: I just use a data-datepicker boolean attribute because the class name 'datepicker' is reserved by the plugin and I already use 'date' for styling elements.
In my use case (feeding the resulting object to X2JS) the recommended approach
data = angular.toJson(source);
help to remove the $$hashKey
properties, but the result could then no longer be processed by X2JS.
data = angular.copy(source);
removed the $$hashKey
properties as well, but the result remained usable as a parameter for X2JS.
Try using absolute positioning, rather than relative positioning
this should get you close - you can adjust by tweaking margins or top/left positions
#play_button {
position:absolute;
transition: .5s ease;
top: 50%;
left: 50%;
}
Is this what you're after?
I added :text-align:center
to the div and image
<div style="width: 10px; height: 10px; position: relative; display: flex; justify-content: center;">
<div style="width: 1.5px; height: 100%; background-color: #9c9f9c; position: absolute; transform: rotate(45deg); border-radius: 2px;"></div>
<div style="width: 1.5px; height: 100%; background-color: #9c9f9c; position: absolute; transform: rotate(-45deg); border-radius: 2px;"></div>
</div>
_x000D_
Move your map variable into a scope where the event listener can use it. You are creating the map inside your initialize() function and nothing else can use it when created that way.
var map; //<-- This is now available to both event listeners and the initialize() function
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(40.5472,12.282715),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, "resize", function() {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
Pure css way to make a table fully responsive, no JavaScript is needed. Checke demo here Responsive Tables
<!DOCTYPE>
<html>
<head>
<title>Responsive Table</title>
<style>
/* only for demo purpose. you can remove it */
.container{border: 1px solid #ccc; background-color: #ff0000;
margin: 10px auto;width: 98%; height:auto;padding:5px; text-align: center;}
/* required */
.tablewrapper{width: 95%; overflow-y: hidden; overflow-x: auto;
background-color:green; height: auto; padding: 5px;}
/* only for demo purpose just for stlying. you can remove it */
table { font-family: arial; font-size: 13px; padding: 2px 3px}
table.responsive{ background-color:#1a99e6; border-collapse: collapse;
border-color: #fff}
tr:nth-child(1) td:nth-of-type(1){
background:#333; color: #fff}
tr:nth-child(1) td{
background:#333; color: #fff; font-weight: bold;}
table tr td:nth-child(2) {
background:yellow;
}
tr:nth-child(1) td:nth-of-type(2){color: #333}
tr:nth-child(odd){ background:#ccc;}
tr:nth-child(even){background:#fff;}
</style>
</head>
<body>
<div class="container">
<div class="tablewrapper">
<table class="responsive" width="98%" cellpadding="4" cellspacing="1" border="1">
<tr>
<td>Name</td>
<td>Email</td>
<td>Phone</td>
<td>Address</td>
<td>Contact</td>
<td>Mobile</td>
<td>Office</td>
<td>Home</td>
<td>Residency</td>
<td>Height</td>
<td>Weight</td>
<td>Color</td>
<td>Desease</td>
<td>Extra</td>
<td>DOB</td>
<td>Nick Name</td>
</tr>
<tr>
<td>RN Kushwaha</td>
<td>[email protected]</td>
<td>--</td>
<td>Varanasi</td>
<td>-</td>
<td>999999999</td>
<td>022-111111</td>
<td>-</td>
<td>India</td>
<td>165cm</td>
<td>58kg</td>
<td>bright</td>
<td>--</td>
<td>--</td>
<td>03/07/1986</td>
<td>Aryan</td>
</tr>
</table>
</div>
</div>
</body>
</html>
Another approach of offsetting is to have two empty rows, for example:
<div class="col-md-4"></div>
<div class="col-md-4">Centered Content</div>
<div class="col-md-4"></div>
UPDATE 2018 MAY:
Alternatively, you can embed Edge browser, but only targetting windows 10.
According to the latest Apple Human Interface Guidelines:
In portrait orientation, tab bar icons appear above tab titles. In landscape orientation, the icons and titles appear side-by-side. Depending on the device and orientation, the system displays either a regular or compact tab bar. Your app should include custom tab bar icons for both sizes.
I suggest you to use the above link to understand the full concept. Because apple update it's document in regular interval
use this after initialisation
$('.form_datetime').datetimepicker('update', new Date());
it's 2021 and here's a fantastically easy plugin to upload anything:
https://pqina.nl/filepond/?ref=pqina
add your element:
<input type="file"
class="filepond"
name="filepond"
multiple
data-allow-reorder="true"
data-max-file-size="3MB"
data-max-files="3">
Register any additional plugins:
FilePond.registerPlugin(
FilePondPluginImagePreview,
FilePondPluginImageExifOrientation,
FilePondPluginFileValidateSize,
FilePondPluginImageEdit);
Then wire in the element:
// Select the file input and use
// create() to turn it into a pond
FilePond.create(
document.querySelector('input'),
// Use Doka.js as image editor
imageEditEditor: Doka.create({
utils: ['crop', 'filter', 'color']
})
);
I use this with the additional Doka image editor to upload and transform images at https://www.yoodu.co.uk
crazy simple to setup and the guys who run it are great at support.
As you can tell I'm a fanboy.
Try this ...
Dim r as Range
Dim x as Integer
For x = 5000 to 4 step -1 '---> or change as you want //Thanx 4 KazJaw
set r = range("E" & format(x))
if ucase(r.Value) = "NONE" then
Rows(x).EntireRow.Delete
end if
Next
I had the same issue. For me I noticed that the https is using another Certificate which was invalid in terms of expiration date. Not sure why it happened. I changed the Https port number and a new self signed cert. WCFtestClinet could connect to the server via HTTPS!
$.ajax({
url: '//freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function(location) {
alert(location.ip);
}
});
This will work https too
This is full degree image rotation code. I recommend you to check the below example app in the jsfiddle.
https://jsfiddle.net/casamia743/xqh48gno/
The process flow of this example app is
function init() {
...
image.onload = function() {
app.boundaryRad = Math.atan(image.width / image.height);
}
...
}
/**
* NOTE : When source rect is rotated at some rad or degrees,
* it's original width and height is no longer usable in the rendered page.
* So, calculate projected rect size, that each edge are sum of the
* width projection and height projection of the original rect.
*/
function calcProjectedRectSizeOfRotatedRect(size, rad) {
const { width, height } = size;
const rectProjectedWidth = Math.abs(width * Math.cos(rad)) + Math.abs(height * Math.sin(rad));
const rectProjectedHeight = Math.abs(width * Math.sin(rad)) + Math.abs(height * Math.cos(rad));
return { width: rectProjectedWidth, height: rectProjectedHeight };
}
/**
* @callback rotatedImageCallback
* @param {DOMString} dataURL - return value of canvas.toDataURL()
*/
/**
* @param {HTMLImageElement} image
* @param {object} angle
* @property {number} angle.degree
* @property {number} angle.rad
* @param {rotatedImageCallback} cb
*
*/
function getRotatedImage(image, angle, cb) {
const canvas = document.createElement('canvas');
const { degree, rad: _rad } = angle;
const rad = _rad || degree * Math.PI / 180 || 0;
debug('rad', rad);
const { width, height } = calcProjectedRectSizeOfRotatedRect(
{ width: image.width, height: image.height }, rad
);
debug('image size', image.width, image.height);
debug('projected size', width, height);
canvas.width = Math.ceil(width);
canvas.height = Math.ceil(height);
const ctx = canvas.getContext('2d');
ctx.save();
const sin_Height = image.height * Math.abs(Math.sin(rad))
const cos_Height = image.height * Math.abs(Math.cos(rad))
const cos_Width = image.width * Math.abs(Math.cos(rad))
const sin_Width = image.width * Math.abs(Math.sin(rad))
debug('sin_Height, cos_Width', sin_Height, cos_Width);
debug('cos_Height, sin_Width', cos_Height, sin_Width);
let xOrigin, yOrigin;
if (rad < app.boundaryRad) {
debug('case1');
xOrigin = Math.min(sin_Height, cos_Width);
yOrigin = 0;
} else if (rad < Math.PI / 2) {
debug('case2');
xOrigin = Math.max(sin_Height, cos_Width);
yOrigin = 0;
} else if (rad < Math.PI / 2 + app.boundaryRad) {
debug('case3');
xOrigin = width;
yOrigin = Math.min(cos_Height, sin_Width);
} else if (rad < Math.PI) {
debug('case4');
xOrigin = width;
yOrigin = Math.max(cos_Height, sin_Width);
} else if (rad < Math.PI + app.boundaryRad) {
debug('case5');
xOrigin = Math.max(sin_Height, cos_Width);
yOrigin = height;
} else if (rad < Math.PI / 2 * 3) {
debug('case6');
xOrigin = Math.min(sin_Height, cos_Width);
yOrigin = height;
} else if (rad < Math.PI / 2 * 3 + app.boundaryRad) {
debug('case7');
xOrigin = 0;
yOrigin = Math.max(cos_Height, sin_Width);
} else if (rad < Math.PI * 2) {
debug('case8');
xOrigin = 0;
yOrigin = Math.min(cos_Height, sin_Width);
}
debug('xOrigin, yOrigin', xOrigin, yOrigin)
ctx.translate(xOrigin, yOrigin)
ctx.rotate(rad);
ctx.drawImage(image, 0, 0);
if (DEBUG) drawMarker(ctx, 'red');
ctx.restore();
const dataURL = canvas.toDataURL('image/jpg');
cb(dataURL);
}
function render() {
getRotatedImage(app.image, {degree: app.degree}, renderResultImage)
}
Create a Pivot Table. It has these features and many more.
If you are dead-set on doing this yourself then you could add shapes to the worksheet and use VBA to hide and unhide rows and columns on clicking the shapes.
The website you linked doesn't changes the image's width but it actually cuts it off. For that it needs to be set as a background-image.
For more info about background-image
look it at http://www.w3schools.com/cssref/pr_background-image.asp
Usage:
#divID {
background-image:url(image_url);
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
Using bootstrap with a little bit of customization, the following seems to work for me:
I need 3 partitions in my container and I tried this:
CSS:
.row.content {height: 100%; width:100%; position: fixed; }
.sidenav {
padding-top: 20px;
border: 1px solid #cecece;
height: 100%;
}
.midnav {
padding: 0px;
}
HTML:
<div class="container-fluid text-center">
<div class="row content">
<div class="col-md-2 sidenav text-left">Some content 1</div>
<div class="col-md-9 midnav text-left">Some content 2</div>
<div class="col-md-1 sidenav text-center">Some content 3</div>
</div>
</div>
The accepted answer has major drawback!
If you loaded your image that way your PictureBox will lock the image,so if you try to do any future operations on that image,you will get error message image used in another application!
This article show solution in VB
and This is C# implementation
FileStream fs = new System.IO.FileStream(@"Images\a.bmp", FileMode.Open, FileAccess.Read);
pictureBox1.Image = Image.FromStream(fs);
fs.Close();
I have same issue with IIS, i uninstalled IIS. Type in run services.msc, I see "wampapache64" service was not running, when I start it using right click it give me error.
I just used these steps.
Click on WAMP icon select Apache -> Service -> Remove Service
Click on Wamp icon select Apache -> Service -> Install Service
Got green Wamp icon :(
As an alternative to using a trigger, you might like to consider creating a stored procedure to handle the INSERT
s that takes most of the columns as arguments and gets the CURRENT_TIMESTAMP
which it includes in the final INSERT
to the database. You could do the same for the CREATE
. You may also be able to set things up so that users cannot execute INSERT
and CREATE
statements other than via the stored procedures.
I have to admit that I haven't actually done this myself so I'm not at all sure of the details.
The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName
to be the name of the file you wish to open.
Private Const TargetWBName As String = "myworkbook.xlsx"
'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
WorkbookOpen = False
On Error GoTo WorkBookNotOpen
If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
WorkbookOpen = True
Exit Function
End If
WorkBookNotOpen:
End Function
Private Sub Workbook_Open()
'Check if our target workbook is open
If WorkbookOpen(TargetWBName) = False Then
'set calculation to manual
Application.Calculation = xlCalculationManual
Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
DoEvents
Me.Close False
End If
End Sub
Set the constant 'TargetWBName' to be the name of the workbook that you wish to open.
This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself.
*NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True
after Me.Close
They change it again. At this moment documentation does not fit actual situation.
Commonly all works as expected with one small difference. Login from Devices
config now moves to Products -> Facebook Login
.
So you need to:
App id
from headline,Client Token
from app Settings -> Advanced
. There is also Native or desktop app?
question/config. I turn it on.Add product
and then Get started
on Facebook login
. Move back to your app config, click to newly added Facebook login
and you'll see your Login from Devices
config.Check the libs version requirements. The lib might be trying to call a method from from a higher Android version. Try adding the apps compatability libs.
When all else fails try switching from a Gradle build to an Eclipse build.
Delete and restructure your folders to the eclipse style and delete everything but your code. Then reload the project with your libs.
Once it runs go back to Gradle, if you wish.
With the current version of Bootstrap (3.3.7), it is possible to color a single cell of a table like so:
<td class = 'text-center col-md-4 success'>
The line reader.Read()
is missing in your code. You should add it. It is the function which actually reads data from the database:
string conString = "Data Source=localhost;Initial Catalog=LoginScreen;Integrated Security=True";
SqlConnection con = new SqlConnection(conString);
string selectSql = "select * from Pending_Tasks";
SqlCommand com = new SqlCommand(selectSql, con);
try
{
con.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
while(reader.Read())
{
CustID.Text = (read["Customer_ID"].ToString());
CustName.Text = (read["Customer_Name"].ToString());
Add1.Text = (read["Address_1"].ToString());
Add2.Text = (read["Address_2"].ToString());
PostBox.Text = (read["Postcode"].ToString());
PassBox.Text = (read["Password"].ToString());
DatBox.Text = (read["Data_Important"].ToString());
LanNumb.Text = (read["Landline"].ToString());
MobNumber.Text = (read["Mobile"].ToString());
FaultRep.Text = (read["Fault_Report"].ToString());
}
}
}
finally
{
con.Close();
}
EDIT : This code works supposing you want to write the last record to your textboxes. If you want to apply a different scenario, like for example to read all the records from database and to change data in the texboxes when you click the Next
button, you should create and use your own Model, or you can store data in the DataTable and refer to them later if you wish.
Maybe a little late to reply. I happen to run into the same problem today. I find that on Windows you can change the console encoder to utf-8
or other encoder that can represent your data. Then you can print it to sys.stdout
.
First, run following code in the console:
chcp 65001
set PYTHONIOENCODING=utf-8
Then, start python
do anything you want.
This is the best way to easyly install Node.js. This also is actual for Ubuntu 12.04 (Precise Pangolin), Ubuntu 13.04 (Raring Ringtail), and Ubuntu 14.04 (Trusty Tahr).
[sudo] apt-get install python-software-properties
[sudo] apt-add-repository ppa:chris-lea/node.js
[sudo] apt-get update
[sudo] apt-get install nodejs
node -v
Outputs
v0.10.20
npm install
npm -v
Outputs
1.4.3
If for some reason, if you see npm is not installed, you may try running:
[sudo] apt-get install npm
To update npm you may try running:
[sudo] npm install -g npm
For a project this size, you should stop writing pure JavaScript and turn to some of the libraries available. I'd recommend jQuery (http://jquery.com/), which allows you to select elements by css-selectors, which I recon should speed up your development quite a bit.
Example of your code then becomes;
function AddtoCart() {
var len = $("#Items tr").length, $row, $inp1, $inp2, $cells;
$row = $("#Items td:first").clone(true);
$cells = $row.find("td");
$cells.get(0).html( len );
$inp1 = $cells.get(1).find("input:first");
$inp1.attr("id", $inp1.attr("id") + len).val("");
$inp2 = $cells.get(2).find("input:first");
$inp2.attr("id", $inp2.attr("id") + len).val("");
$("#Items").append($row);
}
I can see that you might not understand that code yet, but take a look at jQuery, it's easy to learn and will make this development way faster.
I would use the libraries already created specifically for js shopping carts if I were you though.
To your problem; If i look at your jsFiddle, it doesn't even seem like you have defined a table with the id Items? Maybe that's why it doesn't work?
I used the following code, it's working!
using System.Data.OleDb;
using System.IO;
using System.Text.RegularExpressions;
private void btopen_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog openFileDialog1 = new OpenFileDialog(); //create openfileDialog Object
openFileDialog1.Filter = "XML Files (*.xml; *.xls; *.xlsx; *.xlsm; *.xlsb) |*.xml; *.xls; *.xlsx; *.xlsm; *.xlsb";//open file format define Excel Files(.xls)|*.xls| Excel Files(.xlsx)|*.xlsx|
openFileDialog1.FilterIndex = 3;
openFileDialog1.Multiselect = false; //not allow multiline selection at the file selection level
openFileDialog1.Title = "Open Text File-R13"; //define the name of openfileDialog
openFileDialog1.InitialDirectory = @"Desktop"; //define the initial directory
if (openFileDialog1.ShowDialog() == DialogResult.OK) //executing when file open
{
string pathName = openFileDialog1.FileName;
fileName = System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
DataTable tbContainer = new DataTable();
string strConn = string.Empty;
string sheetName = fileName;
FileInfo file = new FileInfo(pathName);
if (!file.Exists) { throw new Exception("Error, file doesn't exists!"); }
string extension = file.Extension;
switch (extension)
{
case ".xls":
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
break;
case ".xlsx":
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";
break;
default:
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
break;
}
OleDbConnection cnnxls = new OleDbConnection(strConn);
OleDbDataAdapter oda = new OleDbDataAdapter(string.Format("select * from [{0}$]", sheetName), cnnxls);
oda.Fill(tbContainer);
dtGrid.DataSource = tbContainer;
}
}
catch (Exception)
{
MessageBox.Show("Error!");
}
}
You need to return the validating function. Something like:
onsubmit="return validateForm();"
Then the validating function should return false on errors. If everything is OK return true. Remember that the server has to validate as well.
Timezones. You have to deal with them, by using getTimezoneOffset()
if you want your visitors from around the wolrd to get the same time.
Try this http://jsfiddle.net/cxyms/2/, it works for me, but I'm not sure will it work with other timezones.
var eventTimeStamp = '1366549200'; // Timestamp - Sun, 21 Apr 2013 13:00:00 GMT
var currentTimeStamp = '1366547400'; // Timestamp - Sun, 21 Apr 2013 12:30:00 GMT
var eventTime = new Date();
eventTime.setTime(366549200);
var Offset = new Date(eventTime.getTimezoneOffset()*60000)
var Diff = eventTimeStamp - currentTimeStamp + (Offset.getTime() / 2);
var duration = moment.duration(Diff, 'milliseconds');
var interval = 1000;
setInterval(function(){
duration = moment.duration(duration.asMilliseconds() - interval, 'milliseconds');
$('.countdown').text(moment(duration.asMilliseconds()).format('H[h]:mm[m]:ss[s]'));
}, interval);
if (reader.HasRows)
{
while (reader.Read())
{
comboBox1.Items.Add(reader.GetString(0));
}
}
reader.Close();
MySqlDataReader reader1 = cmd1.ExecuteReader();
if (reader1.HasRows)
{
while (reader1.Read())
{
listBox1.Items.Add(reader1.GetString(0));
}
}
reader1.Close();
hello to everyone just wanted to share my experience with phpMailer , that was working locally (XAMPP) but wasn't working on my hosting provider.
I turned on phpMailer error reporting
$mail->SMTPDebug=2
i got 'Connection refused Error'
I email my host provider for the issue , and he said that he would open the SMTP PORTS and he opened the ports 25,465,587 .
Then i got the following error response "SMTP ERROR: Password command failed:"...."Please log in via your web browser and then try again"...."SMTP Error: Could not authenticate."
So google checks if your are logged in to your account (i was when i ran the script locally through my browser) and then allows you to send mail through the phpMailer script.
To fix that 1:go to your google account -> security 2:Scroll to the Key Icon and choose "2 way verification" and follow the procedure 3:When done go back to the key icon from google account -> security and choose the second option "create app passwords" and follow the procedure to get the password.
Now go to your phpMailer object and change your google password with the password given from the above procedure
you are done .
The code
require_once('class.phpmailer.php');
$phpMailerObj= new PHPMailer();
$phpMailerObj->isSMTP();
$phpMailerObj->SMTPDebug = 0;
$phpMailerObj->Debugoutput = 'html';
$phpMailerObj->Host = 'smtp.gmail.com';
$phpMailerObj->Port = 587;
$phpMailerObj->SMTPSecure = 'tls';
$phpMailerObj->SMTPAuth = true;
$phpMailerObj->Username = "YOUR EMAIL";
$phpMailerObj->Password = "THE NEW PASSWORD FROM GOOGLE ";
$phpMailerObj->setFrom('YOUR EMAIL ADDRESS', 'THE NAME OF THE SENDER',0);
$phpMailerObj->addAddress('RECEIVER EMAIL ADDRESS', 'RECEIVER NAME');
$phpMailerObj->Subject = 'SUBJECT';
$phpMailerObj->Body ='MESSAGE';
if (!phpMailerObj->send()) {
echo "phpMailerObjer Error: " . $phpMailerObj->ErrorInfo;
return 0;
} else {
echo "Message sent!";
return 1;
}
Try this
sudo -u hdfs hdfs dfsadmin -safemode leave
check status of safemode
sudo -u hdfs hdfs dfsadmin -safemode get
If it is still in safemode ,then one of the reason would be not enough space in your node, you can check your node disk usage using :
df -h
if root partition is full, delete files or add space in your root partition and retry first step.
ssize_t
is not included in the standard and isn't portable. size_t
should be used when handling the size of objects (there's ptrdiff_t
too, for pointer differences).
This problem was caused for me by this error which appeared just prior in the application error log.
"A read operation on a large object failed while sending data to the client. A common cause for this is if the application is running in READ UNCOMMITTED isolation level. This connection will be terminated."
I was storing PDFs in a SQL table and when attempting to SELECT from that table it spit out that error, which resulted in the error mentioned in your question.
The solution was to delete the columns that had large amounts of text, in my case Base64 encoded files.
Try to add this:
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
In my case:
Project properties ? Project Facets. Make sure "Dynamic Web Module" is checked. Finally, I enter the version number "2.3" instead of "3.0". After that, the Apache Tomcat 5.5 runtime is listed in the "Runtimes" tab.
There is two ways to make/create object in c++.
First one is :
MyClass myclass; // if you don;t need to call rather than default constructor
MyClass myclass(12); // if you need to call constructor with parameters
Second one is :
MyClass *myclass = new MyClass();// if you don;t need to call rather than default constructor
MyClass *myclass = new MyClass(12);// if you need to call constructor with parameters
In c++ if you use new keyword, object will be stored in heap. it;s very useful if you are using this object long time of period and if you use first method, it will be stored in stack. it can be used only short time period. Notice : if you use new keyword, remember it will return pointer value. you should declare name with *. If you use second method, it doesn;t delete object in the heap. you must delete by yourself using delete keyword;
delete myclass;
I got a similar error, the problem stopped when I checked my "Linker -> Input -> Additional Dependencies" list in the project properties. I was missing a semi colon ";" just before "%(AdditionalDependencies)". I also had the same entry in twice. You should edit this list separately for Debug and Release.
A little bit late but I got the same error and I realized that it was because I copied some code from a PDF. Check the difference between these two:
-
-
The first one is from hitting the minus sign on keyboard and the second is from a latex generated PDF.
Try this code.
public void send (String fileName) {
String SFTPHOST = "host:IP";
int SFTPPORT = 22;
String SFTPUSER = "username";
String SFTPPASS = "password";
String SFTPWORKINGDIR = "file/to/transfer";
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
System.out.println("preparing the host information for sftp.");
try {
JSch jsch = new JSch();
session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
session.setPassword(SFTPPASS);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
System.out.println("Host connected.");
channel = session.openChannel("sftp");
channel.connect();
System.out.println("sftp channel opened and connected.");
channelSftp = (ChannelSftp) channel;
channelSftp.cd(SFTPWORKINGDIR);
File f = new File(fileName);
channelSftp.put(new FileInputStream(f), f.getName());
log.info("File transfered successfully to host.");
} catch (Exception ex) {
System.out.println("Exception found while tranfer the response.");
} finally {
channelSftp.exit();
System.out.println("sftp Channel exited.");
channel.disconnect();
System.out.println("Channel disconnected.");
session.disconnect();
System.out.println("Host Session disconnected.");
}
}
You don't add links to style sheets. They are for describing the style of the page. You would change your mark-up or add JavaScript to navigate when the image is clicked.
Based only on your style you would have:
<a href="home.com" id="logo"></a>
The .browser call has been removed in jquery 1.9 have a look at http://jquery.com/upgrade-guide/1.9/ for more details.
As mentioned on the javadocs you are better off using a ScheduledThreadPoolExecutor.
Use this class when your use case requires multiple worker threads and the sleep interval is small. How small ? Well, I'd say about 15 minutes. The AlarmManager
starts schedule intervals at this time and it seems to suggest that for smaller sleep intervals this class can be used. I do not have data to back the last statement. It is a hunch.
Your service can be closed any time by the VM. Do not use services for recurring tasks. A recurring task can start a service, which is another matter entirely.
For longer sleep intervals (>15 minutes), this is the way to go. AlarmManager
already has constants ( AlarmManager.INTERVAL_DAY
) suggesting that it can trigger tasks several days after it has initially been scheduled. It can also wake up the CPU to run your code.
You should use one of those solutions based on your timing and worker thread needs.
The simplest way to get equal height columns, without the ugly side effects that come along with absolute positioning, is to use the display: table
properties:
.div1 {
width:300px;
height: auto;
background-color: grey;
border:1px solid;
display: table;
}
.div2, .div3 {
display: table-cell;
}
.div2 {
width:150px;
height:auto;
background-color: #F4A460;
}
.div3 {
width:150px;
height:auto;
background-color: #FFFFE0;
}
Now, if your goal is to have .div2
so that it is only as tall as it needs to be to contain its content while .div3
is at least as tall as .div2
but still able to expand if its content makes it taller than .div2
, then you need to use flexbox. Flexbox support isn't quite there yet (IE10, Opera, Chrome. Firefox follows an old spec, but is following the current spec soon).
.div1 {
width:300px;
height: auto;
background-color: grey;
border:1px solid;
display: flex;
align-items: flex-start;
}
.div2 {
width:150px;
background-color: #F4A460;
}
.div3 {
width:150px;
background-color: #FFFFE0;
align-self: stretch;
}
This works in IE9 (Compatibility View and Normal Mode), Firefox 17, and Chrome 23:
<table>
<tr>
<td style="background-image:url(untitled.png); background-position:right 0px; background-repeat:no-repeat;">
Hello World
</td>
</tr>
</table>
For the the accepted answer of @Joseph Silber is not working, because indexOf returns -1. This is probably because Angular adds an hashkey, which is different for my $scope.items[0] and my item. I tried to resolve this with the angular.toJson() function, but it did not work :(
Ah, I found out the reason... I use a chunk method to create two columns in my table by watching my $scope.items. Sorry!
Usually the problem is not closing brackets (}) or missing semicolon (;)
SELECT a.C_ID,a.QRY_ID,a.RES_ID,b.SCORE,ROW_NUMBER() OVER (ORDER BY SCORE DESC) AS [RANK]
FROM CONTACTS a JOIN RSLTS b ON a.QRY_ID=b.QRY_ID AND a.RES_ID=b.RES_ID
ORDER BY a.C_ID
You have to single quote your src
string inside of the double quotes:
<div ng-include src="'views/sidepanel.html'"></div>
I just created a new cluster and that worked for me, I was using (PostgreSQL) 9.3.20:
sudo pg_createcluster 9.3 main --start
Download the updated version of the Google Chrome driver from Chrome Driver.
Please read the release note as well here.
If the Chrome browser is updated, then you need to download the new Chrome driver from the above link, because it would be compatible with the new browser version.
public class chrome
{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("http://www.google.com");
}
}
Just try to replace your layout with :
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
You need to use the SupportMapFragment for API under 11 !
Aurel
Use the str_contains
function.
if (str_contains($str, "."))
{
echo 'Found it';
}
else
{
echo 'Not found.';
}
if (strpos($str, '.') !== FALSE)
{
echo 'Found it';
}
else
{
echo 'Not found.';
}
Note that you need to use the !==
operator. If you use !=
or <>
and the '.'
is found at position 0
, the comparison will evaluate to true because 0
is loosely equal to false
.
Try Making the Child Form's StartPosition Property set to Center Parent. This you can select from the form Properties.
You can use Modernizr to detect simply IE or not IE, by checking for SVG SMIL animation support.
If you've included SMIL feature detection in your Modernizr setup, you can use a simple CSS approach, and target the .no-smil class that Modernizr applies to the html element:
html.no-smil {
/* IE/Edge specific styles go here - hide HTML5 content and show Flash content */
}
Alternatively, you could use Modernizr with a simple JavaScript approach, like so:
if ( Modernizr.smil ) {
/* set HTML5 content */
} else {
/* set IE/Edge/Flash content */
}
Bear in mind, IE/Edge might someday support SMIL, but there are currently no plans to do so.
For reference, here's a link to the SMIL compatibility chart at caniuse.com.
You only initialize the first N positions to the values in braces and all others are initialized to 0. In this case, N is the number of arguments you passed to the initialization list, i.e.,
float arr1[10] = { }; // all elements are 0
float arr2[10] = { 0 }; // all elements are 0
float arr3[10] = { 1 }; // first element is 1, all others are 0
float arr4[10] = { 1, 2 }; // first element is 1, second is 2, all others are 0
In my case, all libraries in the build path were OK.
To solve it, I deleted all project metadata (.project, .classpath, .settings) and re-imported the project as a Maven project.
No that is wrong. Arrays are special objects in Java. So it is like passing other objects where you pass the value of the reference, but not the reference itself. Meaning, changing the reference of an array in the called routine will not be reflected in the calling routine.
Please follow the way like below:
.selectParent {_x000D_
width:120px;_x000D_
overflow:hidden; _x000D_
}_x000D_
.selectParent select { _x000D_
display: block;_x000D_
width: 100%;_x000D_
padding: 2px 25px 2px 2px; _x000D_
border: none; _x000D_
background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") right center no-repeat; _x000D_
appearance: none; _x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none; _x000D_
}_x000D_
.selectParent.left select {_x000D_
direction: rtl;_x000D_
padding: 2px 2px 2px 25px;_x000D_
background-position: left center;_x000D_
}_x000D_
/* for IE and Edge */ _x000D_
select::-ms-expand { _x000D_
display: none; _x000D_
}
_x000D_
<div class="selectParent">_x000D_
<select>_x000D_
<option value="1">Option 1</option>_x000D_
<option value="2">Option 2</option> _x000D_
</select>_x000D_
</div>_x000D_
<br />_x000D_
<div class="selectParent left">_x000D_
<select>_x000D_
<option value="1">Option 1</option>_x000D_
<option value="2">Option 2</option> _x000D_
</select>_x000D_
</div>
_x000D_
You can just use the normal termios header and normal termios structure (it's the same as the termios2 when using header asm/termios).
So, you open the device using open() and get a file descriptor, then use it in tcgetattr()
to fill your termios structure.
Then clear CBAUD
and set CBAUDEX
on c_cflag
.
CBAUDEX
has the same value as BOTHER.
After setting this, you can set a custom baud rate using normal functions, like cfsetspeed()
, specifying the desired baud rate as an integer.
Here you go:
https://support.google.com/docs/answer/3093281
This is all the documentation that Google provides.
Have you tried the "Publish" method? You just right click on the project file in the solution explorer and select "Publish" from the pop-up menu. This creates an installer in a few very simple steps.
You can do more configuration of the installer from the Publish tab in the project properties window.
NB: This method only works for WPF & Windows Forms apps.
to allow google translate to be mobile friendly get rid of the layout section, layout: google.translate.TranslateElement.InlineLayout.SIMPLE
<div id="google_translate_element">
</div>
<script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element');
}
</script>
<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
It works on my site and it is mobile friendly. https://livinghisword.org/articles/pages/whoiscernandisourworld.php
Rather than provide you with a complete list of differences, I'll give you my view on the matter.
If you read carefully the wiki page you provide, you'll often see sentences like "Octave supports both, while MATLAB requires the first" etc. This shows that Octave's developers try to make Octave syntax "superior" to MATLAB's.
This attitude makes Octave lose its purpose completely. The idea behind Octave is (or has become, I should say, see comments below) to have an open source alternative to run m-code. If it tries to be "better", it thus tries to be different, which is not in line with the reasons most people use it for. In my experience, running stuff developed in MATLAB doesn't ever work in one go, except for the really simple, really short stuff -- For any sizable function, I always have to translate a lot of stuff before it works in Octave, if not re-write it from scratch. How this is better, I really don't see...
Also, if you learn Octave, there's a lot of syntax allowed in Octave that's not allowed in MATLAB. Meaning -- code written in Octave often does not work in MATLAB without numerous conversions. It's also not compatible the other way around!
I could go on: The MathWorks has many toolboxes for MATLAB, there's Simulink and its related products for which there really is no equivalent in Octave (yes, you'd have to pay for all that. But often your employer/school does that anyway, and well, it at least exists), proven compliance with several industry standards, testing tools, validation tools, requirement management systems, report generation, a much larger community & user base, etc. etc. etc. MATLAB is only a small part of something much larger. Octave is...just Octave.
So, my advice:
Why this last point? Because in the sciences, there are often large code bases entirely written in MATLAB. There are professors, engineers, students, professional coders, lots and lots of people who know all the intricate gory details of MATLAB, and not so much of Octave.
If you get a new job, and everyone in your new office speaks Spanish, it's kind of cocky to demand of everyone that they start speaking English from then on, simply because you don't speak/like Spanish. Same with MATLAB and Octave.
NB -- if all downvoters could just leave a comment with their arguments and reasons for disagreeing with me, that'd be great :)
Note: Octave can be run in "traditional mode" (by including the --traditional flag when starting Octave) which makes it give an error when certain Octave-only syntax is used.
you can find mysqld.sock
in /var/run/mysqld
if you have already installed mysql-server
by sudo apt-get install mysql-server
It's because you're trying to assign an object by reference. Remove the ampersand and your script should work as intended.
These emoji characters are also useful if you are okay with this limited variety of colors and shapes (though they may look different in different OS/browsers), This is an alternative to AlecRust's answer which needs an external service that may go down someday, and with the idea of using emojis from Luke Hutchison's answer:
??
??
???????
????????????
There are also many colored rectangle characters with alphanumeric/arrow/other-symbols that may work for you.
Also, the following emojis are skin tone modifiers that have the skin colors inside this rectangular-ish shape. Don't use them! Because they should be alone ( otherwise they may modify the output of the sibling emojis) and also they are rendered so much different in different os/version/browser/version combination when used alone.
Actions act = new Actions(driver);
act.keyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL).build().perform();
Just stack two bootstrap tables; one for columns, the other for content. No plugins, just pure bootstrap (and that ain't no bs, haha!)
<table id="tableHeader" class="table" style="table-layout:fixed">
<thead>
<tr>
<th>Col1</th>
...
</tr>
</thead>
</table>
<div style="overflow-y:auto;">
<table id="tableData" class="table table-condensed" style="table-layout:fixed">
<tbody>
<tr>
<td>data</td>
...
</tr>
</tbody>
</table>
</div>
The content table div needs overflow-y:auto
, for vertical scroll bars. Had to use table-layout:fixed
, otherwise, columns did not line up. Also, had to put the whole thing inside a bootstrap panel to eliminate space between the tables.
Have not tested with custom column widths, but provided you keep the widths consistent between the tables, it should work.
// ADD THIS JS FUNCTION TO MATCH UP COL WIDTHS
$(function () {
//copy width of header cells to match width of cells with data
//so they line up properly
var tdHeader = document.getElementById("tableHeader").rows[0].cells;
var tdData = document.getElementById("tableData").rows[0].cells;
for (var i = 0; i < tdData.length; i++)
tdHeader[i].style.width = tdData[i].offsetWidth + 'px';
});
Scenario 1:
One scenario:
You use a package that gets removed from npm. If you have all the modules in the folder node_modules, then it won't be a problem for you. If you do only have the package name in the package.json, you can't get it anymore.
If a package is less than 24 hours old, you can easily remove it from npm. If it's older than 24 hours old, then you need to contact them.
But:
If you contact support, they will check to see if removing that version of your package would break any other installs. If so, we will not remove it.
So the chances for this are low, but there is scenario 2...
Scenario 2:
An other scenario where this is the case:
You develop an enterprise version of your software or a very important software and write in your package.json:
"dependencies": {
"studpid-package": "~1.0.1"
}
You use the method function1(x)
of that package.
Now the developers of studpid-package rename the method function1(x)
to function2(x)
and they make a fault...
They change the version of their package from 1.0.1
to 1.1.0
.
That's a problem because when you call npm install
the next time, you will accept version 1.1.0
because you used the tilde ("studpid-package": "~1.0.1"
).
Calling function1(x)
can cause errors and problems now.
Pushing the whole node_modules folder (often more than 100 MB) to your repository, will cost you memory space. A few kb (package.json only) compared with hundreds of MB (package.json & node_modules)... Think about it.
You could do it / should think about it if:
the software is very important.
it costs you money when something fails.
you don't trust the npm registry. npm is centralized and could theoretically be shut down.
You don't need to publish the node_modules folder in 99.9% of the cases if:
you develop a software just for yourself.
you've programmed something and just want to publish the result on GitHub because someone else could maybe be interested in it.
If you don't want the node_modules to be in your repository, just create a .gitignore
file and add the line node_modules
.
Possible duplicate: Check if an element has event listener on it. No jQuery Please find my answer there.
Basically here is the trick for Chromium (Chrome) browser:
getEventListeners(document.querySelector('your-element-selector'));
For people out there asking how to setup proxy server in chrome which needs authentication should follow these steps.
There's no problem with using a localhost url for Dev work - obviously it needs to be changed when it comes to production.
You need to go here: https://developers.google.com/accounts/docs/OAuth2 and then follow the link for the API Console - link's in the Basic Steps section. When you've filled out the new application form you'll be asked to provide a redirect Url. Put in the page you want to go to once access has been granted.
When forming the Google oAuth Url - you need to include the redirect url - it has to be an exact match or you'll have problems. It also needs to be UrlEncoded.
I have tried the solutions provided by Dmitriy Lozenko and Gnathonic on my Samsung Galaxy Tab S2 (Model: T819Y) but none helped me retrieve path to an external SD Card directory. mount
command execution contained the required path to external SD Card directory (i.e. /Storage/A5F9-15F4) but it did not match the regular expression hence it was not returned. I don't get the directory naming mechanism followed by Samsung. Why they deviate from standards (i.e. extsdcard) and come up with something really fishy like in my case (i.e. /Storage/A5F9-15F4). Is there anything I am missing? Anyways, following changes in regular expression of Gnathonic's solution helped me get valid sdcard directory:
final HashSet<String> out = new HashSet<String>();
String reg = "(?i).*(vold|media_rw).*(sdcard|vfat|ntfs|exfat|fat32|ext3|ext4).*rw.*";
String s = "";
try {
final Process process = new ProcessBuilder().command("mount")
.redirectErrorStream(true).start();
process.waitFor();
final InputStream is = process.getInputStream();
final byte[] buffer = new byte[1024];
while (is.read(buffer) != -1) {
s = s + new String(buffer);
}
is.close();
} catch (final Exception e) {
e.printStackTrace();
}
// parse output
final String[] lines = s.split("\n");
for (String line : lines) {
if (!line.toLowerCase(Locale.US).contains("asec")) {
if (line.matches(reg)) {
String[] parts = line.split(" ");
for (String part : parts) {
if (part.startsWith("/"))
if (!part.toLowerCase(Locale.US).contains("vold"))
out.add(part);
}
}
}
}
return out;
I am not sure if this is a valid solution and if it will give results for other Samsung tablets but it has fixed my problem for now. Following is another method to retrieve removable SD Card path in Android (v6.0). I have tested the method with android marshmallow and it works. Approach used in it is very basic and will surely work for other versions too but testing is mandatory. Some insight into it will be helpful:
public static String getSDCardDirPathForAndroidMarshmallow() {
File rootDir = null;
try {
// Getting external storage directory file
File innerDir = Environment.getExternalStorageDirectory();
// Temporarily saving retrieved external storage directory as root
// directory
rootDir = innerDir;
// Splitting path for external storage directory to get its root
// directory
String externalStorageDirPath = innerDir.getAbsolutePath();
if (externalStorageDirPath != null
&& externalStorageDirPath.length() > 1
&& externalStorageDirPath.startsWith("/")) {
externalStorageDirPath = externalStorageDirPath.substring(1,
externalStorageDirPath.length());
}
if (externalStorageDirPath != null
&& externalStorageDirPath.endsWith("/")) {
externalStorageDirPath = externalStorageDirPath.substring(0,
externalStorageDirPath.length() - 1);
}
String[] pathElements = externalStorageDirPath.split("/");
for (int i = 0; i < pathElements.length - 1; i++) {
rootDir = rootDir.getParentFile();
}
File[] files = rootDir.listFiles();
for (File file : files) {
if (file.exists() && file.compareTo(innerDir) != 0) {
// Try-catch is implemented to prevent from any IO exception
try {
if (Environment.isExternalStorageRemovable(file)) {
return file.getAbsolutePath();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
Kindly share if you have any other approach to handle this issue. Thanks
jQuery plugin for decorating image maps (highlights, select areas, tooltips):
http://www.outsharked.com/imagemapster/
Disclosure: I wrote it.
Here is a working example. I changed the code to output to a div instead of an alert box. Your issue was item.innerHTML
I believe. I use the jQuery html
function instead and that seemed to resolve the issue.
<table id='thisTable' class='disptable' style='margin-left:auto;margin-right:auto;' >
<tr>
<th>Fund</th>
<th>Organization</th>
<th>Access</th>
<th>Delete</th>
</tr>
<tr>
<td class='fund'>100000</td><td class='org'>10110</td><td>OWNED</td><td><a class='delbtn'ref='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67130</td><td>OWNED</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>170252</td><td class='org'>67130</td><td>OWNED</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67150</td><td>PENDING ACCESS</td><td><a class='delbtn' href='#'>X</a></td></tr>
<tr><td class='fund'>100000</td><td class='org'>67120</td><td>PENDING ACCESS</td><td><a class='delbtn' href='#'>X</a>
</td>
</tr>
</table>
<div id="output"></div>?
the javascript:
$('#thisTable tr').on('click', function(event) {
var tds = $(this).addClass('row-highlight').find('td');
var values = '';
tds.each(function(index, item) {
values = values + 'td' + (index + 1) + ':' + $(item).html() + '<br/>';
});
$("#output").html(values);
});
Building on Vitaliy's CSS and Mehmet's jQuery, I changed the a
tags to span
tags and incorporated some Glyphicons and badging into my take on a Bootstrap tree widget.
Example:
For extra credit, I've created a GitHub project to host the jQuery and LESS code that goes into adding this tree component to Bootstrap. Please see the project documentation at http://jhfrench.github.io/bootstrap-tree/docs/example.html.
Alternately, here is the LESS source to generate that CSS (the JS can be picked up from the jsFiddle):
@import "../../../external/bootstrap/less/bootstrap.less"; /* substitute your path to the bootstrap.less file */
@import "../../../external/bootstrap/less/responsive.less"; /* optional; substitute your path to the responsive.less file */
/* collapsable tree */
.tree {
.border-radius(@baseBorderRadius);
.box-shadow(inset 0 1px 1px rgba(0,0,0,.05));
background-color: lighten(@grayLighter, 5%);
border: 1px solid @grayLight;
margin-bottom: 10px;
max-height: 300px;
min-height: 20px;
overflow-y: auto;
padding: 19px;
a {
display: block;
overflow: hidden;
text-overflow: ellipsis;
width: 90%;
}
li {
list-style-type: none;
margin: 0px 0;
padding: 4px 0px 0px 2px;
position: relative;
&::before, &::after {
content: '';
left: -20px;
position: absolute;
right: auto;
}
&::before {
border-left: 1px solid @grayLight;
bottom: 50px;
height: 100%;
top: 0;
width: 1px;
}
&::after {
border-top: 1px solid @grayLight;
height: 20px;
top: 13px;
width: 23px;
}
span {
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border: 1px solid @grayLight;
border-radius: 5px;
display: inline-block;
line-height: 14px;
padding: 2px 4px;
text-decoration: none;
}
&.parent_li > span {
cursor: pointer;
/*Time for some hover effects*/
&:hover, &:hover+ul li span {
background: @grayLighter;
border: 1px solid @gray;
color: #000;
}
}
/*Remove connectors after last child*/
&:last-child::before {
height: 30px;
}
}
/*Remove connectors before root*/
> ul > li::before, > ul > li::after {
border: 0;
}
}
Try this:
$Wsdl = 'http://xxxx.xxx.xx/webservice3.asmx?WSDL';
libxml_disable_entity_loader(false); //adding this worked for me
$Client = new SoapClient($Wsdl);
//Code...
It may be because your web folder (as mentioned "/Applications/MAMP/htdocs/mysite/web") is empty.
My suggestion is first to make your project and then work on making the virtual host.
I went with a similar situation. I was using an empty folder in the DocumentRoot in httpd-vhosts.confiz and I couldn't access my shahg101.com site.
Below method uploads file in a particular folder in a bucket and return the generated url of the file uploaded.
private String uploadFileToS3Bucket(final String bucketName, final File file) {
final String uniqueFileName = uploadFolder + "/" + file.getName();
LOGGER.info("Uploading file with name= " + uniqueFileName);
final PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, uniqueFileName, file);
amazonS3.putObject(putObjectRequest);
return ((AmazonS3Client) amazonS3).getResourceUrl(bucketName, uniqueFileName);
}
ZF cake:
<?php
class FkuController extends Zend_Controller_Action {
var $image;
var $image_type;
public function store_uploaded_image($html_element_name, $new_img_width, $new_img_height) {
$target_dir = APPLICATION_PATH . "/../public/1/";
$target_file = $target_dir . basename($_FILES[$html_element_name]["name"]);
//$image = new SimpleImage();
$this->load($_FILES[$html_element_name]['tmp_name']);
$this->resize($new_img_width, $new_img_height);
$this->save($target_file);
return $target_file;
//return name of saved file in case you want to store it in you database or show confirmation message to user
public function load($filename) {
$image_info = getimagesize($filename);
$this->image_type = $image_info[2];
if( $this->image_type == IMAGETYPE_JPEG ) {
$this->image = imagecreatefromjpeg($filename);
} elseif( $this->image_type == IMAGETYPE_GIF ) {
$this->image = imagecreatefromgif($filename);
} elseif( $this->image_type == IMAGETYPE_PNG ) {
$this->image = imagecreatefrompng($filename);
}
}
public function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) {
if( $image_type == IMAGETYPE_JPEG ) {
imagejpeg($this->image,$filename,$compression);
} elseif( $image_type == IMAGETYPE_GIF ) {
imagegif($this->image,$filename);
} elseif( $image_type == IMAGETYPE_PNG ) {
imagepng($this->image,$filename);
}
if( $permissions != null) {
chmod($filename,$permissions);
}
}
public function output($image_type=IMAGETYPE_JPEG) {
if( $image_type == IMAGETYPE_JPEG ) {
imagejpeg($this->image);
} elseif( $image_type == IMAGETYPE_GIF ) {
imagegif($this->image);
} elseif( $image_type == IMAGETYPE_PNG ) {
imagepng($this->image);
}
}
public function getWidth() {
return imagesx($this->image);
}
public function getHeight() {
return imagesy($this->image);
}
public function resizeToHeight($height) {
$ratio = $height / $this->getHeight();
$width = $this->getWidth() * $ratio;
$this->resize($width,$height);
}
public function resizeToWidth($width) {
$ratio = $width / $this->getWidth();
$height = $this->getheight() * $ratio;
$this->resize($width,$height);
}
public function scale($scale) {
$width = $this->getWidth() * $scale/100;
$height = $this->getheight() * $scale/100;
$this->resize($width,$height);
}
public function resize($width,$height) {
$new_image = imagecreatetruecolor($width, $height);
imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
$this->image = $new_image;
}
public function savepicAction() {
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$this->_response->setHeader('Access-Control-Allow-Origin', '*');
$this->db = Application_Model_Db::db_load();
$ouser = $_POST['ousername'];
$fdata = 'empty';
if (isset($_FILES['picture']) && $_FILES['picture']['size'] > 0) {
$file_size = $_FILES['picture']['size'];
$tmpName = $_FILES['picture']['tmp_name'];
//Determine filetype
switch ($_FILES['picture']['type']) {
case 'image/jpeg': $ext = "jpg"; break;
case 'image/png': $ext = "png"; break;
case 'image/jpg': $ext = "jpg"; break;
case 'image/bmp': $ext = "bmp"; break;
case 'image/gif': $ext = "gif"; break;
default: $ext = ''; break;
}
if($ext) {
//if($file_size<400000) {
$img = $this->store_uploaded_image('picture', 90,82);
//$fp = fopen($tmpName, 'r');
$fp = fopen($img, 'r');
$fdata = fread($fp, filesize($tmpName));
$fdata = base64_encode($fdata);
fclose($fp);
//}
}
}
if($fdata=='empty'){
}
else {
$this->db->update('users',
array(
'picture' => $fdata,
),
array('username=?' => $ouser ));
}
}
Maybe this is useful to anyone in the future, I have implemented a custom Authorize Attribute like this:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class ClaimAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
{
private readonly string _claim;
public ClaimAuthorizeAttribute(string Claim)
{
_claim = Claim;
}
public void OnAuthorization(AuthorizationFilterContext context)
{
var user = context.HttpContext.User;
if(user.Identity.IsAuthenticated && user.HasClaim(ClaimTypes.Name, _claim))
{
return;
}
context.Result = new ForbidResult();
}
}
In case anyone landed here in search of "how to specify types of multiple return values?", use Tuple[type_value1, ..., type_valueN]
from typing import Tuple
def f() -> Tuple[dict, str]:
a = {1: 2}
b = "hello"
return a, b
something like....
SELECT f.*
,a1.city as from
,a2.city as to
FROM flights f
INNER JOIN airports a1
ON f.fairport = a1. code
INNER JOIN airports a2
ON f.tairport = a2. code
Overview of workarounds
Either:
use a linked list implementation/roll your own.
A linked list is the proper data structure to support efficient item removal, and does not force you to make space/time tradeoffs.
A CPython list
is implemented with dynamic arrays as mentioned here, which is not a good data type to support removals.
There doesn't seem to be a linked list in the standard library however:
start a new list()
from scratch, and .append()
back at the end as mentioned at: https://stackoverflow.com/a/1207460/895245
This time efficient, but less space efficient because it keeps an extra copy of the array around during iteration.
use del
with an index as mentioned at: https://stackoverflow.com/a/1207485/895245
This is more space efficient since it dispenses the array copy, but it is less time efficient, because removal from dynamic arrays requires shifting all following items back by one, which is O(N).
Generally, if you are doing it quick and dirty and don't want to add a custom LinkedList
class, you just want to go for the faster .append()
option by default unless memory is a big concern.
Official Python 2 tutorial 4.2. "for Statements"
https://docs.python.org/2/tutorial/controlflow.html#for-statements
This part of the docs makes it clear that:
[:]
If you need to modify the sequence you are iterating over while inside the loop (for example to duplicate selected items), it is recommended that you first make a copy. Iterating over a sequence does not implicitly make a copy. The slice notation makes this especially convenient:
>>> words = ['cat', 'window', 'defenestrate'] >>> for w in words[:]: # Loop over a slice copy of the entire list. ... if len(w) > 6: ... words.insert(0, w) ... >>> words ['defenestrate', 'cat', 'window', 'defenestrate']
Python 2 documentation 7.3. "The for statement"
https://docs.python.org/2/reference/compound_stmts.html#for
This part of the docs says once again that you have to make a copy, and gives an actual removal example:
Note: There is a subtlety when the sequence is being modified by the loop (this can only occur for mutable sequences, i.e. lists). An internal counter is used to keep track of which item is used next, and this is incremented on each iteration. When this counter has reached the length of the sequence the loop terminates. This means that if the suite deletes the current (or a previous) item from the sequence, the next item will be skipped (since it gets the index of the current item which has already been treated). Likewise, if the suite inserts an item in the sequence before the current item, the current item will be treated again the next time through the loop. This can lead to nasty bugs that can be avoided by making a temporary copy using a slice of the whole sequence, e.g.,
for x in a[:]:
if x < 0: a.remove(x)
However, I disagree with this implementation, since .remove()
has to iterate the entire list to find the value.
Could Python do this better?
It seems like this particular Python API could be improved. Compare it, for instance, with:
std::vector::erase
which returns a valid interator to the element after the one removedboth of which make it crystal clear that you cannot modify a list being iterated except with the iterator itself, and gives you efficient ways to do so without copying the list.
Perhaps the underlying rationale is that Python lists are assumed to be dynamic array backed, and therefore any type of removal will be time inefficient anyways, while Java has a nicer interface hierarchy with both ArrayList
and LinkedList
implementations of ListIterator
.
There doesn't seem to be an explicit linked list type in the Python stdlib either: Python Linked List
If you have multiple databases for testing and development this might help
development:
adapter: mysql2
encoding: utf8
reconnect: false
database: DBNAME
pool: 5
username: usr
password: paswd
shost: localhost
test:
adapter: mysql2
encoding: utf8
reconnect: false
database: DBNAME
pool: 5
username: usr
password: paswd
shost: localhost
production:
adapter: mysql2
encoding: utf8
reconnect: false
database: DBNAME
pool: 5
username: usr
password: paswd
shost: localhost
Using Android Studio newest version
and update Android Plugin to 'newest alpha version`, I can disable Instant Run:
Try to update Android Studio.
def findMaxSales(listoftuples):
newlist = []
tuple = ()
for item in listoftuples:
movie = item[0]
value = (item[1])
tuple = value, movie
newlist += [tuple]
newlist.sort()
highest = newlist[-1]
result = highest[1]
return result
movieList = [("Finding Dory", 486), ("Captain America: Civil
War", 408), ("Deadpool", 363), ("Zootopia", 341), ("Rogue One", 529), ("The Secret Life of Pets", 368), ("Batman v Superman", 330), ("Sing", 268), ("Suicide Squad", 325), ("The Jungle Book", 364)]
print(findMaxSales(movieList))
output --> Rogue One
There are several of this same question (1, 2). One way of doing it is using canvas. Here's a working solution. Here you can see some working examples of using this library.
I prefer to use the @ symbol so I see the query exactly as I can copy and paste into a query file:
string name = "Joe";
string gender = "M";
string query = String.Format(@"
SELECT
*
FROM
tableA
WHERE
Name = '{0}' AND
Gender = '{1}'", name, gender);
It's really great with long complex queries. Nice thing is it keeps tabs and line feeds so pasting into a query browser retains the nice formatting
I suggest this and all the cells for the particular table are effected.
table.tbl_classname td, th {
padding: 5px 5px 5px 4px;
}
In Java, the equals()
method that is inherited from Object
is:
public boolean equals(Object other);
In other words, the parameter must be of type Object
. This is called overriding; your method public boolean equals(Book other)
does what is called overloading to the equals()
method.
The ArrayList
uses overridden equals()
methods to compare contents (e.g. for its contains()
and equals()
methods), not overloaded ones. In most of your code, calling the one that didn't properly override Object
's equals was fine, but not compatible with ArrayList
.
So, not overriding the method correctly can cause problems.
I override equals the following everytime:
@Override
public boolean equals(Object other){
if (other == null) return false;
if (other == this) return true;
if (!(other instanceof MyClass)) return false;
MyClass otherMyClass = (MyClass)other;
...test other properties here...
}
The use of the @Override
annotation can help a ton with silly mistakes.
Use it whenever you think you are overriding a super class' or interface's method. That way, if you do it the wrong way, you will get a compile error.
left: initial
This will also set left
back to the browser default.
But important to know property: initial
is not supported in IE.
npm install jspdf --save
//code on react
import jsPDF from 'jspdf';
var doc = new jsPDF()
doc.fromHTML("<div>JOmin</div>", 1, 1)
onclick //
doc.save("name.pdf")
The conversion of your code to Swift 4 can also be done this way:
let str = "Hello, playground"
let index = str.index(of: ",")!
let substr = str.prefix(upTo: index)
You can use the code below to have a new string:
let newString = String(str.prefix(upTo: index))
This occur due to incompatible java version you are using in android studio and the java version that was used with your imported project.
Go to
File->Project structure->Change jdk 1.7 to jdk 1.8
.After that Go to File->click on Invalidate cache
and Restart.
Hope this helps..
And change the dependency classpath in gradle file
dependencies {
classpath 'com.android.tools.build:gradle:2.2.3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
If you are using ASP.NET Core MVC, the answers above are ever so slightly altered...
In my action method (which returns async Task<JsonResult>
) I add the line (anywhere before the return statement):
Response.Headers.Add("Content-Disposition", $"attachment; filename={myFileName}");
This links might be helpful to convert.
https://code.google.com/p/flying-saucer/
https://today.java.net/pub/a/today/2007/06/26/generating-pdfs-with-flying-saucer-and-itext.html
If it is a college Project, you can even go for these, http://pd4ml.com/examples.htm
Example is given to convert HTML to PDF
Use upper-case HH
for 24h format:
String s = curr.ToString("HH:mm");
SELECT height/10.0 AS HeightDecimal FROM dbo.whatever;
If you want a specific precision scale, then say so:
SELECT CONVERT(DECIMAL(16,4), height/10.0) AS HeightDecimal
FROM dbo.whatever;
Nullable<T>
(or ?
) exposes a HasValue
flag to denote if a value is set or the item is null.
Also, nullable types support ==
:
if (Age == null)
The ??
is the null coalescing operator and doesn't result in a boolean expression, but a value returned:
int i = Age ?? 0;
So for your example:
if (age == null || age == 0)
Or:
if (age.GetValueOrDefault(0) == 0)
Or:
if ((age ?? 0) == 0)
Or ternary:
int i = age.HasValue ? age.Value : 0;
You may try
document.getElementById('name').style.borderColor='#e52213';
document.getElementById('name').style.border='solid';
The specific problem is that you're declaring a new variable instead of assigning to an existing one:
char * ret = new char[strlen(array) + 1 + 1];
^^^^^^ Remove this
and trying to compare string values by comparing pointers:
if (array!="") // Wrong - compares pointer with address of string literal
if (array[0] == 0) // Better - checks for empty string
although there's no need to make that comparison at all; the first branch will do the right thing whether or not the string is empty.
The more general problem is that you're messing around with nasty, error-prone C-style string manipulation in C++. Use std::string
and it will manage all the memory allocation for you:
std::string appendCharToString(std::string const & s, char a) {
return s + a;
}
I changed this:
var htmlText = '<embed width=100% height=100%'
+ ' type="application/pdf"'
+ ' src="data:application/pdf,'
+ escape(pdfText)
+ '"></embed>';
to
var htmlText = '<embed width=100% height=100%'
+ ' type="application/pdf"'
+ ' src="data:application/pdf;base64,'
+ escape(pdfText)
+ '"></embed>';
and it worked for me.
You could encode the binary data using base64 and put it into a Base64 element; the below article is a pretty good one on the subject.
Well there's a problem with the creation of the ContactServiceImpl
bean. First, make sure that the class is actually instantiated by debugging the no-args constructor when the Spring context is initiated and when an instance of ContactController
is created.
If the ContactServiceImpl
is actually instantiated by the Spring context, but it's simply not matched against your @Autowire
annotation, try being more explicit in your annotation injection. Here's a guy dealing with a similar problem as yours and giving some possible solutions:
http://blogs.sourceallies.com/2011/08/spring-injection-with-resource-and-autowired/
If you ask me, I think you'll be ok if you replace
@Autowired
private ContactService contactService;
with:
@Resource
@Qualifier("contactService")
private ContactService contactService;
You first have to 'dot' source the script, so for you :
. .\Get-NetworkStatistics.ps1
The first 'dot' asks PowerShell to load the script file into your PowerShell environment, not to start it. You should also use set-ExecutionPolicy Unrestricted
or set-ExecutionPolicy AllSigned
see(the Execution Policy instructions).
You will have to use some sort of network sniffer if you want to get at this sort of data and you're likely to run into the same problem (pulling out the relevant data from the overall network traffic) with those that you do now with Wireshark.
I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.
Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=D:\test.xls " & _
";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
For i = 0 To rs.Fields.Count - 1
Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
strNaam = rs.Fields(0).Value
Next
rs.MoveNext
Loop
rs.Close
There are other ways, depending on what you want to do, such as GetString (GetString Method Description).
You can do it using Linked Server.
Typically linked servers are configured to enable the Database Engine to execute a Transact-SQL statement that includes tables in another instance of SQL Server, or another database product such as Oracle. Many types OLE DB data sources can be configured as linked servers, including Microsoft Access and Excel.
Linked servers offer the following advantages:
Read more about Linked Servers.
Server Objects -> Linked Servers -> New Linked Server
Provide Remote Server Name.
Select Remote Server Type (SQL Server or Other).
Select Security -> Be made using this security context and provide login and password of remote server.
Click OK and you are done !!
Here is a simple tutorial for creating a linked server.
OR
You can add linked server using query.
Syntax:
sp_addlinkedserver [ @server= ] 'server' [ , [ @srvproduct= ] 'product_name' ]
[ , [ @provider= ] 'provider_name' ]
[ , [ @datasrc= ] 'data_source' ]
[ , [ @location= ] 'location' ]
[ , [ @provstr= ] 'provider_string' ]
[ , [ @catalog= ] 'catalog' ]
Read more about sp_addlinkedserver.
You have to create linked server only once. After creating linked server, we can query it as follows:
select * from LinkedServerName.DatabaseName.OwnerName.TableName
The term for T&&
when used with type deduction (such as for perfect forwarding) is known colloquially as a forwarding reference. The term "universal reference" was coined by Scott Meyers in this article, but was later changed.
That is because it may be either r-value or l-value.
Examples are:
// template
template<class T> foo(T&& t) { ... }
// auto
auto&& t = ...;
// typedef
typedef ... T;
T&& t = ...;
// decltype
decltype(...)&& t = ...;
More discussion can be found in the answer for: Syntax for universal references
I tried this tool and it gave me good results.
A bit shorter with array_diff
$musthave = array('a','b');
$test1 = array('a','b','c');
$test2 = array('a','c');
$containsAllNeeded = 0 == count(array_diff($musthave, $test1));
// this is TRUE
$containsAllNeeded = 0 == count(array_diff($musthave, $test2));
// this is FALSE
Alternative to explicit if
statement
Minimally:
test $? -eq 0 || echo "something bad happened"
Complete:
EXITCODE=$?
test $EXITCODE -eq 0 && echo "something good happened" || echo "something bad happened";
exit $EXITCODE
If you are inheriting from a fragment you can do:
Drawable drawable = getActivity().getDrawable(R.drawable.icon)
You can use the $set syntax if you want to set the value of a document to an arbitrary value. This will either update the value if the attribute already exists on the document or create it if it doesn't. If you need to set a single value in a dictionary like you describe, you can use the dot notation to access child values.
If p is the object retrieved:
existing = p['d']['a']
For pymongo versions < 3.0
db.ProductData.update({
'_id': p['_id']
},{
'$set': {
'd.a': existing + 1
}
}, upsert=False, multi=False)
For pymongo versions >= 3.0
db.ProductData.update_one({
'_id': p['_id']
},{
'$set': {
'd.a': existing + 1
}
}, upsert=False)
However if you just need to increment the value, this approach could introduce issues when multiple requests could be running concurrently. Instead you should use the $inc syntax:
For pymongo versions < 3.0:
db.ProductData.update({
'_id': p['_id']
},{
'$inc': {
'd.a': 1
}
}, upsert=False, multi=False)
For pymongo versions >= 3.0:
db.ProductData.update_one({
'_id': p['_id']
},{
'$inc': {
'd.a': 1
}
}, upsert=False)
This ensures your increments will always happen.
You can specify an empty string as an argument to join, if no argument is specified a comma is used.
arr.join('');
It's too late to answer this question, but it could help for new readers,
It seems version issues. I ran all these tests with spring 4.1.4 and found that the order of @RequestBody
and @RequestParam
doesn't matter.
body= "name=abc"
, and name = "abc"
body ="name=abc"
, name = "xyz,abc"
You can create like this and you can add action also like this....
import UIKit
let myButton = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!)
{ super.init(nibName: nibName, bundle: nibBundle)
myButton.targetForAction("tappedButton:", withSender: self)
}
func tappedButton(sender: UIButton!)
{
println("tapped button")
}
It's of use for everything that has to scale according to the font size.
It's especially useful on browsers which implement zoom by scaling the font size. So if you size all your elements using em
they scale accordingly.
#import <sys/socket.h>
#import <net/if_dl.h>
#import <ifaddrs.h>
#import <sys/xattr.h>
#define IFT_ETHER 0x6
...
- (NSString*)macAddress
{
NSString* result = nil;
char* macAddressString = (char*)malloc(18);
if (macAddressString != NULL)
{
strcpy(macAddressString, "");
struct ifaddrs* addrs = NULL;
struct ifaddrs* cursor;
if (getifaddrs(&addrs) == 0)
{
cursor = addrs;
while (cursor != NULL)
{
if ((cursor->ifa_addr->sa_family == AF_LINK) && (((const struct sockaddr_dl*)cursor->ifa_addr)->sdl_type == IFT_ETHER) && strcmp("en0", cursor->ifa_name) == 0)
{
const struct sockaddr_dl* dlAddr = (const struct sockaddr_dl*) cursor->ifa_addr;
const unsigned char* base = (const unsigned char*)&dlAddr->sdl_data[dlAddr->sdl_nlen];
for (NSInteger index = 0; index < dlAddr->sdl_alen; index++)
{
char partialAddr[3];
sprintf(partialAddr, "%02X", base[index]);
strcat(macAddressString, partialAddr);
}
}
cursor = cursor->ifa_next;
}
}
result = [[[NSString alloc] initWithUTF8String:macAddressString] autorelease];
free(macAddressString);
}
return result;
}
When you change attribute value like mentioned above the change
event is not triggered so if needed for some reasons you can trigger it like so
$('input[name=video_radio][value="' + r.data.video_radio + '"]')
.prop('checked', true)
.trigger('change');
Steps I did:
Init cookies as being NOT http-only in server-side app.'s:
app.configure(function(){
//a bunch of stuff
app.use(express.cookieSession({secret: 'mySecret', store: store, cookie: cookieSettings}));```
Then in client-side services.jss I put ['ngCookies'] in like this:
angular.module('swrp', ['ngCookies']).//etc
Then in controller.js
, in my function UserLoginCtrl
, I have $cookies
in there with $scope
at the top like so:
function UserLoginCtrl($scope, $cookies, socket) {
Lastly, to get the value of a cookie inside the controller function I did:
var mySession = $cookies['connect.sess'];
Now you can send that back to the server from the client. Awesome. Wish they would've put this in the Angular.js documentation. I figured it out by just reading the actual code for angular-cookies.js directly.
Android SharedPreferances allow you to save primitive types (Boolean, Float, Int, Long, String and StringSet which available since API11) in memory as an xml file.
The key idea of any solution would be to convert the data to one of those primitive types.
I personally love to convert the my list to json format and then save it as a String in a SharedPreferences value.
In order to use my solution you'll have to add Google Gson lib.
In gradle just add the following dependency (please use google's latest version):
compile 'com.google.code.gson:gson:2.6.2'
Save data (where HttpParam is your object):
List<HttpParam> httpParamList = "**get your list**"
String httpParamJSONList = new Gson().toJson(httpParamList);
SharedPreferences prefs = getSharedPreferences(**"your_prefes_key"**, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(**"your_prefes_key"**, httpParamJSONList);
editor.apply();
Retrieve Data (where HttpParam is your object):
SharedPreferences prefs = getSharedPreferences(**"your_prefes_key"**, Context.MODE_PRIVATE);
String httpParamJSONList = prefs.getString(**"your_prefes_key"**, "");
List<HttpParam> httpParamList =
new Gson().fromJson(httpParamJSONList, new TypeToken<List<HttpParam>>() {
}.getType());
I had a similar problem to solve, here is a simple solution of how to pass variables to template files, the trick is to write the template file taking advantage of the variable. You need to create a dictionary (list is also possible), which holds the set of variables corresponding to each of the file. Then within the template file access them.
see below:
the template file: test_file.j2
# {{ ansible_managed }} created by [email protected]
{% set dkey = (item | splitext)[0] %}
{% set fname = test_vars[dkey].name %}
{% set fip = test_vars[dkey].ip %}
{% set fport = test_vars[dkey].port %}
filename: {{ fname }}
ip address: {{ fip }}
port: {{ fport }}
the playbook
---
#
# file: template_test.yml
# author: [email protected]
#
# description: playbook to demonstrate passing variables to template files
#
# this playbook will create 3 files from a single template, with different
# variables passed for each of the invocation
#
# usage:
# ansible-playbook -i "localhost," template_test.yml
- name: template variables testing
hosts: all
gather_facts: false
vars:
ansible_connection: local
dest_dir: "/tmp/ansible_template_test/"
test_files:
- file_01.txt
- file_02.txt
- file_03.txt
test_vars:
file_01:
name: file_01.txt
ip: 10.0.0.1
port: 8001
file_02:
name: file_02.txt
ip: 10.0.0.2
port: 8002
file_03:
name: file_03.txt
ip: 10.0.0.3
port: 8003
tasks:
- name: copy the files
template:
src: test_file.j2
dest: "{{ dest_dir }}/{{ item }}"
with_items:
- "{{ test_files }}"
If netstat doesn't show anything, try a reboot.
For me, nothing appeared in netstat for my port. I tried closing Google Chrome browser windows as @Clangon and @J.T. Taylor suggested, but to no avail.
In the end a system reboot worked, however, so I can only assume that something else was secretly holding the port open. Or perhaps it just took longer than I was prepared to wait for the ports to be released after Chrome shut down.
In a class you might call it like this:
public static string GetIPAddress(HttpRequestBase request)
{
string ip;
try
{
ip = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ip))
{
if (ip.IndexOf(",") > 0)
{
string[] ipRange = ip.Split(',');
int le = ipRange.Length - 1;
ip = ipRange[le];
}
} else
{
ip = request.UserHostAddress;
}
} catch { ip = null; }
return ip;
}
I used this in a razor app with great results.
Variable interpolation does not happen in single quotes. You need to use double quotes as:
$i = 1
echo "<p class=\"paragraph$i\"></p>";
++i;
"Objects" are NEVER passed in C# -- "objects" are not values in the language. The only types in the language are primitive types, struct types, etc. and reference types. No "object types".
The types Object
, MyClass
, etc. are reference types. Their values are "references" -- pointers to objects. Objects can only be manipulated through references -- when you do new
on them, you get a reference, the .
operator operates on a reference; etc. There is no way to get a variable whose value "is" an object, because there are no object types.
All types, including reference types, can be passed by value or by reference. A parameter is passed by reference if it has a keyword like ref
or out
. The SetObject
method's obj
parameter (which is of a reference type) does not have such a keyword, so it is passed by value -- the reference is passed by value.
For portability, one should probably use std::signal
from the standard C++ library, but there is a lot of restriction on what a signal handler can do. Unfortunately, it is not possible to catch a SIGSEGV from within a C++ program without introducing undefined behavior because the specification says:
abort
, exit
, some atomic functions, reinstall current signal handler, memcpy
, memmove
, type traits, `std::move, std::forward
, and some more).throw
expression.This proves that it is impossible to catch SIGSEGV from within a program using strictly standard and portable C++. SIGSEGV is still caught by the operating system and is normally reported to the parent process when a wait family function is called.
You will probably run into the same kind of trouble using POSIX signal because there is a clause that says in 2.4.3 Signal Actions:
The behavior of a process is undefined after it returns normally from a signal-catching function for a SIGBUS, SIGFPE, SIGILL, or SIGSEGV signal that was not generated by
kill()
,sigqueue()
, orraise()
.
A word about the longjump
s. Assuming we are using POSIX signals, using longjump
to simulate stack unwinding won't help:
Although
longjmp()
is an async-signal-safe function, if it is invoked from a signal handler which interrupted a non-async-signal-safe function or equivalent (such as the processing equivalent toexit()
performed after a return from the initial call tomain()
), the behavior of any subsequent call to a non-async-signal-safe function or equivalent is undefined.
This means that the continuation invoked by the call to longjump cannot reliably call usually useful library function such as printf
, malloc
or exit
or return from main without inducing undefined behavior. As such, the continuation can only do a restricted operations and may only exit through some abnormal termination mechanism.
To put things short, catching a SIGSEGV and resuming execution of the program in a portable is probably infeasible without introducing UB. Even if you are working on a Windows platform for which you have access to Structured exception handling, it is worth mentioning that MSDN suggest to never attempt to handle hardware exceptions: Hardware Exceptions.
At last but not least, whether any SIGSEGV would be raised when dereferencing a null valued pointer (or invalid valued pointer) is not a requirement from the standard. Because indirection through a null valued pointer or any invalid valued pointer is an undefined behaviour, which means the compiler assumes your code will never attempt such a thing at runtime, the compiler is free to make code transformation that would elide such undefined behavior. For example, from cppreference,
int foo(int* p) {
int x = *p;
if(!p)
return x; // Either UB above or this branch is never taken
else
return 0;
}
int main() {
int* p = nullptr;
std::cout << foo(p);
}
Here the true path of the if
could be completely elided by the compiler as an optimization; only the else
part could be kept. Said otherwise, the compiler infers foo()
will never receive a null valued pointer at runtime since it would lead to an undefined behaviour. Invoking it with a null valued pointer, you may observe the value 0
printed to standard output and no crash, you may observe a crash with SIGSEG, in fact you could observe anything since no sensible requirements are imposed on programs that are not free of undefined behaviors.
Objects can be converted to a string using the toString()
method:
String myString = myIntegerObject.toString();
There is no such rule about casting. For casting to work, the object must actually be of the type you're casting to.
If you install WAMPServer before you install the C++ Redistributable, it won't work even after you've installed it because you will miss a critical step in the installation where you tell Windows Firewall to let Apache run.
unins
file in the wamp directoryI got this error for multi-threading scenario (specifically when dealing with ZMQ). It turned out that socket was still being connected on one thread while another thread already started sending data. The events that occured due to another thread tried to access variables that weren't created yet. If your scenario involves multi-threading and if things work if you add bit of delay then you might have similar issue.
You can use style
property for this. For example, if you want to change border -
document.elm.style.border = "3px solid #FF0000";
similarly for color -
document.getElementById("p2").style.color="blue";
Best thing is you define a class and do this -
document.getElementById("p2").className = "classname";
(Cross Browser artifacts must be considered accordingly).
Use the default javascript string replace function
var curInnerHTML = document.body.innerHTML;
curInnerHTML = curInnerHTML.replace("hello", "hi");
document.body.innerHTML = curInnerHTML;
I want to update the answer for exception handling in Psr-7 Guzzle, Guzzle7 and HTTPClient(expressive, minimal API around the Guzzle HTTP client provided by laravel).
Using RequestException, RequestException catches any exception that can be thrown while transferring requests.
try{
$client = new \GuzzleHttp\Client(['headers' => ['Authorization' => 'Bearer ' . $token]]);
$guzzleResponse = $client->get('/foobar');
// or can use
// $guzzleResponse = $client->request('GET', '/foobar')
if ($guzzleResponse->getStatusCode() == 200) {
$response = json_decode($guzzleResponse->getBody(),true);
//perform your action with $response
}
}
catch(\GuzzleHttp\Exception\RequestException $e){
// you can catch here 400 response errors and 500 response errors
// You can either use logs here use Illuminate\Support\Facades\Log;
$error['error'] = $e->getMessage();
$error['request'] = $e->getRequest();
if($e->hasResponse()){
if ($e->getResponse()->getStatusCode() == '400'){
$error['response'] = $e->getResponse();
}
}
Log::error('Error occurred in get request.', ['error' => $error]);
}catch(Exception $e){
//other errors
}
use GuzzleHttp\Psr7;
use GuzzleHttp\Exception\RequestException;
try {
$client->request('GET', '/foo');
} catch (RequestException $e) {
$error['error'] = $e->getMessage();
$error['request'] = Psr7\Message::toString($e->getRequest());
if ($e->hasResponse()) {
$error['response'] = Psr7\Message::toString($e->getResponse());
}
Log::error('Error occurred in get request.', ['error' => $error]);
}
use Illuminate\Support\Facades\Http;
try{
$response = Http::get('http://api.foo.com');
if($response->successful()){
$reply = $response->json();
}
if($response->failed()){
if($response->clientError()){
//catch all 400 exceptions
Log::debug('client Error occurred in get request.');
$response->throw();
}
if($response->serverError()){
//catch all 500 exceptions
Log::debug('server Error occurred in get request.');
$response->throw();
}
}
}catch(Exception $e){
//catch the exception here
}
Inline Stored procedure we using as per our need. Example like different Same parameter with different values we have to use in queries..
Create Proc SP1
(
@ID int,
@Name varchar(40)
-- etc parameter list, If you don't have any parameter then no need to pass.
)
AS
BEGIN
-- Here we have some opereations
-- If there is any Error Before Executing SP2 then SP will stop executing.
Exec SP2 @ID,@Name,@SomeID OUTPUT
-- ,etc some other parameter also we can use OutPut parameters like
-- @SomeID is useful for some other operations for condition checking insertion etc.
-- If you have any Error in you SP2 then also it will stop executing.
-- If you want to do any other operation after executing SP2 that we can do here.
END
Sometimes I need to import large xlsx files into database, so I use spreadsheet-reader
as it can read file per-row. It is very memory-efficient way to import.
<?php
// If you need to parse XLS files, include php-excel-reader
require('php-excel-reader/excel_reader2.php');
require('SpreadsheetReader.php');
$Reader = new SpreadsheetReader('example.xlsx');
// insert every row just after reading it
foreach ($Reader as $row)
{
$db->insert($row);
}
?>
Came across this old thread searching for a similar solution myself and found the accepted answer to be using .complete()
method of jquery ajax
. I quote the notice on jquery website here:
The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
To know the status code
of a ajax response, one can use the following code:
$.ajax( url [, settings ] )
.always(function (jqXHR) {
console.log(jqXHR.status);
});
Works similarily for .done()
and .fail()
From git 2.10 upwards it is also possible to use the gitconfig sshCommand setting. Docs state :
If this variable is set, git fetch and git push will use the specified command instead of ssh when they need to connect to a remote system. The command is in the same form as the GIT_SSH_COMMAND environment variable and is overridden when the environment variable is set.
An usage example would be: git config core.sshCommand "ssh -i ~/.ssh/[insert_your_keyname]
In some cases this doesn't work because ssh_config overriding the command, in this case try ssh -i ~/.ssh/[insert_your_keyname] -F /dev/null
to not use the ssh_config.
Just looking at the message it sounds like one or more of the components that you reference, or one or more of their dependencies is not registered properly.
If you know which component it is you can use regsvr32.exe to register it, just open a command prompt, go to the directory where the component is and type regsvr32 filename.dll
(assuming it's a dll), if it works, try to run the code again otherwise come back here with the error.
If you don't know which component it is, try re-installing/repairing the GIS software (I assume you've installed some GIS software that includes the component you're trying to use).
From SQL Server 2008 Setup, you have to select "Client Tools Connectivity" to install SQL Server Configuration Manager.
I have done quite a bit of what you're talking about, and SOAP interoperability between platforms has one cardinal rule: CONTRACT FIRST. Do not derive your WSDL from code and then try to generate a client on a different platform. Anything more than "Hello World" type functions will very likely fail to generate code, fail to talk at runtime or (my favorite) fail to properly send or receive all of the data without raising an error.
That said, WSDL is complicated, nasty stuff and I avoid writing it from scratch whenever possible. Here are some guidelines for reliable interop of services (using Web References, WCF, Axis2/Java, WS02, Ruby, Python, whatever):
</rant>
:)
If you extend the base SimpleXMLElement class, you can use this method:
class MyXML extends SimpleXMLElement {
public function find($xpath) {
$tmp = $this->xpath($xpath);
return isset($tmp[0])? $tmp[0]: null;
}
public function remove() {
$dom = dom_import_simplexml($this);
return $dom->parentNode->removeChild($dom);
}
}
// Example: removing the <bar> element with id = 1
$foo = new MyXML('<foo><bar id="1"/><bar id="2"/></foo>');
$foo->find('//bar[@id="1"]')->remove();
print $foo->asXML(); // <foo><bar id="2"/></foo>
You need to be aware that Excel is very sensitive to the culture you are running under as well.
You may find that you need to set the culture to EN-US before calling Excel functions. This does not apply to all functions - but some of them.
CultureInfo en_US = new System.Globalization.CultureInfo("en-US");
System.Threading.Thread.CurrentThread.CurrentCulture = en_US;
string filePathLocal = _applicationObject.ActiveWorkbook.Path;
System.Threading.Thread.CurrentThread.CurrentCulture = orgCulture;
This applies even if you are using VSTO.
For details: http://support.microsoft.com/default.aspx?scid=kb;en-us;Q320369
thanks to Punit S answer, for detecting dynamic connection speed change, you can use the following code :
navigator.connection.onchange = function () {
//do what you need to do ,on speed change event
console.log('Connection Speed Changed');
}
You might set location
directly because it's slightly shorter. If you're trying to be terse, you can usually omit the window.
too.
URL assignments to both location.href
and location
are defined to work in JavaScript 1.0, back in Netscape 2, and have been implemented in every browser since. So take your pick and use whichever you find clearest.
It seems none of the current answers will actually remove 100% of whitespace from the start and end of a string.
As mentioned in other posts, the default TRIM
only removes spaces - not tabs, formfeeds etc. A combination of TRIM
s specifying other whitespace characters may provide a limited improvement e.g. TRIM(BOTH '\r' FROM TRIM(BOTH '\n' FROM TRIM(BOTH '\f' FROM TRIM(BOTH '\t' FROM TRIM(txt)))))
. But the problem with this approach is only a single character can be specified for a particular TRIM
and those characters are only removed from the start and end. So if the string being trimmed is something like \t \t \t \t
(i.e. alternate spaces and tab characters), more TRIM
s would be needed - and in the general case this could go on indefinitely.
For a lightweight solution, it should be possible to write a simple User Defined Function (UDF) to do the job by looping through the characters at the start and end of a string. But I'm not going to do that... as I've already written a rather more heavyweight regular expression replacer which can also do the job - and may come in useful for other reasons, as described in this blog post.
Demo
Rextester online demo. In particular, the last row shows the other methods failing but the regular expression method succeeding.
Function:
-- ------------------------------------------------------------------------------------
-- USAGE
-- ------------------------------------------------------------------------------------
-- SELECT reg_replace(<subject>,
-- <pattern>,
-- <replacement>,
-- <greedy>,
-- <minMatchLen>,
-- <maxMatchLen>);
-- where:
-- <subject> is the string to look in for doing the replacements
-- <pattern> is the regular expression to match against
-- <replacement> is the replacement string
-- <greedy> is TRUE for greedy matching or FALSE for non-greedy matching
-- <minMatchLen> specifies the minimum match length
-- <maxMatchLen> specifies the maximum match length
-- (minMatchLen and maxMatchLen are used to improve efficiency but are
-- optional and can be set to 0 or NULL if not known/required)
-- Example:
-- SELECT reg_replace(txt, '^[Tt][^ ]* ', 'a', TRUE, 2, 0) FROM tbl;
DROP FUNCTION IF EXISTS reg_replace;
CREATE FUNCTION reg_replace(subject VARCHAR(21845), pattern VARCHAR(21845),
replacement VARCHAR(21845), greedy BOOLEAN, minMatchLen INT, maxMatchLen INT)
RETURNS VARCHAR(21845) DETERMINISTIC BEGIN
DECLARE result, subStr, usePattern VARCHAR(21845);
DECLARE startPos, prevStartPos, startInc, len, lenInc INT;
IF subject REGEXP pattern THEN
SET result = '';
-- Sanitize input parameter values
SET minMatchLen = IF(minMatchLen < 1, 1, minMatchLen);
SET maxMatchLen = IF(maxMatchLen < 1 OR maxMatchLen > CHAR_LENGTH(subject),
CHAR_LENGTH(subject), maxMatchLen);
-- Set the pattern to use to match an entire string rather than part of a string
SET usePattern = IF (LEFT(pattern, 1) = '^', pattern, CONCAT('^', pattern));
SET usePattern = IF (RIGHT(pattern, 1) = '$', usePattern, CONCAT(usePattern, '$'));
-- Set start position to 1 if pattern starts with ^ or doesn't end with $.
IF LEFT(pattern, 1) = '^' OR RIGHT(pattern, 1) <> '$' THEN
SET startPos = 1, startInc = 1;
-- Otherwise (i.e. pattern ends with $ but doesn't start with ^): Set start position
-- to the min or max match length from the end (depending on "greedy" flag).
ELSEIF greedy THEN
SET startPos = CHAR_LENGTH(subject) - maxMatchLen + 1, startInc = 1;
ELSE
SET startPos = CHAR_LENGTH(subject) - minMatchLen + 1, startInc = -1;
END IF;
WHILE startPos >= 1 AND startPos <= CHAR_LENGTH(subject)
AND startPos + minMatchLen - 1 <= CHAR_LENGTH(subject)
AND !(LEFT(pattern, 1) = '^' AND startPos <> 1)
AND !(RIGHT(pattern, 1) = '$'
AND startPos + maxMatchLen - 1 < CHAR_LENGTH(subject)) DO
-- Set start length to maximum if matching greedily or pattern ends with $.
-- Otherwise set starting length to the minimum match length.
IF greedy OR RIGHT(pattern, 1) = '$' THEN
SET len = LEAST(CHAR_LENGTH(subject) - startPos + 1, maxMatchLen), lenInc = -1;
ELSE
SET len = minMatchLen, lenInc = 1;
END IF;
SET prevStartPos = startPos;
lenLoop: WHILE len >= 1 AND len <= maxMatchLen
AND startPos + len - 1 <= CHAR_LENGTH(subject)
AND !(RIGHT(pattern, 1) = '$'
AND startPos + len - 1 <> CHAR_LENGTH(subject)) DO
SET subStr = SUBSTRING(subject, startPos, len);
IF subStr REGEXP usePattern THEN
SET result = IF(startInc = 1,
CONCAT(result, replacement), CONCAT(replacement, result));
SET startPos = startPos + startInc * len;
LEAVE lenLoop;
END IF;
SET len = len + lenInc;
END WHILE;
IF (startPos = prevStartPos) THEN
SET result = IF(startInc = 1, CONCAT(result, SUBSTRING(subject, startPos, 1)),
CONCAT(SUBSTRING(subject, startPos, 1), result));
SET startPos = startPos + startInc;
END IF;
END WHILE;
IF startInc = 1 AND startPos <= CHAR_LENGTH(subject) THEN
SET result = CONCAT(result, RIGHT(subject, CHAR_LENGTH(subject) + 1 - startPos));
ELSEIF startInc = -1 AND startPos >= 1 THEN
SET result = CONCAT(LEFT(subject, startPos), result);
END IF;
ELSE
SET result = subject;
END IF;
RETURN result;
END;
DROP FUNCTION IF EXISTS format_result;
CREATE FUNCTION format_result(result VARCHAR(21845))
RETURNS VARCHAR(21845) DETERMINISTIC BEGIN
RETURN CONCAT(CONCAT('|', REPLACE(REPLACE(REPLACE(REPLACE(result, '\t', '\\t'), CHAR(12), '\\f'), '\r', '\\r'), '\n', '\\n')), '|');
END;
DROP TABLE IF EXISTS tbl;
CREATE TABLE tbl
AS
SELECT 'Afghanistan' AS txt
UNION ALL
SELECT ' AF' AS txt
UNION ALL
SELECT ' Cayman Islands ' AS txt
UNION ALL
SELECT CONCAT(CONCAT(CONCAT('\t \t ', CHAR(12)), ' \r\n\t British Virgin Islands \t \t ', CHAR(12)), ' \r\n') AS txt;
SELECT format_result(txt) AS txt,
format_result(TRIM(txt)) AS trim,
format_result(TRIM(BOTH '\r' FROM TRIM(BOTH '\n' FROM TRIM(BOTH '\f' FROM TRIM(BOTH '\t' FROM TRIM(txt))))))
AS `trim spaces, tabs, formfeeds and line endings`,
format_result(reg_replace(reg_replace(txt, '^[[:space:]]+', '', TRUE, 1, 0), '[[:space:]]+$', '', TRUE, 1, 0))
AS `reg_replace`
FROM tbl;
Usage:
SELECT reg_replace(
reg_replace(txt,
'^[[:space:]]+',
'',
TRUE,
1,
0),
'[[:space:]]+$',
'',
TRUE,
1,
0) AS `trimmed txt`
FROM tbl;
One major difference between Sequelize and Persistence.js is that the former supports a STRING
datatype, i.e. VARCHAR(255)
. I felt really uncomfortable making everything TEXT
.
dissect the URL code and unicode error. this symbol came to me as well on google translate in the armenian text and sometimes the broken burmese.
EXIT_FAILURE
, either in a return statement in main
or as an argument to exit()
, is the only portable way to indicate failure in a C or C++ program. exit(1)
can actually signal successful termination on VMS, for example.
If you're going to be using EXIT_FAILURE
when your program fails, then you might as well use EXIT_SUCCESS
when it succeeds, just for the sake of symmetry.
On the other hand, if the program never signals failure, you can use either 0
or EXIT_SUCCESS
. Both are guaranteed by the standard to signal successful completion. (It's barely possible that EXIT_SUCCESS
could have a value other than 0, but it's equal to 0 on every implementation I've ever heard of.)
Using 0
has the minor advantage that you don't need #include <stdlib.h>
in C, or #include <cstdlib>
in C++ (if you're using a return
statement rather than calling exit()
) -- but for a program of any significant size you're going to be including stdlib directly or indirectly anyway.
For that matter, in C starting with the 1999 standard, and in all versions of C++, reaching the end of main()
does an implicit return 0;
anyway, so you might not need to use either 0
or EXIT_SUCCESS
explicitly. (But at least in C, I consider an explicit return 0;
to be better style.)
(Somebody asked about OpenVMS. I haven't used it in a long time, but as I recall odd status values generally denote success while even values denote failure. The C implementation maps 0
to 1
, so that return 0;
indicates successful termination. Other values are passed unchanged, so return 1;
also indicates successful termination. EXIT_FAILURE
would have a non-zero even value.)
--- Shameless plug ---
I have added this function to a library I created
vanillajs-browser-helpers: https://github.com/Tokimon/vanillajs-browser-helpers/blob/master/inView.js
-------------------------------
Well BenM stated, you need to detect the height of the viewport + the scroll position to match up with your top position. The function you are using is ok and does the job, though its a bit more complex than it needs to be.
If you don't use jQuery
then the script would be something like this:
function posY(elm) {
var test = elm, top = 0;
while(!!test && test.tagName.toLowerCase() !== "body") {
top += test.offsetTop;
test = test.offsetParent;
}
return top;
}
function viewPortHeight() {
var de = document.documentElement;
if(!!window.innerWidth)
{ return window.innerHeight; }
else if( de && !isNaN(de.clientHeight) )
{ return de.clientHeight; }
return 0;
}
function scrollY() {
if( window.pageYOffset ) { return window.pageYOffset; }
return Math.max(document.documentElement.scrollTop, document.body.scrollTop);
}
function checkvisible( elm ) {
var vpH = viewPortHeight(), // Viewport Height
st = scrollY(), // Scroll Top
y = posY(elm);
return (y > (vpH + st));
}
Using jQuery is a lot easier:
function checkVisible( elm, evalType ) {
evalType = evalType || "visible";
var vpH = $(window).height(), // Viewport Height
st = $(window).scrollTop(), // Scroll Top
y = $(elm).offset().top,
elementHeight = $(elm).height();
if (evalType === "visible") return ((y < (vpH + st)) && (y > (st - elementHeight)));
if (evalType === "above") return ((y < (vpH + st)));
}
This even offers a second parameter. With "visible" (or no second parameter) it strictly checks whether an element is on screen. If it is set to "above" it will return true when the element in question is on or above the screen.
See in action: http://jsfiddle.net/RJX5N/2/
I hope this answers your question.
-- IMPROVED VERSION--
This is a lot shorter and should do it as well:
function checkVisible(elm) {
var rect = elm.getBoundingClientRect();
var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
return !(rect.bottom < 0 || rect.top - viewHeight >= 0);
}
with a fiddle to prove it: http://jsfiddle.net/t2L274ty/1/
And a version with threshold
and mode
included:
function checkVisible(elm, threshold, mode) {
threshold = threshold || 0;
mode = mode || 'visible';
var rect = elm.getBoundingClientRect();
var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
var above = rect.bottom - threshold < 0;
var below = rect.top - viewHeight + threshold >= 0;
return mode === 'above' ? above : (mode === 'below' ? below : !above && !below);
}
and with a fiddle to prove it: http://jsfiddle.net/t2L274ty/2/
You can use the LIKE operator to compare the content of a T-SQL string, e.g.
SELECT * FROM [table] WHERE [field] LIKE '%stringtosearchfor%'.
The percent character '%' is a wild card- in this case it says return any records where [field] at least contains the value "stringtosearchfor".
I've just jumped into the same issue and I solved it substituting 'button' tag to 'span' tag. In my case I'm using bootstrap. This is how it looks like:
<a href="#register">
<span class="btn btn-default btn-lg">
Subscribe
</span>
</a>
In my case, it's because a trigger is triggered before a insert cause, (actually it means to split a big table in several tables using timestamp), and then return null. So I met this problem when I used springboot jpa save() function.
In addition to change the trigger to SET NOCOUNT ON;
Mr. TA mentioned above, the solution can also be using native query.
insert into table values(nextval('table_id_seq'), value1)
You may need to provide some more details for a more precise response.
Since your dataset seems kind of narrow, you might consider just using a row per result and performing the post-processing at the client.
So if you are really looking to make the server do the work return a result set like
ID Name SomeColumn
1 ABC X
1 ABC Y
1 ABC Z
2 MNO R
2 MNO S
which of course is a simple INNER JOIN on ID
Once you have the resultset back at the client, maintain a variable called CurrentName and use that as a trigger when to stop collecting SomeColumn into the useful thing you want it to do.
edit/update:
Xcode 8 or later • Swift 3 or later
var secondsFromGMT: Int { return TimeZone.current.secondsFromGMT() }
secondsFromGMT // -7200
if you need the abbreviation:
var localTimeZoneAbbreviation: String { return TimeZone.current.abbreviation() ?? "" }
localTimeZoneAbbreviation // "GMT-2"
if you need the timezone identifier:
var localTimeZoneIdentifier: String { return TimeZone.current.identifier }
localTimeZoneIdentifier // "America/Sao_Paulo"
To know all timezones abbreviations available:
var timeZoneAbbreviations: [String:String] { return TimeZone.abbreviationDictionary }
timeZoneAbbreviations // ["CEST": "Europe/Paris", "WEST": "Europe/Lisbon", "CDT": "America/Chicago", "EET": "Europe/Istanbul", "BRST": "America/Sao_Paulo", "EEST": "Europe/Istanbul", "CET": "Europe/Paris", "MSD": "Europe/Moscow", "MST": "America/Denver", "KST": "Asia/Seoul", "PET": "America/Lima", "NZDT": "Pacific/Auckland", "CLT": "America/Santiago", "HST": "Pacific/Honolulu", "MDT": "America/Denver", "NZST": "Pacific/Auckland", "COT": "America/Bogota", "CST": "America/Chicago", "SGT": "Asia/Singapore", "CAT": "Africa/Harare", "BRT": "America/Sao_Paulo", "WET": "Europe/Lisbon", "IST": "Asia/Calcutta", "HKT": "Asia/Hong_Kong", "GST": "Asia/Dubai", "EDT": "America/New_York", "WIT": "Asia/Jakarta", "UTC": "UTC", "JST": "Asia/Tokyo", "IRST": "Asia/Tehran", "PHT": "Asia/Manila", "AKDT": "America/Juneau", "BST": "Europe/London", "PST": "America/Los_Angeles", "ART": "America/Argentina/Buenos_Aires", "PDT": "America/Los_Angeles", "WAT": "Africa/Lagos", "EST": "America/New_York", "BDT": "Asia/Dhaka", "CLST": "America/Santiago", "AKST": "America/Juneau", "ADT": "America/Halifax", "AST": "America/Halifax", "PKT": "Asia/Karachi", "GMT": "GMT", "ICT": "Asia/Bangkok", "MSK": "Europe/Moscow", "EAT": "Africa/Addis_Ababa"]
To know all timezones names (identifiers) available:
var timeZoneIdentifiers: [String] { return TimeZone.knownTimeZoneIdentifiers }
timeZoneIdentifiers // ["Africa/Abidjan", "Africa/Accra", "Africa/Addis_Ababa", "Africa/Algiers", "Africa/Asmara", "Africa/Bamako", "Africa/Bangui", "Africa/Banjul", "Africa/Bissau", "Africa/Blantyre", "Africa/Brazzaville", "Africa/Bujumbura", "Africa/Cairo", "Africa/Casablanca", "Africa/Ceuta", "Africa/Conakry", "Africa/Dakar", "Africa/Dar_es_Salaam", "Africa/Djibouti", "Africa/Douala", "Africa/El_Aaiun", "Africa/Freetown", "Africa/Gaborone", "Africa/Harare", "Africa/Johannesburg", "Africa/Juba", "Africa/Kampala", "Africa/Khartoum", "Africa/Kigali", "Africa/Kinshasa", "Africa/Lagos", "Africa/Libreville", "Africa/Lome", "Africa/Luanda", "Africa/Lubumbashi", "Africa/Lusaka", "Africa/Malabo", "Africa/Maputo", "Africa/Maseru", "Africa/Mbabane", "Africa/Mogadishu", "Africa/Monrovia", "Africa/Nairobi", "Africa/Ndjamena", "Africa/Niamey", "Africa/Nouakchott", "Africa/Ouagadougou", "Africa/Porto-Novo", "Africa/Sao_Tome", "Africa/Tripoli", "Africa/Tunis", "Africa/Windhoek", "America/Adak", "America/Anchorage", "America/Anguilla", "America/Antigua", "America/Araguaina", "America/Argentina/Buenos_Aires", "America/Argentina/Catamarca", "America/Argentina/Cordoba", "America/Argentina/Jujuy", "America/Argentina/La_Rioja", "America/Argentina/Mendoza", "America/Argentina/Rio_Gallegos", "America/Argentina/Salta", "America/Argentina/San_Juan", "America/Argentina/San_Luis", "America/Argentina/Tucuman", "America/Argentina/Ushuaia", "America/Aruba", "America/Asuncion", "America/Atikokan", "America/Bahia", "America/Bahia_Banderas", "America/Barbados", "America/Belem", "America/Belize", "America/Blanc-Sablon", "America/Boa_Vista", "America/Bogota", …, "Pacific/Marquesas", "Pacific/Midway", "Pacific/Nauru", "Pacific/Niue", "Pacific/Norfolk", "Pacific/Noumea", "Pacific/Pago_Pago", "Pacific/Palau", "Pacific/Pitcairn", "Pacific/Pohnpei", "Pacific/Ponape", "Pacific/Port_Moresby", "Pacific/Rarotonga", "Pacific/Saipan", "Pacific/Tahiti", "Pacific/Tarawa", "Pacific/Tongatapu", "Pacific/Truk", "Pacific/Wake", "Pacific/Wallis"]
There is a few other info you may need:
var isDaylightSavingTime: Bool { return TimeZone.current.isDaylightSavingTime(for: Date()) }
print(isDaylightSavingTime) // true (in effect)
var daylightSavingTimeOffset: TimeInterval { return TimeZone.current.daylightSavingTimeOffset() }
print(daylightSavingTimeOffset) // 3600 seconds (1 hour - daylight savings time)
var nextDaylightSavingTimeTransition: Date? { return TimeZone.current.nextDaylightSavingTimeTransition } // "Feb 18, 2017, 11:00 PM"
print(nextDaylightSavingTimeTransition?.description(with: .current) ?? "none")
nextDaylightSavingTimeTransition // "Saturday, February 18, 2017 at 11:00:00 PM Brasilia Standard Time\n"
var nextDaylightSavingTimeTransitionAfterNext: Date? {
guard
let nextDaylightSavingTimeTransition = nextDaylightSavingTimeTransition
else { return nil }
return TimeZone.current.nextDaylightSavingTimeTransition(after: nextDaylightSavingTimeTransition)
}
nextDaylightSavingTimeTransitionAfterNext // "Oct 15, 2017, 1:00 AM"
Please put your related value and try this :
declare @x int, @y varchar(200),
@dt1 smalldatetime = '2014-01-21 10:00:00',
@dt2 smalldatetime = getdate()
set @x = datediff (HOUR, @dt1, @dt2)
set @y = @x * 60 - DATEDIFF(minute,@dt1, @dt2)
set @y = cast(@x as varchar(200)) + ':' + @y
Select @y
You'll need to couple the event listener to $rootScope in Angular 1.x, but you should probably future proof your code a bit by not storing the value of the previous location on $rootScope. A better place to store the value would be a service:
var app = angular.module('myApp', [])
.service('locationHistoryService', function(){
return {
previousLocation: null,
store: function(location){
this.previousLocation = location;
},
get: function(){
return this.previousLocation;
}
})
.run(['$rootScope', 'locationHistoryService', function($location, locationHistoryService){
$rootScope.$on('$locationChangeSuccess', function(e, newLocation, oldLocation){
locationHistoryService.store(oldLocation);
});
}]);
From MSDN: SqlCommand.ExecuteNonQuery Method
You can use the ExecuteNonQuery to perform catalog operations (for example, querying the structure of a database or creating database objects such as tables), or to change the data in a database without using a DataSet by executing UPDATE, INSERT, or DELETE statements.
Although the ExecuteNonQuery returns no rows, any output parameters or return values mapped to parameters are populated with data.
For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.
You are using SELECT query, thus you get -1
Faced same issue on Ubuntu 16LTS when tensor flow was installed over existing python installation.
Workaround: 1.)Uninstall tensorflow from pip and pip3
sudo pip uninstall tensorflow
sudo pip3 uninstall tensorflow
2.)Uninstall python & python3
sudo apt-get remove python-dev python3-dev python-pip python3-pip
3.)Install only a single version of python(I used python 3)
sudo apt-get install python3-dev python3-pip
4.)Install tensorflow to python3
sudo pip3 install --upgrade pip
for non GPU tensorflow, run this command
sudo pip3 install --upgrade tensorflow
for GPU tensorflow, run below command
sudo pip3 install --upgrade tensorflow-gpu
Suggest not to install GPU and vanilla version of tensorflow
You might need to be logged in as postgres
in order to have full privileges on databases.
su - postgres
psql -l # will list all databases on Postgres cluster
pg_dump/pg_restore
pg_dump -U username -f backup.dump database_name -Fc
switch -F
specify format of backup file:
c
will use custom PostgreSQL format which is compressed and results in smallest backup file sized
for directory where each file is one tablet
for TAR archive (bigger than custom format)-h
/--host
Specifies the host name of the machine on which the server is running-W
/--password
Force pg_dump
to prompt for a password before connecting to a database restore backup:
pg_restore -d database_name -U username -C backup.dump
Parameter -C
should create database before importing data. If it doesn't work you can always create database eg. with command (as user postgres
or other account that has rights to create databases) createdb db_name -O owner
pg_dump/psql
In case that you didn't specify the argument -F
default plain text SQL format was used (or with -F p
). Then you can't use pg_restore
. You can import data with psql
.
backup:
pg_dump -U username -f backup.sql database_name
restore:
psql -d database_name -f backup.sql
I believe the sprintf is the right function for you. I's in the standard library, like printf. Follow the link below for more information:
You can create a putty session, and auto load the script on the server, when starting the session:
putty -load "sessionName"
At remote command, point to the remote script.
Option 1: Using Windows PowerShell
Open the windows menu. Type: "PowerShell" and open the 'Windows PowerShell' command window.
Goto folder with desired files: e.g. cd "C:\house chores" Notice: address must incorporate quotes "" if there are spaces involved.
You can use 'dir' to see all the files in the folder. Using '|' will pipeline the output of 'dir' for the command that follows.
Notes: 'dir' is an alias of 'Get-ChildItem'. See: wiki: cmdlets. One can provide further functionality. e.g. 'dir -recurse' outputs all the files, folders and sub-folders.
What if I only want a range of files?
Instead of 'dir |' I can use:
dir | where-object -filterscript {($_.Name -ge 'DSC_20') -and ($_.Name -le 'DSC_31')} |
For batch-renaming with the directory name as a prefix:
dir | Rename-Item -NewName {$_.Directory.Name + " - " + $_.Name}
Option 2: Using Command Prompt
In the folder press shift+right-click : select 'open command-window here'
for %a in (*.*) do ren "%a" "prefix - %a"
If there are a lot of files, it might be good to add an '@echo off' command before this and an 'echo on' command at the end.
I often use a github starter project, like this (it uses babel)
If I understand your question correctly, you are asking how you can create class level constants (static - in C++ parlance) such that you don't a) replicate the overhead in every instance, and b have to recompute what is otherwise constant.
The language has evolved - as every reader knows, but as I test this in Xcode 6.3.1, the solution is:
import Swift
class MyClass {
static let testStr = "test"
static let testStrLen = count(testStr)
init() {
println("There are \(MyClass.testStrLen) characters in \(MyClass.testStr)")
}
}
let a = MyClass()
// -> There are 4 characters in test
I don't know if the static is strictly necessary as the compiler surely only adds only one entry per const variable into the static section of the binary, but it does affect syntax and access. By using static, you can refer to it even when you don't have an instance: MyClass.testStrLen
.
How about using _.find(collection, [predicate=_.identity], [fromIndex=0])
of lo-dash to get object from array of objects by object property value. You could do something like this:
var o = _.find(jsObjects, {'b': 6});
Arguments:
collection (Array|Object): The collection to inspect.
[predicate=_.identity] (Function): The function invoked per iteration.
[fromIndex=0] (number): The index to search from.
Returns
(*): Returns the matched element (in your case, {a: 5, b: 6}), else undefined.
In terms of performance, _.find()
is faster as it only pulls the first object with property {'b': 6}
, on the other hand, if suppose your array contains multiple objects with matching set of properties (key:value), then you should consider using _.filter()
method. So in your case, as your array has a single object with this property, I would use _.find()
.
In [5]: set(df.Col1).union(set(df.Col2))
Out[5]: {'Bill', 'Bob', 'Joe', 'Mary', 'Steve'}
Or:
set(df.Col1) | set(df.Col2)
Recaptcha contact form 7 and Recaptcha v3 solution.
body:not(.page-id-20) .grecaptcha-badge {
display: none;
}
More Than One Contact Form Page?
body:not(.page-id-12):not(.page-id-43) .grecaptcha-badge {
display: none;
}
You can add more “nots” if you have more contact form pages.
body:not(.page-id-45):not(.page-id-78):not(.page-id-98) .grecaptcha-badge {
display: none;
}
Make sure that your body section will like this:
<body>
Change it so that it looks like this:
<body <?php body_class(); ?>>
du
does not follow symlinks by default. No answer here make use of follow_symlinks=False
.
Here is an implementation which follows default behavior of du:
def du(path) -> int:
total = 0
for entry in os.scandir(path):
if entry.is_file(follow_symlinks=False):
total += entry.stat().st_size
elif entry.is_dir(follow_symlinks=False):
total += du(entry.path)
return total
Test:
class Test(unittest.TestCase):
def test_du(self):
root = '/tmp/du_test'
subprocess.run(['rm', '-rf', root])
test_utils.mkdir(root)
test_utils.create_file(root, 'A', '1M')
test_utils.create_file(root, 'B', '1M')
sub = '/'.join([root, 'sub'])
test_utils.mkdir(sub)
test_utils.create_file(sub, 'C', '1M')
test_utils.create_file(sub, 'D', '1M')
subprocess.run(['ln', '-s', '/tmp', '/'.join([root, 'link']), ])
self.assertEqual(4 << 20, util.du(root))
strSearch in this case is probably null (not simply empty).
Try using
String.IsNullOrEmpty(strSearch)
if you are just trying to determine if the string doesn't have any contents.
On centos and fedora work with fsadm
fsadm resize /dev/vg_name/root
If someone happens to be as moronic as me, the following worked.
Old folder structure:
awesome_code.py
__init__.py
src/
__init__.py
stuff1.py
stuff2.py
New structure:
awesome_code.py
src/
__init__.py
stuff1.py
stuff2.py
There are overloads of ActionLink which take a fragment parameter. Passing "section12" as your fragment will get you the behavior you're after.
For example, calling LinkExtensions.ActionLink Method (HtmlHelper, String, String, String, String, String, String, Object, Object):
<%= Html.ActionLink("Link Text", "Action", "Controller", null, null, "section12-the-anchor", new { categoryid = "blah"}, null) %>
The error shows you either didn't create the rails project yet or you're not in the rails project directory.
Suppose if you're working on myapp project. You've to move to that project directory on your command line and then generate the model. Here are some steps you can refer.
Example: Assuming you didn't create the Rails app yet:
$> rails new myapp
$> cd myapp
Now generate the model from your commandline.
$> rails generate model your_model_name
If you are a windows user:
make sure you added the script(dir) path to environment variables
C:\Python34\Scripts
for more how to set path vist
android:targetSdkVersion="20"
it should be < 21
.
Do you want to wait for them to finish? If so, use the Join method.
There is also the isAlive property if you just want to check it.
var label = $('#current_month');
var month = label.val('month');
var year = label.val('year');
var text = label.text();
alert(text);
<label year="2010" month="6" id="current_month"> June 2010</label>
You will not be able to retrieve a plain text password from wordpress.
Wordpress use a 1 way encryption to store the passwords using a variation of md5. There is no way to reverse this.
See this article for more info http://wordpress.org/support/topic/how-is-the-user-password-encrypted-wp_hash_password
Assuming you wanted to do this synchronously, using the WebClient.OpenRead(...) method and setting the timeout on the Stream that it returns will give you the desired result:
using (var webClient = new WebClient())
using (var stream = webClient.OpenRead(streamingUri))
{
if (stream != null)
{
stream.ReadTimeout = Timeout.Infinite;
using (var reader = new StreamReader(stream, Encoding.UTF8, false))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (line != String.Empty)
{
Console.WriteLine("Count {0}", count++);
}
Console.WriteLine(line);
}
}
}
}
Deriving from WebClient and overriding GetWebRequest(...) to set the timeout @Beniamin suggested, didn't work for me as, but this did.
Modify your class definition to read like this:
exports.User = function (socket) {
...
};
Then rename the file to user.js
. Assuming it's in the root directory of your main script, you can include it like this:
var user = require('./user');
var someUser = new user.User();
That's the quick and dirty version. Read about CommonJS Modules if you'd like to learn more.
Try this bit:
input type="button"
data-bind="css:{on:toggleButton, off:toggleButton!=true},value:toggleButton,click: function() { $data.toggleButton(!($data.toggleButton()))}" />
in viewModel
self.toggleButton = ko.observable(false);
You can add the event using the Event API like Tristan outlined and you can also add a Google Calendar event which shows up in the iOS calendar.
using Google's API Objective-C Client
- (void)addAnEvent {
// Make a new event, and show it to the user to edit
GTLCalendarEvent *newEvent = [GTLCalendarEvent object];
newEvent.summary = @"Sample Added Event";
newEvent.descriptionProperty = @"Description of sample added event";
// We'll set the start time to now, and the end time to an hour from now,
// with a reminder 10 minutes before
NSDate *anHourFromNow = [NSDate dateWithTimeIntervalSinceNow:60*60];
GTLDateTime *startDateTime = [GTLDateTime dateTimeWithDate:[NSDate date]
timeZone:[NSTimeZone systemTimeZone]];
GTLDateTime *endDateTime = [GTLDateTime dateTimeWithDate:anHourFromNow
timeZone:[NSTimeZone systemTimeZone]];
newEvent.start = [GTLCalendarEventDateTime object];
newEvent.start.dateTime = startDateTime;
newEvent.end = [GTLCalendarEventDateTime object];
newEvent.end.dateTime = endDateTime;
GTLCalendarEventReminder *reminder = [GTLCalendarEventReminder object];
reminder.minutes = [NSNumber numberWithInteger:10];
reminder.method = @"email";
newEvent.reminders = [GTLCalendarEventReminders object];
newEvent.reminders.overrides = [NSArray arrayWithObject:reminder];
newEvent.reminders.useDefault = [NSNumber numberWithBool:NO];
// Display the event edit dialog
EditEventWindowController *controller = [[[EditEventWindowController alloc] init] autorelease];
[controller runModalForWindow:[self window]
event:newEvent
completionHandler:^(NSInteger returnCode, GTLCalendarEvent *event) {
// Callback
if (returnCode == NSOKButton) {
[self addEvent:event];
}
}];
}
in your location block you can do:
location / {
try_files $uri $uri/index.html;
}
which will tell ngingx to look for a file with the exact name given first, and if none such file is found it will try uri/index.html. So if a request for https://www.example.com/ comes it it would look for an exact file match first, and not finding that would then check for index.html
You can use double quotes instead of single quotes:
theAnchorText = "I'm home";
Alternatively, escape the apostrophe:
theAnchorText = 'I\'m home';
The backslash tells JavaScript (this has nothing to do with jQuery, by the way) that the next character should be interpreted as "special". In this case, an apostrophe after a backslash means to use a literal apostrophe but not to end the string.
There are also other characters you can put after a backslash to indicate other special characters. For example, you can use \n
for a new line, or \t
for a tab.
If you have your text in your_text
variable, you can use:
your_text[0..29]
If you have a DataFrame with only one row, then access the first (only) row as a Series using iloc
, and then the value using the column name:
In [3]: sub_df
Out[3]:
A B
2 -0.133653 -0.030854
In [4]: sub_df.iloc[0]
Out[4]:
A -0.133653
B -0.030854
Name: 2, dtype: float64
In [5]: sub_df.iloc[0]['A']
Out[5]: -0.13365288513107493
Yes, you can connect the raspberry direct to your PC without router. For this is necessary that the raspberry and your computer are on the same subnet, and they both have a static ip configured (And an Ethernet cable connected between the two devices).
An ideal configuration would be the following:
Raspberry on eth0: IP: 192.168.1.10 SubNet: 255.255.255.0
Your PC: IP: 192.168.1.11 SubNet 255.255.255.0
To set a manual IP on raspberry you can follow this guide
In your PC you can set a manual IP in the network adapter settings,and the procedure depends on your operating system.
When you have configured the two static IP, you can connect to the raspberry via SSH using the IP set (192.168.1.10).
Another simpler method is to attach on GPIO a button to turn off the raspberry! Take a look here!
I'd like to promote factory methods for creating helpers for functional APIs:
Optional<R> result = things.stream()
.flatMap(streamopt(this::resolve))
.findFirst();
The factory method:
<T, R> Function<T, Stream<R>> streamopt(Function<T, Optional<R>> f) {
return f.andThen(Optional::stream); // or the J8 alternative:
// return t -> f.apply(t).map(Stream::of).orElseGet(Stream::empty);
}
Reasoning:
As with method references in general, compared to lambda expressions, you can't accidentaly capture a variable from the accessible scope, like:
t -> streamopt(resolve(o))
It's composable, you can e.g. call Function::andThen
on the factory method result:
streamopt(this::resolve).andThen(...)
Whereas in the case of a lambda, you'd need to cast it first:
((Function<T, Stream<R>>) t -> streamopt(resolve(t))).andThen(...)
Type Services.msc in run panel of windows run window. It will list all the windows services in our system. Now we need to start Asp .net State service as show in the image.
Your issue will get resolved.
Maybe you can run ./gradlew build -s
in the terminal, the stacktrace would show you where went wrong.
Simply removing libstdc++-6.dll.a \ libstdc++.dll.a from the mingw directory fixes this.
I tried using the flag -static-libstdc++ but this did not work for me. I found the solution in: http://ghc.haskell.org/trac/ghc/ticket/4468#
Usually that problem is that in the last iteration you have an empty object or undefine object. use console.log() inside you cicle to check that this doent happend.
Sometimes a prototype in some place add an extra element.
With jquery :
$("#reset").on("click", function() {
$('#my_select').val($('#my_select').find('option[selected="selected"]').val());
}
Actually, the correct solution is:
composer require vendor/package
Taken from the CLI documentation for Composer:
The
require
command adds new packages to thecomposer.json
file from the current directory.
php composer.phar require
After adding/changing the requirements, the modified requirements will be installed or updated.
If you do not want to choose requirements interactively, you can just pass them to the command.
php composer.phar require vendor/package:2.* vendor/package2:dev-master
While it is true that composer update
installs new packages found in composer.json, it will also update the composer.lock file and any installed packages according to any fuzzy logic (>
or *
chars after the colons) found in composer.json! This can be avoided by using composer update vendor/package
, but I wouldn't recommend making a habit of it, as you're one forgotten argument away from a potentially broken project…
Keep things sane and stick with composer require vendor/package
for adding new dependencies!
This is working for me:
$user_info = DB::table('usermetas')
->select('browser', DB::raw('count(*) as total'))
->groupBy('browser')
->get();
When you have changes on your working copy, from command line do:
git stash
This will stash your changes and clear your status report
git pull
This will pull changes from upstream branch. Make sure it says fast-forward in the report. If it doesn't, you are probably doing an unintended merge
git stash pop
This will apply stashed changes back to working copy and remove the changes from stash unless you have conflicts. In the case of conflict, they will stay in stash so you can start over if needed.
if you need to see what is in your stash
git stash list
While the Java language does not directly support operator overloading, you can use the Manifold compiler plugin in any Java project to enable it. It supports Java 8 - 13 (the current Java version) and is fully supported in IntelliJ IDEA.
You can run with:
java -cp .;app.jar package.MainClass
It works for me if there is no manifest in the JAR file.
The solution I came up with is:
This way the compiler will give you a warning for any method in the protocol that isn't implemented by your child class.
It's not as succinct as in Java, but you do get the desired compiler warning.
In Netbeans 8.2
1. Dowload the binaries from the web source. The Apache Commos are in: [http://commons.apache.org/components.html][1] In this case, you must select the "Logging" in the Components menu and follow the link to downloads in the Releases part. Direct URL: [http://commons.apache.org/proper/commons-logging/download_logging.cgi][2] For me, the correct download was the file: commons-logging-1.2-bin.zip from the Binaries.
2. Unzip downloaded content. Now, you can see several jar files inside the directory created from the zip file.
3. Add the library to the project. Right click in the project, select Properties and click in Libraries (in the left side). Click the button "Add Jar/Folder". Go to the previously unzipped contents and select the properly jar file. Clic in "Open" and click in"Ok". The library has been loaded!
FIDDLE: https://jsfiddle.net/1ytxfcwx/
NPM: https://www.npmjs.com/package/typescript-string-operations
GITHUB: https://github.com/sevensc/typescript-string-operations
I implemented a class for String. Its not perfect but it works for me.
use it i.e. like this:
var getFullName = function(salutation, lastname, firstname) {
return String.Format('{0} {1:U} {2:L}', salutation, lastname, firstname)
}
export class String {
public static Empty: string = "";
public static isNullOrWhiteSpace(value: string): boolean {
try {
if (value == null || value == 'undefined')
return false;
return value.replace(/\s/g, '').length < 1;
}
catch (e) {
return false;
}
}
public static Format(value, ...args): string {
try {
return value.replace(/{(\d+(:.*)?)}/g, function (match, i) {
var s = match.split(':');
if (s.length > 1) {
i = i[0];
match = s[1].replace('}', '');
}
var arg = String.formatPattern(match, args[i]);
return typeof arg != 'undefined' && arg != null ? arg : String.Empty;
});
}
catch (e) {
return String.Empty;
}
}
private static formatPattern(match, arg): string {
switch (match) {
case 'L':
arg = arg.toLowerCase();
break;
case 'U':
arg = arg.toUpperCase();
break;
default:
break;
}
return arg;
}
}
EDIT:
I extended the class and created a repository on github. It would be great if you can help to improve it!
https://github.com/sevensc/typescript-string-operations
or download the npm package
from string import rstrip
with open('bvc.txt') as f:
alist = map(rstrip, f)
Nota Bene: rstrip()
removes the whitespaces, that is to say : \f
, \n
, \r
, \t
, \v
, \x
and blank ,
but I suppose you're only interested to keep the significant characters in the lines. Then, mere map(strip, f)
will fit better, removing the heading whitespaces too.
If you really want to eliminate only the NL \n
and RF \r
symbols, do:
with open('bvc.txt') as f:
alist = f.read().splitlines()
splitlines() without argument passed doesn't keep the NL and RF symbols (Windows records the files with NLRF at the end of lines, at least on my machine) but keeps the other whitespaces, notably the blanks and tabs.
.
with open('bvc.txt') as f:
alist = f.read().splitlines(True)
has the same effect as
with open('bvc.txt') as f:
alist = f.readlines()
that is to say the NL and RF are kept
This works fine for me:
while True:
answer = input('Do you want to continue?:')
if answer.lower().startswith("y"):
print("ok, carry on then")
elif answer.lower().startswith("n"):
print("sayonara, Robocop")
exit()
edit: use input
in python 3.2 instead of raw_input
I just added class="span2"
to the <li>
for the dropdown items and that worked.
This function returns the column letter for a given column number.
Function Col_Letter(lngCol As Long) As String
Dim vArr
vArr = Split(Cells(1, lngCol).Address(True, False), "$")
Col_Letter = vArr(0)
End Function
testing code for column 100
Sub Test()
MsgBox Col_Letter(100)
End Sub
One way, making the preprocessor do the work. It also ensures your enums and strings are in sync.
#define FOREACH_FRUIT(FRUIT) \
FRUIT(apple) \
FRUIT(orange) \
FRUIT(grape) \
FRUIT(banana) \
#define GENERATE_ENUM(ENUM) ENUM,
#define GENERATE_STRING(STRING) #STRING,
enum FRUIT_ENUM {
FOREACH_FRUIT(GENERATE_ENUM)
};
static const char *FRUIT_STRING[] = {
FOREACH_FRUIT(GENERATE_STRING)
};
After the preprocessor gets done, you'll have:
enum FRUIT_ENUM {
apple, orange, grape, banana,
};
static const char *FRUIT_STRING[] = {
"apple", "orange", "grape", "banana",
};
Then you could do something like:
printf("enum apple as a string: %s\n",FRUIT_STRING[apple]);
If the use case is literally just printing the enum name, add the following macros:
#define str(x) #x
#define xstr(x) str(x)
Then do:
printf("enum apple as a string: %s\n", xstr(apple));
In this case, it may seem like the two-level macro is superfluous, however, due to how stringification works in C, it is necessary in some cases. For example, let's say we want to use a #define with an enum:
#define foo apple
int main() {
printf("%s\n", str(foo));
printf("%s\n", xstr(foo));
}
The output would be:
foo
apple
This is because str will stringify the input foo rather than expand it to be apple. By using xstr the macro expansion is done first, then that result is stringified.
See Stringification for more information.
I'm guessing you've taken a look at mod_perl?
Have you tried the following tutorial?
EDIT: In relation to your posting - perhaps you could include a sample of the code inside your .cgi
file. Perhaps even the first few lines?
This is what I tried for a right outer join [as per my requirement]:
m1 <- merge(x=companies, y=rounds2, by.x=companies$permalink,
by.y=rounds2$company_permalink, all.y=TRUE)
# Error in fix.by(by.x, x) : 'by' must specify uniquely valid columns
m1 <- merge(x=companies, y=rounds2, by.x=c("permalink"),
by.y=c("company_permalink"), all.y=TRUE)
This worked.
On a fresh ubuntu docker image, run
apt-get update
apt-get install net-tools
These can be executed by logging into the docker container or add this to your dockerfile to build an image with the same.
The semantically correct character is the Interpunct, also known as middle dot, as HTML entity
·
Example
Home · Photos · About
You could also use the bullet point character, as HTML entity
•
Example
Home • Photos • About
Yes we can check the length of queue object created from collections.
from collections import deque
class Queue():
def __init__(self,batchSize=32):
#self.batchSie = batchSize
self._queue = deque(maxlen=batchSize)
def enqueue(self, items):
''' Appending the items to the queue'''
self._queue.append(items)
def dequeue(self):
'''remoe the items from the top if the queue becomes full '''
return self._queue.popleft()
Creating an object of class
q = Queue(batchSize=64)
q.enqueue([1,2])
q.enqueue([2,3])
q.enqueue([1,4])
q.enqueue([1,22])
Now retrieving the length of the queue
#check the len of queue
print(len(q._queue))
#you can print the content of the queue
print(q._queue)
#Can check the content of the queue
print(q.dequeue())
#Check the length of retrieved item
print(len(q.dequeue()))
check the results in attached screen shot
Hope this helps...
If you're not wanting to save changes set savechanges to false
Sub CloseBook2()
ActiveWorkbook.Close savechanges:=False
End Sub
for more examples, http://support.microsoft.com/kb/213428 and i believe in the past I've just used
ActiveWorkbook.Close False
adb shell
su
mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system
This assumes your /system is yaffs2 and that it's at /dev/block/mtdblock3 the easier/better way to do this on most Android phones is:
adb shell
su
mount -o remount,rw /system
Done. This just says remount /system read-write, you don't have to specify filesystem or mount location.
Can't you implement your own timeout system?
Keep a sorted list, or better yet a priority heap as Heath suggests, of timeout events. In your select or poll calls use the timeout value from the top of the timeout list. When that timeout arrives, do that action attached to that timeout.
That action could be closing a socket that hasn't connected yet.
C is not object oriented programming (OOP) language. So you can not use properties in OOP. Eg. There is no .length property in C. So you need to use loops for your task.
Yes, it can be done as long as both windows are on the same domain. The window.open() function will return a handle to the new window. The child window can access the parent window using the DOM element "opener".
Not sure if it will fix your particular issue but worth sharing anyway.
I had issues with twitter boot strap in IE. No rounded corners. Navigation menu not collapsing. Spans not sitting in correct location, even some images not displaying.
Strangely, site works okay in IE when run through visual studio debugger, its once deployed to a server that the problem occurs.
Try using IE developer tools (F12 is keyboard shortcut) Check your browser mode and document mode. (its at the top along side the menu bar)
Problem happened for me as document was IE7 and browser was IE10 compatibility. I added a http header in IIS: Name X-UA-Compatible Value IE=EmulateIE9
Now the page loads as document - IE9 standards, browser IE10 compatibility and all the previous issues are resolved.
Hope this helps.
-tessi
Works for me:
std::wstring CStringToWString(const CString& s)
{
std::string s2;
s2 = std::string((LPCTSTR)s);
return std::wstring(s2.begin(),s2.end());
}
CString WStringToCString(std::wstring s)
{
std::string s2;
s2 = std::string(s.begin(),s.end());
return s2.c_str();
}
Yes, as was already noted by Jeffrey Bosboom (Sorry Jeffrey, I hadn't noticed your comment when I answered), there is such a function: Math.negateExact.
and
No, you probably shouldn't be using it. Not unless you need a method reference.
OK, I discovered that you need to either avoid checking the "Git Credential Manager" checkbox during the Git for Windows installer, or (after installation) run the Bash shell as Administrator and use git config --edit --system
to remove the helper = manager
line so that it is no longer registered as a credential helper.
For bonus points, use git config --edit --global
and insert:
[core]
askpass =
To disable the OpenSSH credentials popup too.
<View style={{flexDirection:'row'}}> <Text style={{ flex: number }}> You miss fdddddd dddddddd You miss fdd </Text> </View>
{ flex: aNumber } is all you need!
Just set 'flex' to a number that suit for you. And then the text will wrap.
A simplified version of the accepted answer (third point), just worked for me.
function run_cmd(cmd, args, callBack ) {
var spawn = require('child_process').spawn;
var child = spawn(cmd, args);
var resp = "";
child.stdout.on('data', function (buffer) { resp += buffer.toString() });
child.stdout.on('end', function() { callBack (resp) });
} // ()
Usage:
run_cmd( "ls", ["-l"], function(text) { console.log (text) });
run_cmd( "hostname", [], function(text) { console.log (text) });
I didn't want to wrap my *ngFor
into another div
with *ngIf
or use [ngClass]
, so I created a pipe named show
:
show.pipe.ts
export class ShowPipe implements PipeTransform {
transform(values: any[], show: boolean): any[] {
if (!show) {
return[];
}
return values;
}
}
any.page.html
<table>
<tr *ngFor="let arr of anyArray | show : ngIfCondition">
<td>{{arr.label}}</td>
</tr>
</table>
Setting a min-width on child elements will also create a breakpoint. For example breaking every 3 elements,
flex-grow: 1;
min-width: 33%;
If there are 4 elements, this will have the 4th element wrap taking the full 100%. If there are 5 elements, the 4th and 5th elements will wrap and take each 50%.
Make sure to have parent element with,
flex-wrap: wrap
This approach works for me in Node.js, Is there any problem with this one?
File 'include.js':
fs = require('fs');
File 'main.js':
require('./include.js');
fs.readFile('./file.json', function (err, data) {
if (err) {
console.log('ERROR: file.json not found...')
} else {
contents = JSON.parse(data)
};
})
Are you running a 64 bit system with the database running 32 bit but the console running 64 bit? There are no MS Access drivers that run 64 bit and would report an error identical to the one your reported.
Here's one suggestion:
public interface Service<T,U> {
T executeService(U... args);
}
public class MyService implements Service<String, Integer> {
@Override
public String executeService(Integer... args) {
// do stuff
return null;
}
}
Because of type erasure any class will only be able to implement one of these. This eliminates the redundant method at least.
It's not an unreasonable interface that you're proposing but I'm not 100% sure of what value it adds either. You might just want to use the standard Callable
interface. It doesn't support arguments but that part of the interface has the least value (imho).
Unix shells operate a series of transformations on each line of input before executing them. For most shells it looks something like this (taken from the bash
manpage):
Using $cmd
directly gets it replaced by your command during the parameter expansion phase, and it then undergoes all following transformations.
Using eval "$cmd"
does nothing until the quote removal phase, where $cmd
is returned as is, and passed as a parameter to eval
, whose function is to run the whole chain again before executing.
So basically, they're the same in most cases, and differ when your command makes use of the transformation steps up to parameter expansion. For example, using brace expansion:
$ cmd="echo foo{bar,baz}"
$ $cmd
foo{bar,baz}
$ eval "$cmd"
foobar foobaz
in your sample code you must remove the brackets, because it's not a functional assignment; also for documentary reasons I would suggest you use the :=
notation (see code sample below)
Application.Thisworkbook
refers to the book containing the VBA code, not necessarily the book containing the data, so be cautious.Express the sheet you're working on as a sheet object and pass it, together with a logical variable to the following sub:
Sub SetProtectionMode(MySheet As Worksheet, ProtectionMode As Boolean)
If ProtectionMode Then
MySheet.Protect DrawingObjects:=True, Contents:=True, _
AllowSorting:=True, AllowFiltering:=True
Else
MySheet.Unprotect
End If
End Sub
Within the .Protect
method you can define what you want to allow/disallow. This code block will switch protection on/off - without password in this example, you can add it as a parameter or hardcoded within the Sub. Anyway somewhere the PW will be hardcoded. If you don't want this, just call the Protection Dialog window and let the user decide what to do:
Application.Dialogs(xlDialogProtectDocument).Show
Hope that helps
Good luck - MikeD
There is no "colon" operator, but the colon appears in two places:
1: In the ternary operator, e.g.:
int x = bigInt ? 10000 : 50;
In this case, the ternary operator acts as an 'if' for expressions. If bigInt is true, then x will get 10000 assigned to it. If not, 50. The colon here means "else".
2: In a for-each loop:
double[] vals = new double[100];
//fill x with values
for (double x : vals) {
//do something with x
}
This sets x to each of the values in 'vals' in turn. So if vals contains [10, 20.3, 30, ...], then x will be 10 on the first iteration, 20.3 on the second, etc.
Note: I say it's not an operator because it's just syntax. It can't appear in any given expression by itself, and it's just chance that both the for-each and the ternary operator use a colon.
Use the System.Web.UI.HtmlTextWriter class.
StringWriter writer = new StringWriter();
HtmlTextWriter html = new HtmlTextWriter(writer);
html.RenderBeginTag(HtmlTextWriterTag.H1);
html.WriteEncodedText("Heading Here");
html.RenderEndTag();
html.WriteEncodedText(String.Format("Dear {0}", userName));
html.WriteBreak();
html.RenderBeginTag(HtmlTextWriterTag.P);
html.WriteEncodedText("First part of the email body goes here");
html.RenderEndTag();
html.Flush();
string htmlString = writer.ToString();
For extensive HTML that includes the creation of style attributes HtmlTextWriter is probably the best way to go. However it can be a bit clunky to use and some developers like the markup itself to be easily read but perversly HtmlTextWriter's choices with regard indentation is a bit wierd.
In this example you can also use XmlTextWriter quite effectively:-
writer = new StringWriter();
XmlTextWriter xml = new XmlTextWriter(writer);
xml.Formatting = Formatting.Indented;
xml.WriteElementString("h1", "Heading Here");
xml.WriteString(String.Format("Dear {0}", userName));
xml.WriteStartElement("br");
xml.WriteEndElement();
xml.WriteElementString("p", "First part of the email body goes here");
xml.Flush();
we can simply use in.next().charAt(0); to assign + - * / operations as characters by initializing operation as a char.
import java.util.*; public class Calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char operation;
int num1;
int num2;
System.out.println("Enter First Number");
num1 = in.nextInt();
System.out.println("Enter Operation");
operation = in.next().charAt(0);
System.out.println("Enter Second Number");
num2 = in.nextInt();
if (operation == '+')//make sure single quotes
{
System.out.println("your answer is " + (num1 + num2));
}
if (operation == '-')
{
System.out.println("your answer is " + (num1 - num2));
}
if (operation == '/')
{
System.out.println("your answer is " + (num1 / num2));
}
if (operation == '*')
{
System.out.println("your answer is " + (num1 * num2));
}
}
}
If you are on RHEL and want a Red Hat supported Python, use Red Hat Software collections (RHSCL). The EPEL and IUS packages are not supported by Red Hat. Also many of the answers above point to the CentOS software collections. While you can install those, they aren't the Red Hat supported packages for RHEL.
Also, the top voted answer gives bad advice - On RHEL you do not want to change /usr/bin/python
, /usr/bin/python2
because you will likely break yum
and other RHEL admin tools. Take a look at /bin/yum
, it is a Python script that starts with #!/usr/bin/python
. If you compile Python from source, do not do a make install
as root. That will overwrite /usr/bin/python
. If you break yum
it can be difficult to restore your system.
For more info, see How to install Python 3, pip, venv, virtualenv, and pipenv on RHEL on developers.redhat.com. It covers installing and using Python 3 from RHSCL, using Python Virtual Environments, and a number of tips for working with software collections and working with Python on RHEL.
In a nutshell, to install Python 3.6 via Red Hat Software Collections:
$ su -
# subscription-manager repos --enable rhel-7-server-optional-rpms \
--enable rhel-server-rhscl-7-rpms
# yum -y install @development
# yum -y install rh-python36
# yum -y install rh-python36-numpy \
rh-python36-scipy \
rh-python36-python-tools \
rh-python36-python-six
To use a software collection you have to enable it:
scl enable rh-python36 bash
However if you want Python 3 permanently enabled, you can add the following to your ~/.bashrc and then log out and back in again. Now Python 3 is permanently in your path.
# Add RHSCL Python 3 to my login environment
source scl_source enable rh-python36
Note: once you do that, typing python
now gives you Python 3.6 instead of Python 2.7.
See the above article for all of this and a lot more detail.
There is no magic method that will do what you want. The answer is simply name it appropriately. asdict
is a reasonable choice for a plain conversion to dict
, inspired primarily by namedtuple
. However, your method will obviously contain special logic that might not be immediately obvious from that name; you are returning only a subset of the class' state. If you can come up with with a slightly more verbose name that communicates the concepts clearly, all the better.
Other answers suggest using __iter__
, but unless your object is truly iterable (represents a series of elements), this really makes little sense and constitutes an awkward abuse of the method. The fact that you want to filter out some of the class' state makes this approach even more dubious.
The problem with asking this question is that you'll get so many subjective answers that simply state "I prefer this...". Instead of making such pointless statements, I'll try to answer this question with facts and references, rather than personal opinions.
Through experience, we can probably start by excluding the do-while alternatives (and the goto), as they are not commonly used. I can't recall ever seeing them in live production code, written by professionals.
The while(1)
, while(true)
and for(;;)
are the 3 different versions commonly existing in real code. They are of course completely equivalent and results in the same machine code.
for(;;)
This is the original, canonical example of an eternal loop. In the ancient C bible The C Programming Language by Kernighan and Ritchie, we can read that:
K&R 2nd ed 3.5:
for (;;) {
...
}
is an "infinite" loop, presumably to be broken by other means, such as a break or return. Whether to use while or for is largely a matter of personal preference.
For a long while (but not forever), this book was regarded as canon and the very definition of the C language. Since K&R decided to show an example of for(;;)
, this would have been regarded as the most correct form at least up until the C standardization in 1990.
However, K&R themselves already stated that it was a matter of preference.
And today, K&R is a very questionable source to use as a canonical C reference. Not only is it outdated several times over (not addressing C99 nor C11), it also preaches programming practices that are often regarded as bad or blatantly dangerous in modern C programming.
But despite K&R being a questionable source, this historical aspect seems to be the strongest argument in favour of the for(;;)
.
The argument against the for(;;)
loop is that it is somewhat obscure and unreadable. To understand what the code does, you must know the following rule from the standard:
ISO 9899:2011 6.8.5.3:
for ( clause-1 ; expression-2 ; expression-3 ) statement
/--/
Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a nonzero constant.
Based on this text from the standard, I think most will agree that it is not only obscure, it is subtle as well, since the 1st and 3rd part of the for loop are treated differently than the 2nd, when omitted.
while(1)
This is supposedly a more readable form than for(;;)
. However, it relies on another obscure, although well-known rule, namely that C treats all non-zero expressions as boolean logical true. Every C programmer is aware of that, so it is not likely a big issue.
There is one big, practical problem with this form, namely that compilers tend to give a warning for it: "condition is always true" or similar. That is a good warning, of a kind which you really don't want to disable, because it is useful for finding various bugs. For example a bug such as while(i = 1)
, when the programmer intended to write while(i == 1)
.
Also, external static code analysers are likely to whine about "condition is always true".
while(true)
To make while(1)
even more readable, some use while(true)
instead. The consensus among programmers seem to be that this is the most readable form.
However, this form has the same problem as while(1)
, as described above: "condition is always true" warnings.
When it comes to C, this form has another disadvantage, namely that it uses the macro true
from stdbool.h. So in order to make this compile, we need to include a header file, which may or may not be inconvenient. In C++ this isn't an issue, since bool
exists as a primitive data type and true
is a language keyword.
Yet another disadvantage of this form is that it uses the C99 bool type, which is only available on modern compilers and not backwards compatible. Again, this is only an issue in C and not in C++.
So which form to use? Neither seems perfect. It is, as K&R already said back in the dark ages, a matter of personal preference.
Personally, I always use for(;;)
just to avoid the compiler/analyser warnings frequently generated by the other forms. But perhaps more importantly because of this:
If even a C beginner knows that for(;;)
means an eternal loop, then who are you trying to make the code more readable for?
I guess that's what it all really boils down to. If you find yourself trying to make your source code readable for non-programmers, who don't even know the fundamental parts of the programming language, then you are only wasting time. They should not be reading your code.
And since everyone who should be reading your code already knows what for(;;)
means, there is no point in making it further readable - it is already as readable as it gets.
for 32-bit Python, the installer is here. after you run the installer, you will have easy_install.exe
in your \Python27\Scripts
directory
if you are looking for 64-bit installers, this is an excellent resource:
http://www.lfd.uci.edu/~gohlke/pythonlibs/
the author has installers for both Setuptools and Distribute. Either one will give you easy_install.exe
If you are going to display this tree on the GUI, you can use TreeView and TreeNode. (I suppose technically you can create a TreeNode without putting it on a GUI, but it does have more overhead than a simple homegrown TreeNode implementation.)
What you are using is called a list comprehension in Python, not an inline for-loop (even though it is similar to one). You would write your loop as a list comprehension like so:
p = [q.index(v) if v in q else 99999 for v in vm]
When using a list comprehension, you do not call list.append
because the list is being constructed from the comprehension itself. Each item in the list will be what is returned by the expression on the left of the for
keyword, which in this case is q.index(v) if v in q else 99999
. Incidentially, if you do use list.append
inside a comprehension, then you will get a list of None
values because that is what the append
method always returns.
We have just uploaded AmbilWarna color picker to Maven:
https://github.com/yukuku/ambilwarna
It can be used either as a dialog or as a Preference entry.
Start up R in a fresh session and paste this in:
library(ggplot2)
df <- structure(list(year = c(1, 2, 3, 4), pollution = structure(c(346.82,
134.308821199349, 130.430379885892, 88.275457392443), .Dim = 4L, .Dimnames = list(
c("1999", "2002", "2005", "2008")))), .Names = c("year",
"pollution"), row.names = c(NA, -4L), class = "data.frame")
df[] <- lapply(df, as.numeric) # make all columns numeric
ggplot(df, aes(year, pollution)) +
geom_point() +
geom_line() +
labs(x = "Year",
y = "Particulate matter emissions (tons)",
title = "Motor vehicle emissions in Baltimore")
I solved this by putting the ImageButton
and TextView
inside a LinearLayout
with vertical orientation. Works great!
<LinearLayout
android:id="@+id/linLayout"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageButton
android:id="@+id/camera_ibtn"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_gravity="center"
android:background="@drawable/camera" />
<TextView
android:id="@+id/textView2"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:gravity="center"
android:text="@string/take_pic"
android:textColor="#FFFFFF"
android:textStyle="bold" />
</LinearLayout>
If you attach the same event handler to several events, you often run into the issue of more than one of them firing at once (e.g. user presses tab after editing; keydown, change, and blur might all fire).
It sounds like what you actually want is something like this:
$('#ValidatedInput').keydown(function(evt) {
// If enter is pressed
if (evt.keyCode === 13) {
evt.preventDefault();
// If changes have been made to the input's value,
// blur() will result in a change event being fired.
this.blur();
}
});
$('#ValidatedInput').change(function(evt) {
var valueToValidate = this.value;
// Your validation callback/logic here.
});
You could do it this way:
-- Notice how STATE got moved inside the condition:
CASE WHEN STATE = 2 AND RetailerProcessType IN (1, 2) THEN '"AUTHORISED"'
WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'
ELSE '"DECLINED"'
END
The reason you can do an AND
here is that you are not checking the CASE
of STATE
, but instead you are CASING Conditions.
The key part here is that the STATE
condition is a part of the WHEN
.
Keep in mind that readonly only applies to the value itself, so if you're using a reference type readonly only protects the reference from being change. The state of the instance is not protected by readonly.
Since PyCharm 3.4 the path tab in the 'Project Interpreter' settings has been replaced. In order to add paths to a project you need to select the cogwheel, click on 'More...' and then select the "Show path for the selected interpreter" icon. This allows you to add paths to your project as before.
My project is now behaving as I would expect.
If you don't have an id on the image but have a parent div this is also a technique you can use.
<div id="myDiv"><img src="http://www.example.com/image.png"></div>
var myVar = document.querySelectorAll('#myDiv img')[0].src
Use Date.Add
and add a New TimeSpan
with the new time you want to add
DateTime dt = DateTime.Now
dt.Date.Add(new TimeSpan(12,15,00))
I used a simpler solution found partly here:
How to sort details with Date and time in sql server ?
I used this query to get my results:
SELECT TOP (5) * FROM My_Table_Name WHERE id=WhateverValueINeed ORDER BY DateTimeColumnName DESC
This is more straight forward and worked for me.
Notice: the column of the Date has the "datetime" type
If you know the size use this
No temporary variable used just to store user input
int main()
{
cout << "Hello World!\n";
int n;//input size
cin >> n;
vector<int>a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
//to verify output user input printed below
for (auto x : a) {
cout << x << " ";
}
return 0;
}
[x for x in L if 'ab' in x]
I'm working with an embedded version of the V8 Engine. I've tested a single string. Pushing each step 1000 characters. UTF-8.
First test with single byte (8bit, ANSI) Character "A" (hex: 41). Second test with two byte character (16bit) "O" (hex: CE A9) and the third test with three byte character (24bit) "?" (hex: E2 98 BA).
In all three cases the device prints out of memory at 888 000 characters and using ca. 26 348 kb in RAM.
Result: The characters are not dynamically stored. And not with only 16bit. - Ok, perhaps only for my case (Embedded 128 MB RAM Device, V8 Engine C++/QT) - The character encoding has nothing to do with the size in ram of the javascript engine. E.g. encodingURI, etc. is only useful for highlevel data transmission and storage.
Embedded or not, fact is that the characters are not only stored in 16bit. Unfortunally I've no 100% answer, what Javascript do at low level area. Btw. I've tested the same (first test above) with an array of character "A". Pushed 1000 items every step. (Exactly the same test. Just replaced string to array) And the system bringt out of memory (wanted) after 10 416 KB using and array length of 1 337 000. So, the javascript engine is not simple restricted. It's a kind more complex.
Just iterate and add:
for(Map.Entry e : a.entrySet())
if(!b.containsKey(e.getKey())
b.put(e.getKey(), e.getValue());
Edit to add:
If you can make changes to a, you can also do:
a.putAll(b)
and a will have exactly what you need. (all the entries in b
and all the entries in a
that aren't in b
)
best solution TNX to Drew Chapin and all of you too:
I just want to add that if you don't inheritently know the name of a domain controller, you can get the closest one, pass it's hostname to the -Server argument.
$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite
Get-ADUser -Server $dc.HostName[0] `
-Filter { EmailAddress -Like "*Smith_Karla*" } `
-Properties EmailAddress
my script:
$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite
Get-ADUser -Server $dc.HostName[0] ` -Filter { EmailAddress -Like "*Smith_Karla*" } ` -Properties EmailAddress | Export-CSV "C:\Scripts\Email.csv
Since you don't care which id to return I stick with MAX id for each email to simplify SQL query, give it a try
;WITH ue(id)
AS
(
SELECT MAX(id)
FROM table
GROUP BY email
)
SELECT * FROM table t
INNER JOIN ue ON ue.id = t.id
1. NSTemporaryDirectory() gives this:
/Users/spokaneDude/Library/Developer/CoreSimulator/Devices/1EE69744-255A-45CD-88F1-63FEAD117B32/data/Containers/Data/Application/199B1ACA-A80B-44BD-8E5E-DDF3DCF0D8D9/tmp
2. remove "/tmp" replacing it with "/Library/Application Support/<app name>/" --> is where the .sqlite files reside
I think CAST(ROUND(yourColumn,2) as varchar)
should do the job.
But why do you want to do this presentational formatting in T-SQL?
ports:
expose:
I found a post on the Eclipse forums that solved this problem for me.
This is my way of doing this, i use setTimeout:
var timer = {
running: false,
iv: 5000,
timeout: false,
cb : function(){},
start : function(cb,iv){
var elm = this;
clearInterval(this.timeout);
this.running = true;
if(cb) this.cb = cb;
if(iv) this.iv = iv;
this.timeout = setTimeout(function(){elm.execute(elm)}, this.iv);
},
execute : function(e){
if(!e.running) return false;
e.cb();
e.start();
},
stop : function(){
this.running = false;
},
set_interval : function(iv){
clearInterval(this.timeout);
this.start(false, iv);
}
};
Usage:
timer.start(function(){
console.debug('go');
}, 2000);
timer.set_interval(500);
timer.stop();
I haven't figured out yet why this occurs, but I had classes that were in my App_Code
folder that were calling methods in each other, and were fine in doing this when I built a .NET 4.5.2 project, but then I had to revert it to 4.0 as the target server wasn't getting upgraded. That's when I found this problem (after fixing the langversion
in my web.config from 6 to 5... another story)....
One of my methods kept having an error like:
The type X.Y conflicts with the imported type X.Y in MyProject.DLL
All of my classes were already set to "Compile" in their properties, as suggested on the accepted answer here, and each had a common namespace that was the same, and each had using MyNamespace;
at the top of each class.
I found that if I just moved the offending classes that had to call methods in each other to another, standard folder named something other than "App_Code", they stopped having this conflict issue.
Note: If you create a standard folder called "AppCode", move your classes into it, delete the "App_Code" folder, then rename "AppCode" to "App_Code", your problems will return. It doesn't matter if you use the "New Folder" or "Add ASP .NET Folder" option to create "App_Code" - it seems to key in on the name.
Maybe this is just a .NET 4.0 (and possibly earlier) issue... I was just fine in 4.5.2 before having to revert!
Think about it. When your client makes a GET request to an URI X, what it's saying to the server is: "I want a representation of the resource located at X, and this operation shouldn't change anything on the server." A PUT request is saying: "I want you to replace whatever is the resource located at X with the new entity I'm giving you on the body of this request". A DELETE request is saying: "I want you to delete whatever is the resource located at X". A PATCH is saying "I'm giving you this diff, and you should try to apply it to the resource at X and tell me if it succeeds." But a POST is saying: "I'm sending you this data subordinated to the resource at X, and we have a previous agreement on what you should do with it."
If you don't have it documented somewhere that the resource expects a POST and does something with it, it doesn't make sense to send a POST to it expecting it to act like a GET.
REST relies on the standardized behavior of the underlying protocol, and POST is precisely the method used for an action that isn't standardized. The result of a GET, PUT and DELETE requests are clearly defined in the standard, but POST isn't. The result of a POST is subordinated to the server, so if it's not documented that you can use POST to do something, you have to assume that you can't.
I was using a .Net Core 2.1 API with the [FromBody]
attribute and I had to use the following solution to successfully Post to it:
_apiClient = new HttpClient();
_apiClient.BaseAddress = new Uri(<YOUR API>);
var MyObject myObject = new MyObject(){
FirstName = "Me",
LastName = "Myself"
};
var stringified = JsonConvert.SerializeObject(myObject);
var result = await _apiClient.PostAsync("api/appusers", new StringContent(stringified, Encoding.UTF8, "application/json"));
You don't need to use GROUP BY but using it won't change the outcome. Just add an ORDER BY line at the end to sort your results.
SELECT player_name, player_salary, SUM(player_salary*1.1) AS NewSalary
FROM players
GROUP BY player_salary, player_name;
ORDER BY SUM(player_salary*1.1) DESC
For temporary internal files their are 2 options
1.
File file;
file = File.createTempFile(filename, null, this.getCacheDir());
2.
File file
file = new File(this.getCacheDir(), filename);
Both options adds files in the applications cache directory and thus can be cleared to make space as required but option 1 will add a random number on the end of the filename to keep files unique. It will also add a file extension which is .tmp
by default, but it can be set to anything via the use of the 2nd parameter. The use of the random number means despite specifying a filename it doesn't stay the same as the number is added along with the suffix/file extension (.tmp
by default) e.g you specify your filename as internal_file
and comes out as internal_file1456345.tmp
. Whereas you can specify the extension you can't specify the number that is added. You can however find the filename it generates via file.getName();
, but you would need to store it somewhere so you can use it whenever you wanted for example to delete or read the file. Therefore for this reason I prefer the 2nd option as the filename you specify is the filename that is created.
Neither one is better in that they may be used for different purposes. onClick
(should actually be onclick
) performs very slightly better, but I highly doubt you will notice a difference there.
It is worth noting that they do different things: .click
can be bound to any jQuery collection whereas onclick
has to be used inline on the elements you want it to be bound to. You can also bind only one event to using onclick
, whereas .click
lets you continue to bind events.
In my opinion, I would be consistent about it and just use .click
everywhere and keep all of my JavaScript code together and separated from the HTML.
Don't use onclick
. There isn't any reason to use it unless you know what you're doing, and you probably don't.
As I find it best to explain by example and none of the answers seem to do that...
A practical example of using reflections would be a Java Language Server written in Java or a PHP Language Server written in PHP, etc. Language Server gives your IDE abilities like autocomplete, jump to definition, context help, hinting types and more. In order to have all tag names (words that can be autocompleted) to show all the possible matches as you type the Language Server has to inspect everything about the class including doc blocks and private members. For that it needs a reflection of said class.
A different example would be a unit-test of a private method. One way to do so is to create a reflection and change the method's scope to public in the test's set-up phase. Of course one can argue private methods shouldn't be tested directly but that's not the point.
I found this problem when trying to run the Notepadv3 programme from Googles 'first lesson'..
For me it was an issue with the xml file, due to the API level I was using. I renamed each case of Match_Parent to the older type of Fill_Parent. Oh and if you have already auto-built the project then you need to delete 'import android.R' on NoteEdit.java and Notepadv3.java, clean the project (click 'Project', then 'clean...') before saving.
Solved it for me. Came from this post Android NDK r4 san-angeles problem
Can't believe Google dosen't warn of this problem - I have been setting up another PC to start programming again and even with a bit of prior knowledge this was a pain.. How do you set the API when importing an existing project??? Can't see where there is any dialogue option when you 'File' 'Import' etc ..
Scamparelli
In order to export out the VAR variable first the most logical and seems working way is to source the variable:
. ./export.bash
or
source ./export.bash
Now when echoing from main shell it works
echo $VAR
HELLO, VARABLE
We will now reset VAR
export VAR=""
echo $VAR
Now we will execute a script to source the variable then unset it :
./test-export.sh
HELLO, VARABLE
--
.
the code: cat test-export.sh
#!/bin/bash
# Source env variable
source ./export.bash
# echo out the variable in test script
echo $VAR
# unset the variable
unset VAR
# echo a few dotted lines
echo "---"
# now return VAR which is blank
echo $VAR
Here is one way
PLEASE NOTE: The exports are limited to the script that execute the exports in your main console - so as far as a cron job I would add it like the console like below... for the command part still questionable: here is how you would run in from your shell:
On your command prompt (so long as the export.bash has multiple echo values)
IFS=$'\n'; for entries in $(./export.bash); do export $entries; done; ./v1.sh
HELLO THERE
HI THERE
cat v1.sh
#!/bin/bash
echo $VAR
echo $VAR1
Now so long as this is for your usage - you could make the variables available for your scripts at any time by doing a bash alias like this:
myvars ./v1.sh
HELLO THERE
HI THERE
echo $VAR
.
add this to your .bashrc
function myvars() {
IFS=$'\n';
for entries in $(./export.bash); do export $entries; done;
"$@";
for entries in $(./export.bash); do variable=$(echo $entries|awk -F"=" '{print $1}'); unset $variable;
done
}
source your bashrc file and you can do like above any time ...
Anyhow back to the rest of it..
This has made it available globally then executed the script..
simply echo it out then run export on the echo !
cat export.bash
#!/bin/bash
echo "VAR=HELLO THERE"
Now within script or your console run:
export "$(./export.bash)"
Try:
echo $VAR
HELLO THERE
Multiple values so long as you know what you are expecting in another script using above method:
cat export.bash
#!/bin/bash
echo "VAR=HELLO THERE"
echo "VAR1=HI THERE"
cat test-export.sh
#!/bin/bash
IFS=$'\n'
for entries in $(./export.bash); do
export $entries
done
echo "round 1"
echo $VAR
echo $VAR1
for entries in $(./export.bash); do
variable=$(echo $entries|awk -F"=" '{print $1}');
unset $variable
done
echo "round 2"
echo $VAR
echo $VAR1
Now the results
./test-export.sh
round 1
HELLO THERE
HI THERE
round 2
.
and the final final update to auto assign read the VARIABLES:
./test-export.sh
Round 0 - Export out then find variable name -
Set current variable to the variable exported then echo its value
$VAR has value of HELLO THERE
$VAR1 has value of HI THERE
round 1 - we know what was exported and we will echo out known variables
HELLO THERE
HI THERE
Round 2 - We will just return the variable names and unset them
round 3 - Now we get nothing back
The script: cat test-export.sh
#!/bin/bash
IFS=$'\n'
echo "Round 0 - Export out then find variable name - "
echo "Set current variable to the variable exported then echo its value"
for entries in $(./export.bash); do
variable=$(echo $entries|awk -F"=" '{print $1}');
export $entries
eval current_variable=\$$variable
echo "\$$variable has value of $current_variable"
done
echo "round 1 - we know what was exported and we will echo out known variables"
echo $VAR
echo $VAR1
echo "Round 2 - We will just return the variable names and unset them "
for entries in $(./export.bash); do
variable=$(echo $entries|awk -F"=" '{print $1}');
unset $variable
done
echo "round 3 - Now we get nothing back"
echo $VAR
echo $VAR1
I would use a listener. Fragment1 calling the listener (main activity)
You need to add target for that button.
myButton.addTarget(self, action: #selector(ClassName.FunctionName(_:), forControlEvents: .TouchUpInside)
FunctionName: connected // for example
And of course you need to set tag of that button since you are using it.
myButton.tag = indexPath.row
You can achieve this by subclassing UITableViewCell. Use it in interface builder, drop a button on that cell, connect it via outlet and there you go.
To get the tag in the connected function:
func connected(sender: UIButton) {
let buttonTag = sender.tag
// Do any additional setup
}
just type
attrib -h -r -s /s /d j:*.*
where j is the drive letter... unlocks all the locked stuff in j drive
if u want to make it specific..then go to a specific location using cmd and then type
attrib -h -r -s /s /d "foldername"
it can also be used to lock drives or folders just alter "-" with "+"
attrib +h +r +s /s /d "foldername"
Echoing text that contains line breaks is fine, and there's no limit on the amount of text or lines you can echo at once (save for available memory).
The error in your code is caused by the unescaped single quotes which appear in the string.
See this line:
$('input_6').hint('ex: [email protected]');
You'd need to escape those single quotes in a PHP string whether it's a single line or not.
There is another good way to echo large strings, though, and that's to close the PHP block and open it again later:
if (is_single()) {
?>
<link type="text/css" rel="stylesheet" href="http://jotform.com/css/styles/form.css"/><style type="text/css">
.form-label{
width:150px !important;
}
.form-label-left{
width:150px !important;
}
.form-line{
padding:10px;
}
.form-label-right{
width:150px !important;
}
body, html{
margin:0;
padding:0;
background:false;
}
.form-all{
margin:0px auto;
padding-top:20px;
width:650px !important;
color:Black;
font-family:Verdana;
font-size:12px;
}
</style>
<link href="http://jotform.com/css/calendarview.css" rel="stylesheet" type="text/css" />
<script src="http://jotform.com/js/prototype.js" type="text/javascript"></script>
<script src="http://jotform.com/js/protoplus.js" type="text/javascript"></script>
<script src="http://jotform.com/js/protoplus-ui.js" type="text/javascript"></script>
<script src="http://jotform.com/js/jotform.js?v3" type="text/javascript"></script>
<script src="http://jotform.com/js/location.js" type="text/javascript"></script>
<script src="http://jotform.com/js/calendarview.js" type="text/javascript"></script>
<script type="text/javascript">
JotForm.init(function(){
$('input_6').hint('ex: [email protected]');
});
</script>
<?php
}else {
}
Or another alternative, which is probably better for readability, is to put all that static HTML into another page and include() it.
In My case the issue was fixed by changing the solution platform from AnyCPU to x86.